1 # Copyright 2019 ZTE Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
21 from django.db.models import Q
22 from requests.auth import HTTPBasicAuth
23 from rest_framework import status
25 import catalog.pub.utils.timeutil
26 from catalog.packages import const
27 from catalog.packages.serializers.vnf_pkg_notifications import PkgChangeNotificationSerializer, \
28 PkgOnboardingNotificationSerializer
29 from catalog.pub.config import config as pub_config
30 from catalog.pub.database.models import VnfPackageModel, VnfPkgSubscriptionModel, NsdmSubscriptionModel
31 from catalog.pub.utils.values import remove_none_key
33 logger = logging.getLogger(__name__)
36 class NotificationsUtil(object):
37 def __init__(self, notification_type):
38 self.notification_type = notification_type
39 self.notifyserializer = None
41 def prepare_notification(self, **kwargs):
44 def send_notification(self):
45 notification = self.prepare_notification()
47 subscriptions_filter = {v + "__contains": notification[k] for k, v in self.filter.items()}
48 subscriptions_filter = remove_none_key(subscriptions_filter)
49 logger.debug('send_notification subscriptions_filter = %s' % subscriptions_filter)
52 for k, v in subscriptions_filter.items():
53 q1.children.append((k, v))
55 subscriptions = self.SubscriptionModel.objects.filter(q1)
56 if not subscriptions.exists():
57 logger.info("No subscriptions created for the filter %s" % notification)
59 logger.info("Start sending notifications")
60 for sub in subscriptions:
62 notification["subscriptionId"] = sub.get_subscription_id()
63 notification['_links']['subscription'] = {
64 'href': '%s/%s%s' % (pub_config.MSB_BASE_URL, self.subscription_root_uri, notification["subscriptionId"])
66 callbackuri = sub.callback_uri
68 auth_info = json.loads(sub.auth_info)
69 if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
72 if self.notifyserializer:
73 serialized_data = self.notifyserializer(data=notification)
74 if not serialized_data.is_valid():
75 logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
78 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
80 self.post_notification(callbackuri, notification)
82 def post_notification(self, callbackuri, notification, auth_info=None):
85 if const.BASIC in auth_info.get("authType", ''):
86 params = auth_info.get("paramsBasic", {})
87 username = params.get("userName")
88 password = params.get("password")
89 resp = requests.post(callbackuri,
90 data=json.dumps(notification),
91 headers={'Connection': 'close',
92 'content-type': 'application/json',
93 'accept': 'application/json'},
94 auth=HTTPBasicAuth(username, password),
96 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
103 resp = requests.post(callbackuri,
104 data=json.dumps(notification),
105 headers={'Connection': 'close',
106 'content-type': 'application/json',
107 'accept': 'application/json'},
110 if resp.status_code == status.HTTP_204_NO_CONTENT:
111 logger.info("Sending notification to %s successfully.", callbackuri)
113 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
115 logger.error("Post notification failed.")
116 logger.error(traceback.format_exc())
119 class PkgNotifications(NotificationsUtil):
120 def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
121 super(PkgNotifications, self).__init__(notification_type)
124 'vnfPkgId': 'vnf_pkg_id'
126 self.vnf_pkg_id = vnf_pkg_id
127 self.change_type = change_type
128 self.operational_state = operational_state
129 self.SubscriptionModel = VnfPkgSubscriptionModel
130 self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
131 if self.notification_type == "VnfPackageChangeNotification":
132 self.notifyserializer = PkgChangeNotificationSerializer
134 self.notifyserializer = PkgOnboardingNotificationSerializer
136 def prepare_notification(self):
137 logger.info('Start to prepare Pkgnotification')
139 vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
142 vnfd_id = vnf_pkg[0].vnfdId
143 notification_content = {
144 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
145 'notificationType': self.notification_type,
146 # set 'subscriptionId' after filtering for subscribers
147 'timeStamp': catalog.pub.utils.timeutil.now_time(),
148 'vnfPkgId': self.vnf_pkg_id,
152 'href': '%s/%s/vnf_packages/%s' % (pub_config.MSB_BASE_URL, const.PKG_URL_PREFIX, self.vnf_pkg_id)
157 if self.notification_type == "VnfPackageChangeNotification":
158 notification_content['changeType'] = self.change_type
159 notification_content['operationalState'] = self.operational_state
161 return notification_content
164 class NsdNotifications(NotificationsUtil):
165 def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
166 super(NsdNotifications, self).__init__(notification_type)
168 'nsdInfoId': 'nsdInfoId',
171 self.SubscriptionModel = NsdmSubscriptionModel
172 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
173 self.nsd_info_id = nsd_info_id
175 self.failure_details = failure_details
176 self.operational_state = operational_state
178 # if self.notification_type == "VnfPackageChangeNotification":
179 # self.notifyserializer = PkgChangeNotificationSerializer
181 # self.notifyserializer = PkgOnboardingNotificationSerializer
183 def prepare_notification(self):
184 logger.info('Start to prepare Nsdnotification')
186 notification_content = {
187 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
188 'notificationType': self.notification_type,
189 # set 'subscriptionId' after filtering for subscribers
190 'timeStamp': catalog.pub.utils.timeutil.now_time(),
191 'nsdInfoId': self.nsd_info_id,
192 'nsdId': self.nsd_id,
195 'href': '%s/%s/ns_descriptors/%s' % (pub_config.MSB_BASE_URL, const.NSD_URL_PREFIX, self.nsd_info_id)
199 if self.notification_type == "NsdOnboardingFailureNotification":
200 notification_content['onboardingFailureDetails'] = self.failure_details
201 if self.notification_type == "NsdChangeNotification":
202 notification_content['nsdOperationalState'] = self.operational_state
203 return notification_content
206 class PnfNotifications(NotificationsUtil):
207 def __init__(self, notification_type, pnfd_info_id, pnfd_id, failure_details=None):
208 super(PnfNotifications, self).__init__(notification_type)
211 'pnfdInfoIds': 'pnfdInfoIds',
213 self.SubscriptionModel = NsdmSubscriptionModel
214 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
215 self.pnfd_info_id = pnfd_info_id
216 self.pnfd_id = pnfd_id
217 self.failure_details = failure_details
219 # if self.notification_type == "VnfPackageChangeNotification":
220 # self.notifyserializer = PkgChangeNotificationSerializer
222 # self.notifyserializer = PkgOnboardingNotificationSerializer
224 def prepare_notification(self, *args, **kwargs):
225 logger.info('Start to prepare Pnfnotification')
226 notification_content = {
227 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
228 'notificationType': self.notification_type,
229 # set 'subscriptionId' after filtering for subscribers
230 'timeStamp': catalog.pub.utils.timeutil.now_time(),
231 'pnfdInfoIds': self.pnfd_info_id,
232 'pnfdId': self.pnfd_id,
235 'href': '%s/%s/pnf_descriptors/%s' % (pub_config.MSB_BASE_URL,
236 const.NSD_URL_PREFIX,
241 if self.notification_type == "PnfdOnboardingFailureNotification":
242 notification_content['onboardingFailureDetails'] = self.failure_details
243 return notification_content