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': 'http://%s:%s/%s%s' % (pub_config.MSB_SERVICE_IP,
65 pub_config.MSB_SERVICE_PORT,
66 self.subscription_root_uri,
67 notification["subscriptionId"])
69 callbackuri = sub.callback_uri
71 auth_info = json.loads(sub.auth_info)
72 if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
75 if self.notifyserializer:
76 serialized_data = self.notifyserializer(data=notification)
77 if not serialized_data.is_valid():
78 logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
81 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
83 self.post_notification(callbackuri, notification)
85 def post_notification(self, callbackuri, notification, auth_info=None):
88 if const.BASIC in auth_info.get("authType", ''):
89 params = auth_info.get("paramsBasic", {})
90 username = params.get("userName")
91 password = params.get("password")
92 resp = requests.post(callbackuri,
93 data=json.dumps(notification),
94 headers={'Connection': 'close',
95 'content-type': 'application/json',
96 'accept': 'application/json'},
97 auth=HTTPBasicAuth(username, password),
99 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
106 resp = requests.post(callbackuri,
107 data=json.dumps(notification),
108 headers={'Connection': 'close',
109 'content-type': 'application/json',
110 'accept': 'application/json'},
113 if resp.status_code == status.HTTP_204_NO_CONTENT:
114 logger.info("Sending notification to %s successfully.", callbackuri)
116 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
118 logger.error("Post notification failed.")
119 logger.error(traceback.format_exc())
122 class PkgNotifications(NotificationsUtil):
123 def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
124 super(PkgNotifications, self).__init__(notification_type)
127 'vnfPkgId': 'vnf_pkg_id'
129 self.vnf_pkg_id = vnf_pkg_id
130 self.change_type = change_type
131 self.operational_state = operational_state
132 self.SubscriptionModel = VnfPkgSubscriptionModel
133 self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
134 if self.notification_type == "VnfPackageChangeNotification":
135 self.notifyserializer = PkgChangeNotificationSerializer
137 self.notifyserializer = PkgOnboardingNotificationSerializer
139 def prepare_notification(self):
140 logger.info('Start to prepare Pkgnotification')
142 vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
145 vnfd_id = vnf_pkg[0].vnfdId
146 notification_content = {
147 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
148 'notificationType': self.notification_type,
149 # set 'subscriptionId' after filtering for subscribers
150 'timeStamp': catalog.pub.utils.timeutil.now_time(),
151 'vnfPkgId': self.vnf_pkg_id,
155 'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
156 pub_config.MSB_SERVICE_PORT,
157 const.PKG_URL_PREFIX,
163 if self.notification_type == "VnfPackageChangeNotification":
164 notification_content['changeType'] = self.change_type
165 notification_content['operationalState'] = self.operational_state
167 return notification_content
170 class NsdNotifications(NotificationsUtil):
171 def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
172 super(NsdNotifications, self).__init__(notification_type)
174 'nsdInfoId': 'nsdInfoId',
177 self.SubscriptionModel = NsdmSubscriptionModel
178 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
179 self.nsd_info_id = nsd_info_id
181 self.failure_details = failure_details
182 self.operational_state = operational_state
184 # if self.notification_type == "VnfPackageChangeNotification":
185 # self.notifyserializer = PkgChangeNotificationSerializer
187 # self.notifyserializer = PkgOnboardingNotificationSerializer
189 def prepare_notification(self):
190 logger.info('Start to prepare Nsdnotification')
192 notification_content = {
193 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
194 'notificationType': self.notification_type,
195 # set 'subscriptionId' after filtering for subscribers
196 'timeStamp': catalog.pub.utils.timeutil.now_time(),
197 'nsdInfoId': self.nsd_info_id,
198 'nsdId': self.nsd_id,
201 'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
202 pub_config.MSB_SERVICE_PORT,
203 const.NSD_URL_PREFIX,
208 if self.notification_type == "NsdOnboardingFailureNotification":
209 notification_content['onboardingFailureDetails'] = self.failure_details
210 if self.notification_type == "NsdChangeNotification":
211 notification_content['nsdOperationalState'] = self.operational_state
212 return notification_content
215 class PnfNotifications(NotificationsUtil):
216 def __init__(self, notification_type, pnfd_info_id, pnfd_id, failure_details=None):
217 super(PnfNotifications, self).__init__(notification_type)
220 'pnfdInfoIds': 'pnfdInfoIds',
222 self.SubscriptionModel = NsdmSubscriptionModel
223 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
224 self.pnfd_info_id = pnfd_info_id
225 self.pnfd_id = pnfd_id
226 self.failure_details = failure_details
228 # if self.notification_type == "VnfPackageChangeNotification":
229 # self.notifyserializer = PkgChangeNotificationSerializer
231 # self.notifyserializer = PkgOnboardingNotificationSerializer
233 def prepare_notification(self, *args, **kwargs):
234 logger.info('Start to prepare Pnfnotification')
235 notification_content = {
236 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
237 'notificationType': self.notification_type,
238 # set 'subscriptionId' after filtering for subscribers
239 'timeStamp': catalog.pub.utils.timeutil.now_time(),
240 'pnfdInfoIds': self.pnfd_info_id,
241 'pnfdId': self.pnfd_id,
244 'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
245 pub_config.MSB_SERVICE_PORT,
246 const.NSD_URL_PREFIX,
251 if self.notification_type == "PnfdOnboardingFailureNotification":
252 notification_content['onboardingFailureDetails'] = self.failure_details
253 return notification_content