1. fix the url of links in VNF
[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': 'http://%s:%s/%s%s' % (pub_config.MSB_SERVICE_IP,
65                                                pub_config.MSB_SERVICE_PORT,
66                                                self.subscription_root_uri,
67                                                notification["subscriptionId"])
68             }
69             callbackuri = sub.callback_uri
70             """
71             auth_info = json.loads(sub.auth_info)
72             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
73                 pass
74             """
75             if self.notifyserializer:
76                 serialized_data = self.notifyserializer(data=notification)
77                 if not serialized_data.is_valid():
78                     logger.error('Notification Data is invalid:%s.' % serialized_data.errors)
79
80             if sub.auth_info:
81                 self.post_notification(callbackuri, notification, auth_info=json.loads(sub.auth_info))
82             else:
83                 self.post_notification(callbackuri, notification)
84
85     def post_notification(self, callbackuri, notification, auth_info=None):
86         try:
87             if auth_info:
88                 if const.BASIC in auth_info.get("authType", ''):
89                     params = auth_info.get("paramsBasic", {})
90                     username = params.get("userName")
91                     password = params.get("password")
92                     resp = requests.post(callbackuri,
93                                          data=json.dumps(notification),
94                                          headers={'Connection': 'close',
95                                                   'content-type': 'application/json',
96                                                   'accept': 'application/json'},
97                                          auth=HTTPBasicAuth(username, password),
98                                          verify=False)
99                 elif const.OAUTH2_CLIENT_CREDENTIALS in auth_info.get("authType", ''):
100                     # todo
101                     pass
102                 else:
103                     # todo
104                     pass
105             else:
106                 resp = requests.post(callbackuri,
107                                      data=json.dumps(notification),
108                                      headers={'Connection': 'close',
109                                               'content-type': 'application/json',
110                                               'accept': 'application/json'},
111                                      verify=False)
112
113             if resp.status_code == status.HTTP_204_NO_CONTENT:
114                 logger.info("Sending notification to %s successfully.", callbackuri)
115             else:
116                 logger.error("Sending notification to %s failed: %s" % (callbackuri, resp))
117         except:
118             logger.error("Post notification failed.")
119             logger.error(traceback.format_exc())
120
121
122 class PkgNotifications(NotificationsUtil):
123     def __init__(self, notification_type, vnf_pkg_id, change_type=None, operational_state=None):
124         super(PkgNotifications, self).__init__(notification_type)
125         self.filter = {
126             'vnfdId': 'vnfd_id',
127             'vnfPkgId': 'vnf_pkg_id'
128         }
129         self.vnf_pkg_id = vnf_pkg_id
130         self.change_type = change_type
131         self.operational_state = operational_state
132         self.SubscriptionModel = VnfPkgSubscriptionModel
133         self.subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
134         if self.notification_type == "VnfPackageChangeNotification":
135             self.notifyserializer = PkgChangeNotificationSerializer
136         else:
137             self.notifyserializer = PkgOnboardingNotificationSerializer
138
139     def prepare_notification(self):
140         logger.info('Start to prepare Pkgnotification')
141
142         vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=self.vnf_pkg_id)
143         vnfd_id = None
144         if vnf_pkg:
145             vnfd_id = vnf_pkg[0].vnfdId
146         notification_content = {
147             'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
148             'notificationType': self.notification_type,
149             # set 'subscriptionId' after filtering for subscribers
150             'timeStamp': catalog.pub.utils.timeutil.now_time(),
151             'vnfPkgId': self.vnf_pkg_id,
152             'vnfdId': vnfd_id,
153             '_links': {
154                 'vnfPackage': {
155                     'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
156                                                                  pub_config.MSB_SERVICE_PORT,
157                                                                  const.PKG_URL_PREFIX,
158                                                                  self.vnf_pkg_id)
159                 }
160             }
161         }
162
163         if self.notification_type == "VnfPackageChangeNotification":
164             notification_content['changeType'] = self.change_type
165             notification_content['operationalState'] = self.operational_state
166
167         return notification_content
168
169
170 class NsdNotifications(NotificationsUtil):
171     def __init__(self, notification_type, nsd_info_id, nsd_id, failure_details=None, operational_state=None):
172         super(NsdNotifications, self).__init__(notification_type)
173         self.filter = {
174             'nsdInfoId': 'nsdInfoId',
175             'nsdId': 'nsdId',
176         }
177         self.SubscriptionModel = NsdmSubscriptionModel
178         self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
179         self.nsd_info_id = nsd_info_id
180         self.nsd_id = nsd_id
181         self.failure_details = failure_details
182         self.operational_state = operational_state
183         # todo:
184         # if self.notification_type == "VnfPackageChangeNotification":
185         #     self.notifyserializer = PkgChangeNotificationSerializer
186         # else:
187         #     self.notifyserializer = PkgOnboardingNotificationSerializer
188
189     def prepare_notification(self):
190         logger.info('Start to prepare Nsdnotification')
191
192         notification_content = {
193             'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
194             'notificationType': self.notification_type,
195             # set 'subscriptionId' after filtering for subscribers
196             'timeStamp': catalog.pub.utils.timeutil.now_time(),
197             'nsdInfoId': self.nsd_info_id,
198             'nsdId': self.nsd_id,
199             '_links': {
200                 'nsdInfo': {
201                     'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
202                                                                    pub_config.MSB_SERVICE_PORT,
203                                                                    const.NSD_URL_PREFIX,
204                                                                    self.nsd_info_id)
205                 }
206             }
207         }
208         if self.notification_type == "NsdOnboardingFailureNotification":
209             notification_content['onboardingFailureDetails'] = self.failure_details
210         if self.notification_type == "NsdChangeNotification":
211             notification_content['nsdOperationalState'] = self.operational_state
212         return notification_content
213
214
215 class PnfNotifications(NotificationsUtil):
216     def __init__(self, notification_type, pnfd_info_id, pnfd_id, failure_details=None):
217         super(PnfNotifications, self).__init__(notification_type)
218         self.filter = {
219             'pnfdId': 'pnfdId',
220             'pnfdInfoIds': 'pnfdInfoIds',
221         }
222         self.SubscriptionModel = NsdmSubscriptionModel
223         self.subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
224         self.pnfd_info_id = pnfd_info_id
225         self.pnfd_id = pnfd_id
226         self.failure_details = failure_details
227         # todo
228         # if self.notification_type == "VnfPackageChangeNotification":
229         #     self.notifyserializer = PkgChangeNotificationSerializer
230         # else:
231         #     self.notifyserializer = PkgOnboardingNotificationSerializer
232
233     def prepare_notification(self, *args, **kwargs):
234         logger.info('Start to prepare Pnfnotification')
235         notification_content = {
236             'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
237             'notificationType': self.notification_type,
238             # set 'subscriptionId' after filtering for subscribers
239             'timeStamp': catalog.pub.utils.timeutil.now_time(),
240             'pnfdInfoIds': self.pnfd_info_id,
241             'pnfdId': self.pnfd_id,
242             '_links': {
243                 'pnfdInfo': {
244                     'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
245                                                                     pub_config.MSB_SERVICE_PORT,
246                                                                     const.NSD_URL_PREFIX,
247                                                                     self.pnfd_info_id)
248                 }
249             }
250         }
251         if self.notification_type == "PnfdOnboardingFailureNotification":
252             notification_content['onboardingFailureDetails'] = self.failure_details
253         return notification_content