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