Fix for ETSI Catalog Manager does not support HTTPS for Test Notification Endpoint...
[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 logging
16 import uuid
17 import requests
18 import json
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
26 import traceback
27 from django.db.models import Q
28 from catalog.packages.serializers.vnf_pkg_notifications import PkgChangeNotificationSerializer, \
29     PkgOnboardingNotificationSerializer
30
31 logger = logging.getLogger(__name__)
32
33
34 class NotificationsUtil(object):
35     def __init__(self, notification_type):
36         self.notification_type = notification_type
37         self.notifyserializer = None
38
39     def prepare_notification(self, **kwargs):
40         pass
41
42     def send_notification(self):
43         notification = self.prepare_notification()
44
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)
48         q1 = Q()
49         q1.connector = 'OR'
50         for k, v in subscriptions_filter.items():
51             q1.children.append((k, v))
52
53         subscriptions = self.SubscriptionModel.objects.filter(q1)
54         if not subscriptions.exists():
55             logger.info("No subscriptions created for the filter %s" % notification)
56             return
57         logger.info("Start sending notifications")
58         for sub in subscriptions:
59             # set subscription id
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"])
66             }
67             callbackuri = sub.callback_uri
68             """
69             auth_info = json.loads(sub.auth_info)
70             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
71                 pass
72             """
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)
77
78             if sub.auth_info:
79                 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
80             else:
81                 self.post_notification(callbackuri, notification)
82
83     def post_notification(self, callbackuri, notification, auth_info=None):
84         try:
85             if auth_info:
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,
91                                          data=notification,
92                                          headers={'Connection': 'close',
93                                                   'content-type': 'application/json',
94                                                   'accept': 'application/json'},
95                                          auth=HTTPBasicAuth(username, password),
96                                          verify=False)
97                 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
98                     # todo
99                     pass
100                 else:
101                     # todo
102                     pass
103             else:
104                 resp = requests.post(callbackuri,
105                                      data=notification,
106                                      headers={'Connection': 'close',
107                                               'content-type': 'application/json',
108                                               'accept': 'application/json'},
109                                      verify=False)
110
111             if resp.status_code == status.HTTP_204_NO_CONTENT:
112                 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
113             else:
114                 logger.info("Sending notification to %s successfully.", callbackuri)
115         except:
116             logger.error("Post notification failed.")
117             logger.error(traceback.format_exc())
118
119
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)
123         self.filter = {
124             'vnfdId': 'vnfd_id',
125             'vnfPkgId': 'vnf_pkg_id'
126         }
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
134         else:
135             self.notifyserializer = PkgOnboardingNotificationSerializer
136
137     def prepare_notification(self):
138         logger.info('Start to prepare Pkgnotification')
139
140         vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
141         vnfd_id = None
142         if vnf_pkg:
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,
150             'vnfdId': vnfd_id,
151             '_links': {
152                 'vnfPackage': {
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,
156                                                                  self.vnf_pkg_id)
157                 }
158             }
159         }
160
161         if self.notification_type == "VnfPackageChangeNotification":
162             notification_content['changeType'] = self.change_type
163             notification_content['operationalState'] = self.operational_state
164
165         return notification_content
166
167
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)
171         self.filter = {
172             'nsdInfoId': 'nsdInfoId',
173             'nsdId': 'nsdId',
174         }
175         self.SubscriptionModel = NsdmSubscriptionModel
176         self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
177         self.nsd_info_id = nsd_info_id
178         self.nsd_id = nsd_id
179         self.failure_details = failure_details
180         self.operational_state = operational_state
181         # todo:
182         # if self.notification_type == "VnfPackageChangeNotification":
183         #     self.notifyserializer = PkgChangeNotificationSerializer
184         # else:
185         #     self.notifyserializer = PkgOnboardingNotificationSerializer
186
187     def prepare_notification(self):
188         logger.info('Start to prepare Nsdnotification')
189
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,
197             '_links': {
198                 'nsdInfo': {
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,
202                                                                    self.nsd_info_id)
203                 }
204             }
205         }
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
211
212
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)
216         self.filter = {
217             'pnfdId': 'pnfdId',
218             'pnfdInfoIds': 'pnfdInfoIds',
219         }
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
225         # todo
226         # if self.notification_type == "VnfPackageChangeNotification":
227         #     self.notifyserializer = PkgChangeNotificationSerializer
228         # else:
229         #     self.notifyserializer = PkgOnboardingNotificationSerializer
230
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,
240             '_links': {
241                 'pnfdInfo': {
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,
245                                                                     self.pnfd_info_id)
246                 }
247             }
248         }
249         if self.notification_type == "PnfdOnboardingFailureNotification":
250             notification_content['onboardingFailureDetails'] = self.failure_details
251         return notification_content