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.database.models import VnfPackageModel, VnfPkgSubscriptionModel, NsdmSubscriptionModel
30 from catalog.pub.utils.values import remove_none_key
32 logger = logging.getLogger(__name__)
35 class NotificationsUtil(object):
36 def __init__(self, notification_type):
37 self.notification_type = notification_type
38 self.notifyserializer = None
40 def prepare_notification(self, **kwargs):
43 def send_notification(self):
44 notification = self.prepare_notification()
46 subscriptions_filter = {v + "__contains": notification[k] for k, v in self.filter.items()}
47 subscriptions_filter = remove_none_key(subscriptions_filter)
48 logger.debug('send_notification subscriptions_filter = %s' % subscriptions_filter)
51 for k, v in subscriptions_filter.items():
52 q1.children.append((k, v))
54 subscriptions = self.SubscriptionModel.objects.filter(q1)
55 if not subscriptions.exists():
56 logger.info("No subscriptions created for the filter %s" % notification)
58 logger.info("Start sending notifications")
59 for sub in subscriptions:
61 notification["subscriptionId"] = sub.get_subscription_id()
62 notification['_links']['subscription'] = {
63 'href': '/%s%s' % (self.subscription_root_uri, notification["subscriptionId"])
65 callbackuri = sub.callback_uri
67 auth_info = json.loads(sub.auth_info)
68 if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
71 if self.notifyserializer:
72 serialized_data = self.notifyserializer(data=notification)
73 if not serialized_data.is_valid():
74 logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
77 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
79 self.post_notification(callbackuri, notification)
81 def post_notification(self, callbackuri, notification, auth_info=None):
84 if const.BASIC in auth_info.get("authType", ''):
85 params = auth_info.get("paramsBasic", {})
86 username = params.get("userName")
87 password = params.get("password")
88 resp = requests.post(callbackuri,
89 data=json.dumps(notification),
90 headers={'Connection': 'close',
91 'content-type': 'application/json',
92 'accept': 'application/json'},
93 auth=HTTPBasicAuth(username, password),
95 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
102 resp = requests.post(callbackuri,
103 data=json.dumps(notification),
104 headers={'Connection': 'close',
105 'content-type': 'application/json',
106 'accept': 'application/json'},
109 if resp.status_code == status.HTTP_204_NO_CONTENT:
110 logger.info("Sending notification to %s successfully.", callbackuri)
112 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
114 logger.error("Post notification failed.")
115 logger.error(traceback.format_exc())
118 class PkgNotifications(NotificationsUtil):
119 def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
120 super(PkgNotifications, self).__init__(notification_type)
123 'vnfPkgId': 'vnf_pkg_id'
125 self.vnf_pkg_id = vnf_pkg_id
126 self.change_type = change_type
127 self.operational_state = operational_state
128 self.SubscriptionModel = VnfPkgSubscriptionModel
129 self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
130 if self.notification_type == "VnfPackageChangeNotification":
131 self.notifyserializer = PkgChangeNotificationSerializer
133 self.notifyserializer = PkgOnboardingNotificationSerializer
135 def prepare_notification(self):
136 logger.info('Start to prepare Pkgnotification')
138 vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
141 vnfd_id = vnf_pkg[0].vnfdId
142 notification_content = {
143 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
144 'notificationType': self.notification_type,
145 # set 'subscriptionId' after filtering for subscribers
146 'timeStamp': catalog.pub.utils.timeutil.now_time(),
147 'vnfPkgId': self.vnf_pkg_id,
151 'href': '/%s/vnf_packages/%s' % (const.PKG_URL_PREFIX, self.vnf_pkg_id)
156 if self.notification_type == "VnfPackageChangeNotification":
157 notification_content['changeType'] = self.change_type
158 notification_content['operationalState'] = self.operational_state
160 return notification_content
163 class NsdNotifications(NotificationsUtil):
164 def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
165 super(NsdNotifications, self).__init__(notification_type)
167 'nsdInfoId': 'nsdInfoId',
170 self.SubscriptionModel = NsdmSubscriptionModel
171 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
172 self.nsd_info_id = nsd_info_id
174 self.failure_details = failure_details
175 self.operational_state = operational_state
177 # if self.notification_type == "VnfPackageChangeNotification":
178 # self.notifyserializer = PkgChangeNotificationSerializer
180 # self.notifyserializer = PkgOnboardingNotificationSerializer
182 def prepare_notification(self):
183 logger.info('Start to prepare Nsdnotification')
185 notification_content = {
186 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
187 'notificationType': self.notification_type,
188 # set 'subscriptionId' after filtering for subscribers
189 'timeStamp': catalog.pub.utils.timeutil.now_time(),
190 'nsdInfoId': self.nsd_info_id,
191 'nsdId': self.nsd_id,
194 'href': '/%s/ns_descriptors/%s' % (
195 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/pnf_descriptors/%s' % (const.NSD_URL_PREFIX,
240 if self.notification_type == "PnfdOnboardingFailureNotification":
241 notification_content['onboardingFailureDetails'] = self.failure_details
242 return notification_content