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.
19 from rest_framework import status
20 from requests.auth import HTTPBasicAuth
21 from catalog.packages import const
22 from catalog.pub.database.models import VnfPackageModel, VnfPkgSubscriptionModel, NsdmSubscriptionModel
23 import catalog.pub.utils.timeutil
24 from catalog.pub.utils.values import remove_none_key
25 from catalog.pub.config import config as pub_config
27 from django.db.models import Q
28 from catalog.packages.serializers.vnf_pkg_notifications import PkgChangeNotificationSerializer, \
29 PkgOnboardingNotificationSerializer
31 logger = logging.getLogger(__name__)
34 class NotificationsUtil(object):
35 def __init__(self, notification_type):
36 self.notification_type = notification_type
37 self.notifyserializer = None
39 def prepare_notification(self, **kwargs):
42 def send_notification(self):
43 notification = self.prepare_notification()
45 subscriptions_filter = {v + "__contains": notification[k] for k, v in self.filter.items()}
46 subscriptions_filter = remove_none_key(subscriptions_filter)
47 logger.debug('send_notification subscriptions_filter = %s' % subscriptions_filter)
50 for k, v in subscriptions_filter.items():
51 q1.children.append((k, v))
53 subscriptions = self.SubscriptionModel.objects.filter(q1)
54 if not subscriptions.exists():
55 logger.info("No subscriptions created for the filter %s" % notification)
57 logger.info("Start sending notifications")
58 for sub in subscriptions:
60 notification["subscriptionId"] = sub.get_subscription_id()
61 notification['_links']['subscription'] = {
62 'href': 'http://%s:%s/%s%s' % (pub_config.MSB_SERVICE_IP,
63 pub_config.MSB_SERVICE_PORT,
64 self.subscription_root_uri,
65 notification["subscriptionId"])
67 callbackuri = sub.callback_uri
69 auth_info = json.loads(sub.auth_info)
70 if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
73 if self.notifyserializer:
74 serialized_data = self.notifyserializer(data=notification)
75 if not serialized_data.is_valid():
76 logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
79 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
81 self.post_notification(callbackuri, notification)
83 def post_notification(self, callbackuri, notification, auth_info=None):
86 if const.BASIC in auth_info.get("authType", ''):
87 params = auth_info.get("paramsBasic", {})
88 username = params.get("userName")
89 password = params.get("password")
90 resp = requests.post(callbackuri,
92 headers={'Connection': 'close',
93 'content-type': 'application/json',
94 'accept': 'application/json'},
95 auth=HTTPBasicAuth(username, password),
97 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
104 resp = requests.post(callbackuri,
106 headers={'Connection': 'close',
107 'content-type': 'application/json',
108 'accept': 'application/json'},
111 if resp.status_code == status.HTTP_204_NO_CONTENT:
112 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
114 logger.info("Sending notification to %s successfully.", callbackuri)
116 logger.error("Post notification failed.")
117 logger.error(traceback.format_exc())
120 class PkgNotifications(NotificationsUtil):
121 def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
122 super(PkgNotifications, self).__init__(notification_type)
125 'vnfPkgId': 'vnf_pkg_id'
127 self.vnf_pkg_id = vnf_pkg_id
128 self.change_type = change_type
129 self.operational_state = operational_state
130 self.SubscriptionModel = VnfPkgSubscriptionModel
131 self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
132 if self.notification_type == "VnfPackageChangeNotification":
133 self.notifyserializer = PkgChangeNotificationSerializer
135 self.notifyserializer = PkgOnboardingNotificationSerializer
137 def prepare_notification(self):
138 logger.info('Start to prepare Pkgnotification')
140 vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
143 vnfd_id = vnf_pkg[0].vnfdId
144 notification_content = {
145 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
146 'notificationType': self.notification_type,
147 # set 'subscriptionId' after filtering for subscribers
148 'timeStamp': catalog.pub.utils.timeutil.now_time(),
149 'vnfPkgId': self.vnf_pkg_id,
153 'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
154 pub_config.MSB_SERVICE_PORT,
155 const.PKG_URL_PREFIX,
161 if self.notification_type == "VnfPackageChangeNotification":
162 notification_content['changeType'] = self.change_type
163 notification_content['operationalState'] = self.operational_state
165 return notification_content
168 class NsdNotifications(NotificationsUtil):
169 def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
170 super(NsdNotifications, self).__init__(notification_type)
172 'nsdInfoId': 'nsdInfoId',
175 self.SubscriptionModel = NsdmSubscriptionModel
176 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
177 self.nsd_info_id = nsd_info_id
179 self.failure_details = failure_details
180 self.operational_state = operational_state
182 # if self.notification_type == "VnfPackageChangeNotification":
183 # self.notifyserializer = PkgChangeNotificationSerializer
185 # self.notifyserializer = PkgOnboardingNotificationSerializer
187 def prepare_notification(self):
188 logger.info('Start to prepare Nsdnotification')
190 notification_content = {
191 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
192 'notificationType': self.notification_type,
193 # set 'subscriptionId' after filtering for subscribers
194 'timeStamp': catalog.pub.utils.timeutil.now_time(),
195 'nsdInfoId': self.nsd_info_id,
196 'nsdId': self.nsd_id,
199 'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
200 pub_config.MSB_SERVICE_PORT,
201 const.NSD_URL_PREFIX,
206 if self.notification_type == "NsdOnboardingFailureNotification":
207 notification_content['onboardingFailureDetails'] = self.failure_details
208 if self.notification_type == "NsdChangeNotification":
209 notification_content['nsdOperationalState'] = self.operational_state
210 return notification_content
213 class PnfNotifications(NotificationsUtil):
214 def __init__(self, notification_type, pnfd_info_id, pnfd_id, failure_details=None):
215 super(PnfNotifications, self).__init__(notification_type)
218 'pnfdInfoIds': 'pnfdInfoIds',
220 self.SubscriptionModel = NsdmSubscriptionModel
221 self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
222 self.pnfd_info_id = pnfd_info_id
223 self.pnfd_id = pnfd_id
224 self.failure_details = failure_details
226 # if self.notification_type == "VnfPackageChangeNotification":
227 # self.notifyserializer = PkgChangeNotificationSerializer
229 # self.notifyserializer = PkgOnboardingNotificationSerializer
231 def prepare_notification(self, *args, **kwargs):
232 logger.info('Start to prepare Pnfnotification')
233 notification_content = {
234 'id': str(uuid.uuid4()), # shall be the same if sent multiple times due to multiple subscriptions.
235 'notificationType': self.notification_type,
236 # set 'subscriptionId' after filtering for subscribers
237 'timeStamp': catalog.pub.utils.timeutil.now_time(),
238 'pnfdInfoIds': self.pnfd_info_id,
239 'pnfdId': self.pnfd_id,
242 'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
243 pub_config.MSB_SERVICE_PORT,
244 const.NSD_URL_PREFIX,
249 if self.notification_type == "PnfdOnboardingFailureNotification":
250 notification_content['onboardingFailureDetails'] = self.failure_details
251 return notification_content