93c26c762b575e946c9c119a65cf3100c0417ad8
[modeling/etsicatalog.git] / catalog / packages / biz / notificationsutil.py
1 # Copyright 2019 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import json
16 import logging
17 import traceback
18 import uuid
19
20 import requests
21 from django.db.models import Q
22 from requests.auth import HTTPBasicAuth
23 from rest_framework import status
24
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
31
32 logger = logging.getLogger(__name__)
33
34
35 class NotificationsUtil(object):
36     def __init__(self, notification_type):
37         self.notification_type = notification_type
38         self.notifyserializer = None
39
40     def prepare_notification(self, **kwargs):
41         pass
42
43     def send_notification(self):
44         notification = self.prepare_notification()
45
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)
49         q1 = Q()
50         q1.connector = 'OR'
51         for k, v in subscriptions_filter.items():
52             q1.children.append((k, v))
53
54         subscriptions = self.SubscriptionModel.objects.filter(q1)
55         if not subscriptions.exists():
56             logger.info("No subscriptions created for the filter %s" % notification)
57             return
58         logger.info("Start sending notifications")
59         for sub in subscriptions:
60             # set subscription id
61             notification["subscriptionId"] = sub.get_subscription_id()
62             notification['_links']['subscription'] = {
63                 'href': '/%s%s' % (self.subscription_root_uri, notification["subscriptionId"])
64             }
65             callbackuri = sub.callback_uri
66             """
67             auth_info = json.loads(sub.auth_info)
68             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
69                 pass
70             """
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)
75
76             if sub.auth_info:
77                 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
78             else:
79                 self.post_notification(callbackuri, notification)
80
81     def post_notification(self, callbackuri, notification, auth_info=None):
82         try:
83             if auth_info:
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),
94                                          verify=False)
95                 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
96                     # todo
97                     pass
98                 else:
99                     # todo
100                     pass
101             else:
102                 resp = requests.post(callbackuri,
103                                      data=json.dumps(notification),
104                                      headers={'Connection': 'close',
105                                               'content-type': 'application/json',
106                                               'accept': 'application/json'},
107                                      verify=False)
108
109             if resp.status_code == status.HTTP_204_NO_CONTENT:
110                 logger.info("Sending notification to %s successfully.", callbackuri)
111             else:
112                 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
113         except:
114             logger.error("Post notification failed.")
115             logger.error(traceback.format_exc())
116
117
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)
121         self.filter = {
122             'vnfdId': 'vnfd_id',
123             'vnfPkgId': 'vnf_pkg_id'
124         }
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
132         else:
133             self.notifyserializer = PkgOnboardingNotificationSerializer
134
135     def prepare_notification(self):
136         logger.info('Start to prepare Pkgnotification')
137
138         vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
139         vnfd_id = None
140         if vnf_pkg:
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,
148             'vnfdId': vnfd_id,
149             '_links': {
150                 'vnfPackage': {
151                     'href': '/%s/vnf_packages/%s' % (const.PKG_URL_PREFIX, self.vnf_pkg_id)
152                 }
153             }
154         }
155
156         if self.notification_type == "VnfPackageChangeNotification":
157             notification_content['changeType'] = self.change_type
158             notification_content['operationalState'] = self.operational_state
159
160         return notification_content
161
162
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)
166         self.filter = {
167             'nsdInfoId': 'nsdInfoId',
168             'nsdId': 'nsdId',
169         }
170         self.SubscriptionModel = NsdmSubscriptionModel
171         self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
172         self.nsd_info_id = nsd_info_id
173         self.nsd_id = nsd_id
174         self.failure_details = failure_details
175         self.operational_state = operational_state
176         # todo:
177         # if self.notification_type == "VnfPackageChangeNotification":
178         #     self.notifyserializer = PkgChangeNotificationSerializer
179         # else:
180         #     self.notifyserializer = PkgOnboardingNotificationSerializer
181
182     def prepare_notification(self):
183         logger.info('Start to prepare Nsdnotification')
184
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,
192             '_links': {
193                 'nsdInfo': {
194                     'href': '/%s/ns_descriptors/%s' % (
195                         const.NSD_URL_PREFIX, self.nsd_info_id)
196                 }
197             }
198         }
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
204
205
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)
209         self.filter = {
210             'pnfdId': 'pnfdId',
211             'pnfdInfoIds': 'pnfdInfoIds',
212         }
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
218         # todo
219         # if self.notification_type == "VnfPackageChangeNotification":
220         #     self.notifyserializer = PkgChangeNotificationSerializer
221         # else:
222         #     self.notifyserializer = PkgOnboardingNotificationSerializer
223
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,
233             '_links': {
234                 'pnfdInfo': {
235                     'href': '/%s/pnf_descriptors/%s' % (const.NSD_URL_PREFIX,
236                                                         self.pnfd_info_id)
237                 }
238             }
239         }
240         if self.notification_type == "PnfdOnboardingFailureNotification":
241             notification_content['onboardingFailureDetails'] = self.failure_details
242         return notification_content