31760ccbb3d06a937806d70b44bb286d1fa6c6c9
[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.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
32
33 logger = logging.getLogger(__name__)
34
35
36 class NotificationsUtil(object):
37     def __init__(self, notification_type):
38         self.notification_type = notification_type
39         self.notifyserializer = None
40
41     def prepare_notification(self, **kwargs):
42         pass
43
44     def send_notification(self):
45         notification = self.prepare_notification()
46
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)
50         q1 = Q()
51         q1.connector = 'OR'
52         for k, v in subscriptions_filter.items():
53             q1.children.append((k, v))
54
55         subscriptions = self.SubscriptionModel.objects.filter(q1)
56         if not subscriptions.exists():
57             logger.info("No subscriptions created for the filter %s" % notification)
58             return
59         logger.info("Start sending notifications")
60         for sub in subscriptions:
61             # set subscription id
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"])
65             }
66             callbackuri = sub.callback_uri
67             """
68             auth_info = json.loads(sub.auth_info)
69             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
70                 pass
71             """
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)
76
77             if sub.auth_info:
78                 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
79             else:
80                 self.post_notification(callbackuri, notification)
81
82     def post_notification(self, callbackuri, notification, auth_info=None):
83         try:
84             if auth_info:
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),
95                                          verify=False)
96                 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
97                     # todo
98                     pass
99                 else:
100                     # todo
101                     pass
102             else:
103                 resp = requests.post(callbackuri,
104                                      data=json.dumps(notification),
105                                      headers={'Connection': 'close',
106                                               'content-type': 'application/json',
107                                               'accept': 'application/json'},
108                                      verify=False)
109
110             if resp.status_code == status.HTTP_204_NO_CONTENT:
111                 logger.info("Sending notification to %s successfully.", callbackuri)
112             else:
113                 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
114         except:
115             logger.error("Post notification failed.")
116             logger.error(traceback.format_exc())
117
118
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)
122         self.filter = {
123             'vnfdId': 'vnfd_id',
124             'vnfPkgId': 'vnf_pkg_id'
125         }
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
133         else:
134             self.notifyserializer = PkgOnboardingNotificationSerializer
135
136     def prepare_notification(self):
137         logger.info('Start to prepare Pkgnotification')
138
139         vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
140         vnfd_id = None
141         if vnf_pkg:
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,
149             'vnfdId': vnfd_id,
150             '_links': {
151                 'vnfPackage': {
152                     'href': '%s/%s/vnf_packages/%s' % (pub_config.MSB_BASE_URL, const.PKG_URL_PREFIX, self.vnf_pkg_id)
153                 }
154             }
155         }
156
157         if self.notification_type == "VnfPackageChangeNotification":
158             notification_content['changeType'] = self.change_type
159             notification_content['operationalState'] = self.operational_state
160
161         return notification_content
162
163
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)
167         self.filter = {
168             'nsdInfoId': 'nsdInfoId',
169             'nsdId': 'nsdId',
170         }
171         self.SubscriptionModel = NsdmSubscriptionModel
172         self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
173         self.nsd_info_id = nsd_info_id
174         self.nsd_id = nsd_id
175         self.failure_details = failure_details
176         self.operational_state = operational_state
177         # todo:
178         # if self.notification_type == "VnfPackageChangeNotification":
179         #     self.notifyserializer = PkgChangeNotificationSerializer
180         # else:
181         #     self.notifyserializer = PkgOnboardingNotificationSerializer
182
183     def prepare_notification(self):
184         logger.info('Start to prepare Nsdnotification')
185
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,
193             '_links': {
194                 'nsdInfo': {
195                     'href': '%s/%s/ns_descriptors/%s' % (pub_config.MSB_BASE_URL, 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/%s/pnf_descriptors/%s' % (pub_config.MSB_BASE_URL,
236                                                           const.NSD_URL_PREFIX,
237                                                           self.pnfd_info_id)
238                 }
239             }
240         }
241         if self.notification_type == "PnfdOnboardingFailureNotification":
242             notification_content['onboardingFailureDetails'] = self.failure_details
243         return notification_content