2de67ca739a236a7965daafeeb3857477169713d
[vfc/nfvo/lcm.git] / lcm / ns_vnfs / biz / subscribe.py
1 # Copyright 2018 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
18 from lcm.pub.database.models import SubscriptionModel
19 from lcm.pub.exceptions import NSLCMException
20 from lcm.pub.msapi.extsys import get_vnfm_by_id
21 from lcm.pub.utils.restcall import req_by_msb
22 from lcm.pub.utils.values import ignore_case_get
23 from lcm.pub.config import config as pub_config
24
25 logger = logging.getLogger(__name__)
26
27
28 class SubscriptionCreation(object):
29     def __init__(self, data):
30         self.data = data
31         self.vnf_instance_id = self.data['vnfInstanceId']
32         self.vnfm_id = self.data['vnfmId']
33         self.subscription_request_data = {}
34         self.subscription_response_data = {}
35         pass
36
37     def do_biz(self):
38         logger.debug('Start subscribing...')
39         self.prepare_lccn_subscription_request_data()
40         self.send_subscription_request()
41         self.save_subscription_response_data()
42         logger.debug('Subscribing has completed.')
43
44     def prepare_lccn_subscription_request_data(self):
45         vnfm_info = get_vnfm_by_id(self.vnfm_id)
46         call_back = "http://%s:%s/api/gvnfmdriver/v1/vnfs/lifecyclechangesnotification" % (pub_config.MSB_SERVICE_IP, pub_config.MSB_SERVICE_PORT)
47         self.subscription_request_data = {
48             "filter": {
49                 "notificationTypes": ["VnfLcmOperationOccurrenceNotification"],
50                 "operationTypes": [
51                     "INSTANTIATE",
52                     "SCALE",
53                     "SCALE_TO_LEVEL",
54                     "CHANGE_FLAVOUR",
55                     "TERMINATE",
56                     "HEAL",
57                     "OPERATE",
58                     "CHANGE_EXT_CONN",
59                     "MODIFY_INFO"
60                 ],
61                 "operationStates": [
62                     "STARTING",
63                     "PROCESSING",
64                     "COMPLETED",
65                     "FAILED_TEMP",
66                     "FAILED",
67                     "ROLLING_BACK",
68                     "ROLLED_BACK"
69                 ],
70                 "vnfInstanceSubscriptionFilter": {
71                     # "vnfdIds": [],
72                     "vnfInstanceIds": [self.vnf_instance_id],
73                     # "vnfInstanceNames": [],
74                     # "vnfProductsFromProviders": {}
75                 }
76             },
77             "callbackUri": call_back,  # TODO: need reconfirming
78             "authentication": {
79                 "authType": ["BASIC"],
80                 "paramsBasic": {
81                     # "userName": vnfm_info['userName'],
82                     # "password": vnfm_info['password']
83                 }
84             }
85         }
86         if vnfm_info['userName']:
87             self.subscription_request_data["authentication"]["paramsBasic"]["userName"] = vnfm_info['userName']
88         if vnfm_info['password']:
89             self.subscription_request_data["authentication"]["paramsBasic"]["password"] = vnfm_info['password']
90
91     def send_subscription_request(self):
92         ret = req_by_msb('api/gvnfmdriver/v1/%s/subscriptions' % self.vnfm_id, 'POST', json.JSONEncoder().encode(self.subscription_request_data))
93         if ret[0] != 0:
94             logger.error("Status code is %s, detail is %s.", ret[2], ret[1])
95             raise NSLCMException("Failed to subscribe from vnfm(%s)." % self.vnfm_id)
96         self.subscription_response_data = json.JSONDecoder().decode(ret[1])
97
98     def save_subscription_response_data(self):
99         logger.debug("Save subscription[%s] to the database" % self.subscription_response_data['id'])
100         lccn_filter = self.subscription_response_data['filter']
101         SubscriptionModel.objects.create(
102             subscription_id=self.subscription_response_data['id'],
103             notification_types=json.dumps(lccn_filter['notificationTypes']),
104             operation_types=json.dumps(lccn_filter['operationTypes']),
105             operation_states=json.dumps(lccn_filter['operationStates']),
106             vnf_instance_filter=json.dumps(lccn_filter['vnfInstanceSubscriptionFilter']),
107             callback_uri=self.subscription_response_data['callbackUri'],
108             links=json.dumps(self.subscription_response_data['_links'])
109         )
110         logger.debug('Subscription[%s] has been created', self.subscription_response_data['id'])
111
112
113 class SubscriptionDeletion(object):
114     def __init__(self, vnfm_id, vnf_instance_id):
115         self.vnfm_id = vnfm_id
116         self.vnf_instance_id = vnf_instance_id
117         self.subscription_id = None
118         self.subscription = None
119
120     def do_biz(self):
121         self.filter_subscription()
122         self.send_subscription_deletion_request()
123         self.delete_subscription_in_db()
124
125     def filter_subscription(self):
126         subscritptions = SubscriptionModel.objects.filter(vnf_instance_filter__contains=self.vnf_instance_id)
127         if not subscritptions.exists():
128             logger.debug("Subscription contains VNF(%s) does not exist." % self.vnf_instance_id)
129         self.subscription = subscritptions.first()
130
131     def send_subscription_deletion_request(self):
132         if self.subscription:
133             self.subscription_id = ignore_case_get(self.subscription.__dict__, 'id')
134             ret = req_by_msb('api/gvnfmdriver/v1/%s/subscriptions/%s' % (self.vnfm_id, self.subscription_id), 'DELETE')
135             if ret[0] != 0:
136                 logger.error('Status code is %s, detail is %s.', ret[2], ret[1])
137                 raise NSLCMException("Failed to subscribe from vnfm(%s)." % self.vnfm_id)
138             logger.debug('Subscripton(%s) in vnfm(%s) has been deleted.' % (self.subscription, self.vnfm_id))
139
140     def delete_subscription_in_db(self):
141         if self.subscription:
142             self.subscription.delete()