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