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