Refactor codes for notification
[vfc/gvnfm/vnflcm.git] / lcm / lcm / pub / utils / notificationsutil.py
1 # Copyright (C) 2018 Verizon. All Rights Reserved
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 uuid
18
19 import requests
20 from requests.auth import HTTPBasicAuth
21 from rest_framework import status
22
23 from lcm.nf import const
24 from lcm.pub.database.models import SubscriptionModel
25 from lcm.pub.database.models import (
26     VmInstModel, NetworkInstModel,
27     PortInstModel, StorageInstModel, VNFCInstModel
28 )
29 from lcm.pub.utils.timeutil import now_time
30 from lcm.pub.utils.enumutil import enum
31
32 logger = logging.getLogger(__name__)
33
34 NOTIFY_TYPE = enum(lCM_OP_OCC="VnfLcmOperationOccurrenceNotification",
35                    CREATION="VnfIdentifierCreationNotification",
36                    DELETION="VnfIdentifierDeletionNotification")
37
38
39 class NotificationsUtil(object):
40     def __init__(self):
41         pass
42
43     def send_notification(self, notification):
44         logger.info("Send Notifications to the callbackUri")
45         filters = {
46             "operationState": "operation_states",
47             "operation": "operation_types"
48         }
49         subscriptions_filter = {v + "__contains": notification[k] for k, v in filters.iteritems()}
50
51         subscriptions = SubscriptionModel.objects.filter(**subscriptions_filter)
52         if not subscriptions.exists():
53             logger.info("No subscriptions created for the filters %s" % notification)
54             return
55         logger.info("Start sending notifications")
56         for subscription in subscriptions:
57             # set subscription id
58             notification["subscriptionId"] = subscription.subscription_id
59             notification['_links']['subscription'] = {
60                 'href': '/api/vnflcm/v1/subscriptions/%s' % subscription.subscription_id
61             }
62             callbackUri = subscription.callback_uri
63             auth_info = json.loads(subscription.auth_info)
64             if auth_info["authType"] != const.OAUTH2_CLIENT_CREDENTIALS:
65                 try:
66                     self.post_notification(callbackUri, auth_info, notification)
67                 except Exception as e:
68                     logger.error("Failed to post notification: %s", e.message)
69
70     def post_notification(self, callbackUri, auth_info, notification):
71         params = auth_info.get("paramsBasic", {})
72         username = params.get("userName")
73         password = params.get("password")
74         logger.info("Sending notification to %s", callbackUri)
75         resp = requests.post(callbackUri,
76                              data=notification,
77                              auth=HTTPBasicAuth(username, password))
78         if resp.status_code != status.HTTP_204_NO_CONTENT:
79             raise Exception("Notify %s failed: %s" % (callbackUri, resp.text))
80
81
82 def set_affected_vnfcs(affected_vnfcs, nfinstid, changetype):
83     vnfcs = VNFCInstModel.objects.filter(instid=nfinstid)
84     for vnfc in vnfcs:
85         vm_resource = {}
86         if vnfc.vmid:
87             vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
88             if vm:
89                 vm_resource = {
90                     'vimConnectionId': vm[0].vimid,
91                     'resourceId': vm[0].resourceid,
92                     'resourceProviderId': vm[0].vmname,  # TODO: is resourceName mapped to resourceProviderId?
93                     'vimLevelResourceType': 'vm'
94                 }
95         affected_vnfcs.append({
96             'id': vnfc.vnfcinstanceid,
97             'vduId': vnfc.vduid,
98             'changeType': changetype,
99             'computeResource': vm_resource
100         })
101     logger.debug("affected_vnfcs=%s", affected_vnfcs)
102     return affected_vnfcs
103
104
105 def set_affected_vls(affected_vls, nfinstid, changetype):
106     networks = NetworkInstModel.objects.filter(instid=nfinstid)
107     for network in networks:
108         network_resource = {
109             'vimConnectionId': network.vimid,
110             'resourceId': network.resourceid,
111             'resourceProviderId': network.name,  # TODO: is resourceName mapped to resourceProviderId?
112             'vimLevelResourceType': 'network'
113         }
114         affected_vls.append({
115             'id': network.networkid,
116             'virtualLinkDescId': network.nodeId,
117             'changeType': changetype,
118             'networkResource': network_resource
119         })
120     logger.debug("affected_vls=%s", affected_vls)
121
122
123 def set_ext_connectivity(ext_connectivity, nfinstid):
124     ext_connectivity_map = {}
125     ports = PortInstModel.objects.filter(instid=nfinstid)
126     for port in ports:
127         if port.networkid not in ext_connectivity_map:
128             ext_connectivity_map[port.networkid] = []
129         ext_connectivity_map[port.networkid].append({
130             'id': port.portid,  # TODO: port.portid or port.nodeid?
131             'resourceHandle': {
132                 'vimConnectionId': port.vimid,
133                 'resourceId': port.resourceid,
134                 'resourceProviderId': port.name,  # TODO: is resourceName mapped to resourceProviderId?
135                 'vimLevelResourceType': 'port'
136             },
137             'cpInstanceId': port.portid  # TODO: port.cpinstanceid is not initiated when create port resource.
138         })
139     for network_id, ext_link_ports in ext_connectivity_map.items():
140         networks = NetworkInstModel.objects.filter(networkid=network_id)
141         net_name = networks[0].name if networks else network_id
142         network_resource = {
143             'vimConnectionId': ext_link_ports[0]['resourceHandle']['vimConnectionId'],
144             'resourceId': network_id,
145             'resourceProviderId': net_name,  # TODO: is resourceName mapped to resourceProviderId?
146             'vimLevelResourceType': 'network'
147         }
148         ext_connectivity.append({
149             'id': network_id,
150             'resourceHandle': network_resource,
151             'extLinkPorts': ext_link_ports
152         })
153     logger.debug("ext_connectivity=%s", ext_connectivity)
154
155
156 def set_affected_vss(affected_vss, nfinstid, changetype):
157     vss = StorageInstModel.objects.filter(instid=nfinstid)
158     for vs in vss:
159         affected_vss.append({
160             'id': vs.storageid,
161             'virtualStorageDescId': vs.nodeId,
162             'changeType': changetype,
163             'storageResource': {
164                 'vimConnectionId': vs.vimid,
165                 'resourceId': vs.resourceid,
166                 'resourceProviderId': vs.name,  # TODO: is resourceName mapped to resourceProviderId?
167                 'vimLevelResourceType': 'volume'
168             }
169         })
170     logger.debug("affected_vss=%s", affected_vss)
171
172
173 def get_notification_status(operation_state):
174     notification_status = const.LCM_NOTIFICATION_STATUS.START
175     if operation_state in const.RESULT_RANGE:
176         notification_status = const.LCM_NOTIFICATION_STATUS.RESULT
177     return notification_status
178
179
180 def prepare_notification(nfinstid, jobid, operation, operation_state):
181     logger.info('Start to prepare notification')
182     notification_content = {
183         'id': str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
184         'notificationType': NOTIFY_TYPE.lCM_OP_OCC,
185         # set 'subscriptionId' after filtering for subscribers
186         'timeStamp': now_time(),
187         'notificationStatus': get_notification_status(operation_state),
188         'operationState': operation_state,
189         'vnfInstanceId': nfinstid,
190         'operation': operation,
191         'isAutomaticInvocation': False,
192         'vnfLcmOpOccId': jobid,
193         'affectedVnfcs': [],
194         'affectedVirtualLinks': [],
195         'affectedVirtualStorages': [],
196         'changedExtConnectivity': [],
197         'error': '',
198         '_links': {
199             'vnfInstance': {
200                 'href': '%s/vnf_instances/%s' % (const.URL_PREFIX, nfinstid)
201             },
202             'vnfLcmOpOcc': {
203                 'href': '%s/vnf_lcm_op_occs/%s' % (const.URL_PREFIX, jobid)
204             }
205         }
206     }
207     return notification_content
208
209
210 def prepare_notification_data(nfinstid, jobid, changetype, operation):
211     data = prepare_notification(nfinstid=nfinstid,
212                                 jobid=jobid,
213                                 operation=operation,
214                                 operation_state=const.OPERATION_STATE_TYPE.COMPLETED)
215
216     set_affected_vnfcs(data['affectedVnfcs'], nfinstid, changetype)
217     set_affected_vls(data['affectedVirtualLinks'], nfinstid, changetype)
218     set_affected_vss(data['affectedVirtualStorages'], nfinstid, changetype)
219     set_ext_connectivity(data['changedExtConnectivity'], nfinstid)
220
221     logger.debug('Notification content: %s' % data)
222     return data
223
224
225 def prepare_vnf_identifier_notification(notify_type, nfinstid):
226     data = {
227         "id": str(uuid.uuid4()),  # shall be the same if sent multiple times due to multiple subscriptions.
228         "notificationType": notify_type,
229         "timeStamp": now_time(),
230         "vnfInstanceId": nfinstid,
231         "_links": {
232             "vnfInstance": {
233                 'href': '%s/vnf_instances/%s' % (const.URL_PREFIX, nfinstid)
234             }
235         }
236     }
237
238     logger.debug('Vnf Identifier Notification: %s' % data)
239     return data