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