04bad4746d21f458411a577d302421c73a702ceb
[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 from rest_framework import status
19 from catalog.packages import const
20 from catalog.pub.database.models import VnfPkgSubscriptionModel, NsdmSubscriptionModel
21 from catalog.pub.database.models import VnfPackageModel
22 import catalog.pub.utils.timeutil
23 from catalog.pub.utils.values import remove_none_key
24 from catalog.pub.config import config as pub_config
25 import traceback
26
27 logger = logging.getLogger(__name__)
28
29
30 class NotificationsUtil(object):
31     def __init__(self):
32         pass
33
34     def send_notification(self, notification, filters, isvnfpkg):
35         logger.info("Send Notifications to the callbackUri")
36         subscriptions_filter = {v + "__contains": notification[k] for k, v in filters.items()}
37         logger.debug('send_notification subscriptions_filter = %s' % subscriptions_filter)
38         subscriptions_filter = remove_none_key(subscriptions_filter)
39         if isvnfpkg:
40             subscriptions = VnfPkgSubscriptionModel.objects.filter(**subscriptions_filter)
41             subscription_root_uri = const.VNFPKG_SUBSCRIPTION_ROOT_URI
42         else:
43             subscriptions = NsdmSubscriptionModel.objects.filter(**subscriptions_filter)
44             subscription_root_uri = const.NSDM_SUBSCRIPTION_ROOT_URI
45         if not subscriptions.exists():
46             logger.info("No subscriptions created for the filters %s" % notification)
47             return
48         logger.info("Start sending notifications")
49         for sub in subscriptions:
50             # set subscription id
51             if isvnfpkg:
52                 notification["subscriptionId"] = sub.subscription_id
53             else:
54                 notification["subscriptionId"] = sub.subscriptionid
55             notification['_links']['subscription'] = {
56                 'href': 'http://%s:%s/%s%s' % (pub_config.MSB_SERVICE_IP,
57                                                pub_config.MSB_SERVICE_PORT,
58                                                subscription_root_uri,
59                                                notification["subscriptionId"])
60             }
61             callbackuri = sub.callback_uri
62             """
63             auth_info = json.loads(sub.auth_info)
64             if auth_info["authType"] == const.OAUTH2_CLIENT_CREDENTIALS:
65                 pass
66             """
67             self.post_notification(callbackuri, notification)
68
69     def post_notification(self, callbackuri, notification):
70         """
71         params = auth_info.get("paramsBasic", {})
72         username, password = params.get("userName"), params.get("password")
73         logger.info("Sending notification to %s, %s", callbackuri, params)
74         resp = None
75         if username:
76             resp = requests.post(callbackuri,
77                                  data=notification,
78                                  auth=HTTPBasicAuth(username, password))
79         else:
80         """
81
82         try:
83             resp = requests.post(callbackuri, data=notification, headers={'Connection': 'close'})
84             if resp.status_code != status.HTTP_204_NO_CONTENT:
85                 logger.error("Sendingnotification to %s failed: %s" % (callbackuri, resp.text))
86             else:
87                 logger.info("Sending notification to %s successfully.", callbackuri)
88         except:
89             logger.error("Post notification failed.")
90             logger.error(traceback.format_exc())
91
92
93 def prepare_vnfpkg_notification(vnf_pkg_id, notification_type, pkg_change_type, operational_state):
94     logger.info('Start to prepare notification')
95     vnf_pkg = VnfPackageModel.objects.filter(vnfPackageId=vnf_pkg_id)
96     vnfd_id = None
97     if vnf_pkg:
98         vnfd_id = vnf_pkg[0].vnfdId
99     notification_content = {
100         'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
101         'notificationType': notification_type,
102         # set 'subscriptionId' after filtering for subscribers
103         'timeStamp': catalog.pub.utils.timeutil.now_time(),
104         'vnfPkgId': vnf_pkg_id,
105         'vnfdId': vnfd_id,
106         'changeType': pkg_change_type,
107         'operationalState': operational_state,
108         '_links': {
109             'vnfPackage': {
110                 'href': 'http://%s:%s/%s/vnf_packages/%s' % (pub_config.MSB_SERVICE_IP,
111                                                              pub_config.MSB_SERVICE_PORT,
112                                                              const.PKG_URL_PREFIX,
113                                                              vnf_pkg_id)
114             }
115         }
116     }
117     return notification_content
118
119
120 def prepare_nsd_notification(nsd_info_id, nsd_id, notification_type, failure_details=None, operational_state=None):
121     logger.info('Start to prepare notification')
122     notification_content = {
123         'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
124         'notificationType': notification_type,
125         # set 'subscriptionId' after filtering for subscribers
126         'timeStamp': catalog.pub.utils.timeutil.now_time(),
127         'nsdInfoId': nsd_info_id,
128         'nsdId': nsd_id,
129         'onboardingFailureDetails': failure_details,
130         'nsdOperationalState': operational_state,
131         '_links': {
132             'nsdInfo': {
133                 'href': 'http://%s:%s/%s/ns_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
134                                                                pub_config.MSB_SERVICE_PORT,
135                                                                const.NSD_URL_PREFIX,
136                                                                nsd_info_id)
137             }
138         }
139     }
140     return notification_content
141
142
143 def prepare_pnfd_notification(pnfd_info_id, pnfd_id, notification_type, failure_details=None):
144     logger.info('Start to prepare notification')
145     notification_content = {
146         'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
147         'notificationType': notification_type,
148         # set 'subscriptionId' after filtering for subscribers
149         'timeStamp': catalog.pub.utils.timeutil.now_time(),
150         'pnfdInfoIds': pnfd_info_id,
151         'pnfdId': pnfd_id,
152         'onboardingFailureDetails': failure_details,
153         '_links': {
154             'pnfdInfo': {
155                 'href': 'http://%s:%s/%s/pnf_descriptors/%s' % (pub_config.MSB_SERVICE_IP,
156                                                                 pub_config.MSB_SERVICE_PORT,
157                                                                 const.NSD_URL_PREFIX,
158                                                                 pnfd_info_id)
159             }
160         }
161     }
162     return notification_content