blob: 627d74b6a435c0eacb34e448fa066c867c6f11b9 [file] [log] [blame]
Bartek Grzybowskifbbdbec2019-09-25 16:37:05 +02001#!/usr/bin/env python
Kang Xi11d278c2018-04-06 16:56:04 -04002
3import sys
4import logging
5import requests
6import json
7from datetime import datetime
8import progressbar
9import time
10import csar_parser
11import preload
12from vcpecommon import *
13
14
15class SoUtils:
16 def __init__(self, vcpecommon, api_version):
17 """
18 :param vcpecommon:
19 :param api_version: must be 'v4' or 'v5'
20 """
Kang Xi268b74d2018-05-23 15:53:42 -040021 self.tmp_solution_for_so_bug = False
Kang Xi11d278c2018-04-06 16:56:04 -040022 self.logger = logging.getLogger(__name__)
23 self.vcpecommon = vcpecommon
24 if api_version not in self.vcpecommon.so_req_api_url:
25 self.logger.error('Incorrect SO API version: %s', api_version)
Bartek Grzybowski68d93c22019-10-30 10:55:55 +010026 sys.exit(1)
Kang Xi11d278c2018-04-06 16:56:04 -040027 self.service_req_api_url = self.vcpecommon.so_req_api_url[api_version]
Brian Freeman9b3d6ca2019-11-06 13:22:53 -050028 self.testApi = 'VNF_API'
Kang Xi11d278c2018-04-06 16:56:04 -040029
30 def submit_create_req(self, req_json, req_type, service_instance_id=None, vnf_instance_id=None):
31 """
32 POST {serverRoot}/serviceInstances/v4
33 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs
34 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/networks
35 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules
36 :param req_json:
37 :param service_instance_id: this is required only for networks, vnfs, and vf modules
38 :param req_type:
39 :param vnf_instance_id:
40 :return: req_id, instance_id
41 """
42 if req_type == 'service':
43 url = self.service_req_api_url
44 elif req_type == 'vnf':
45 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs'])
46 elif req_type == 'network':
47 url = '/'.join([self.service_req_api_url, service_instance_id, 'networks'])
48 elif req_type == 'vfmodule':
49 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs', vnf_instance_id, 'vfModules'])
50 else:
51 self.logger.error('Invalid request type: {0}. Can only be service/vnf/network/vfmodule'.format(req_type))
52 return None, None
53
Kang Xi268b74d2018-05-23 15:53:42 -040054 self.logger.info(url)
Kang Xi11d278c2018-04-06 16:56:04 -040055 r = requests.post(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass, json=req_json)
Kang Xi268b74d2018-05-23 15:53:42 -040056 self.logger.debug(r)
Kang Xi11d278c2018-04-06 16:56:04 -040057 response = r.json()
58
59 self.logger.debug('---------------------------------------------------------------')
60 self.logger.debug('------- Creation request submitted to SO, got response --------')
61 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
62 self.logger.debug('---------------------------------------------------------------')
63 req_id = response.get('requestReferences', {}).get('requestId', '')
64 instance_id = response.get('requestReferences', {}).get('instanceId', '')
Kang Xi268b74d2018-05-23 15:53:42 -040065
Kang Xi11d278c2018-04-06 16:56:04 -040066 return req_id, instance_id
67
68 def check_progress(self, req_id, eta=0, interval=5):
69 if not req_id:
70 self.logger.error('Error when checking SO request progress, invalid request ID: ' + req_id)
71 return False
72 duration = 0.0
73 bar = progressbar.ProgressBar(redirect_stdout=True)
74 url = self.vcpecommon.so_check_progress_api_url + '/' + req_id
75
76 while True:
77 time.sleep(interval)
78 r = requests.get(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass)
79 response = r.json()
80
81 duration += interval
82 if eta > 0:
83 percentage = min(95, 100 * duration / eta)
84 else:
85 percentage = int(response['request']['requestStatus']['percentProgress'])
86
87 if response['request']['requestStatus']['requestState'] == 'IN_PROGRESS':
88 self.logger.debug('------------------Request Status-------------------------------')
89 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
90 bar.update(percentage)
91 else:
92 self.logger.debug('---------------------------------------------------------------')
93 self.logger.debug('----------------- Creation Request Results --------------------')
94 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
95 self.logger.debug('---------------------------------------------------------------')
96 flag = response['request']['requestStatus']['requestState'] == 'COMPLETE'
97 if not flag:
98 self.logger.error('Request failed.')
99 self.logger.error(json.dumps(response, indent=4, sort_keys=True))
100 bar.update(100)
101 bar.finish()
102 return flag
103
104 def add_req_info(self, req_details, instance_name, product_family_id=None):
105 req_details['requestInfo'] = {
106 'instanceName': instance_name,
107 'source': 'VID',
108 'suppressRollback': 'true',
109 'requestorId': 'vCPE-Robot'
110 }
111 if product_family_id:
112 req_details['requestInfo']['productFamilyId'] = product_family_id
113
114 def add_related_instance(self, req_details, instance_id, instance_model):
115 instance = {"instanceId": instance_id, "modelInfo": instance_model}
116 if 'relatedInstanceList' not in req_details:
117 req_details['relatedInstanceList'] = [{"relatedInstance": instance}]
118 else:
119 req_details['relatedInstanceList'].append({"relatedInstance": instance})
120
121 def generate_vnf_or_network_request(self, req_type, instance_name, vnf_or_network_model, service_instance_id,
122 service_model):
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500123 if self.vcpecommon.gra_api_flag:
124 self.testApi = 'GR_API'
Kang Xi11d278c2018-04-06 16:56:04 -0400125 req_details = {
126 'modelInfo': vnf_or_network_model,
127 'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
128 "tenantId": self.vcpecommon.os_tenant_id},
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500129 'requestParameters': {
130 "userParams": [],
131 "testApi": self.testApi
132 },
Kang Xi268b74d2018-05-23 15:53:42 -0400133 'platform': {"platformName": "Platform-Demonstration"}
Kang Xi11d278c2018-04-06 16:56:04 -0400134 }
135 self.add_req_info(req_details, instance_name, self.vcpecommon.product_family_id)
136 self.add_related_instance(req_details, service_instance_id, service_model)
137 return {'requestDetails': req_details}
138
139 def generate_vfmodule_request(self, instance_name, vfmodule_model, service_instance_id,
140 service_model, vnf_instance_id, vnf_model):
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500141 if self.vcpecommon.gra_api_flag:
142 self.testApi = 'GR_API'
Kang Xi11d278c2018-04-06 16:56:04 -0400143 req_details = {
144 'modelInfo': vfmodule_model,
145 'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
146 "tenantId": self.vcpecommon.os_tenant_id},
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500147 'requestParameters': {
148 "usePreload": 'true',
149 "testApi": self.testApi
150 }
Kang Xi11d278c2018-04-06 16:56:04 -0400151 }
152 self.add_req_info(req_details, instance_name, self.vcpecommon.product_family_id)
153 self.add_related_instance(req_details, service_instance_id, service_model)
154 self.add_related_instance(req_details, vnf_instance_id, vnf_model)
155 return {'requestDetails': req_details}
156
157 def generate_service_request(self, instance_name, model):
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500158 if self.vcpecommon.gra_api_flag:
159 self.testApi = 'GR_API'
160
161 self.logger.info('testApi' + self.testApi)
162
Kang Xi11d278c2018-04-06 16:56:04 -0400163 req_details = {
164 'modelInfo': model,
165 'subscriberInfo': {'globalSubscriberId': self.vcpecommon.global_subscriber_id},
166 'requestParameters': {
167 "userParams": [],
168 "subscriptionServiceType": "vCPE",
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500169 "aLaCarte": 'true',
170 "testApi": self.testApi
Kang Xi11d278c2018-04-06 16:56:04 -0400171 }
172 }
173 self.add_req_info(req_details, instance_name)
Kang Xi268b74d2018-05-23 15:53:42 -0400174 self.add_project_info(req_details)
175 self.add_owning_entity(req_details)
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500176 self.logger.info(json.dumps(req_details, indent=2, sort_keys=True))
Kang Xi11d278c2018-04-06 16:56:04 -0400177 return {'requestDetails': req_details}
178
Kang Xi268b74d2018-05-23 15:53:42 -0400179 def add_project_info(self, req_details):
180 req_details['project'] = {'projectName': self.vcpecommon.project_name}
181
182 def add_owning_entity(self, req_details):
183 req_details['owningEntity'] = {'owningEntityId': self.vcpecommon.owning_entity_id,
184 'owningEntityName': self.vcpecommon.owning_entity_name}
185
Kang Xi11d278c2018-04-06 16:56:04 -0400186 def generate_custom_service_request(self, instance_name, model, brg_mac):
Yang Xu9f935b22018-11-22 10:56:52 -0500187 brg_mac_enc = brg_mac.replace(':', '-')
Kang Xi11d278c2018-04-06 16:56:04 -0400188 req_details = {
189 'modelInfo': model,
190 'subscriberInfo': {'subscriberName': 'Kaneohe',
191 'globalSubscriberId': self.vcpecommon.global_subscriber_id},
Brian Freeman8076a872018-11-13 11:34:48 -0500192 'cloudConfiguration': {"lcpCloudRegionId": 'RegionOne', #self.vcpecommon.os_region_name,
Kang Xi11d278c2018-04-06 16:56:04 -0400193 "tenantId": self.vcpecommon.os_tenant_id},
194 'requestParameters': {
195 "userParams": [
196 {
197 'name': 'BRG_WAN_MAC_Address',
198 'value': brg_mac
Yang Xu63a0afd2018-11-20 16:01:01 -0500199 },
200 {
201 'name': 'VfModuleNames',
202 'value': [
203 {
Yang Xu9f935b22018-11-22 10:56:52 -0500204 'VfModuleModelInvariantUuid': self.vcpecommon.vgw_VfModuleModelInvariantUuid,
205 'VfModuleName': 'VGW2BRG-{0}'.format(brg_mac_enc)
Yang Xu63a0afd2018-11-20 16:01:01 -0500206 }
207 ]
208 },
Kang Xi268b74d2018-05-23 15:53:42 -0400209 {
210 "name": "Customer_Location",
211 "value": self.vcpecommon.customer_location_used_by_oof
212 },
213 {
214 "name": "Homing_Solution",
215 "value": self.vcpecommon.homing_solution
216 }
Kang Xi11d278c2018-04-06 16:56:04 -0400217 ],
218 "subscriptionServiceType": "vCPE",
219 'aLaCarte': 'false'
220 }
221 }
222 self.add_req_info(req_details, instance_name, self.vcpecommon.custom_product_family_id)
Kang Xi268b74d2018-05-23 15:53:42 -0400223 self.add_project_info(req_details)
224 self.add_owning_entity(req_details)
Kang Xi11d278c2018-04-06 16:56:04 -0400225 return {'requestDetails': req_details}
226
227 def create_custom_service(self, csar_file, brg_mac, name_suffix=None):
228 parser = csar_parser.CsarParser()
229 if not parser.parse_csar(csar_file):
230 return False
231
232 # yyyymmdd_hhmm
233 if not name_suffix:
234 name_suffix = '_' + datetime.now().strftime('%Y%m%d%H%M')
235
236 # create service
237 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
Yang Xu9eae1542018-11-27 13:00:05 -0500238 parser.svc_model['modelName'][0:10], name_suffix])
Kang Xi11d278c2018-04-06 16:56:04 -0400239 instance_name = instance_name.lower()
240 req = self.generate_custom_service_request(instance_name, parser.svc_model, brg_mac)
Kang Xi268b74d2018-05-23 15:53:42 -0400241 self.logger.info(json.dumps(req, indent=2, sort_keys=True))
Kang Xi11d278c2018-04-06 16:56:04 -0400242 self.logger.info('Creating custom service {0}.'.format(instance_name))
243 req_id, svc_instance_id = self.submit_create_req(req, 'service')
244 if not self.check_progress(req_id, 140):
245 return False
246 return True
247
248 def wait_for_aai(self, node_type, uuid):
249 self.logger.info('Waiting for AAI traversal to complete...')
250 bar = progressbar.ProgressBar()
251 for i in range(30):
252 time.sleep(1)
253 bar.update(i*100.0/30)
254 if self.vcpecommon.is_node_in_aai(node_type, uuid):
255 bar.update(100)
256 bar.finish()
257 return
258
259 self.logger.error("AAI traversal didn't finish in 30 seconds. Something is wrong. Type {0}, UUID {1}".format(
260 node_type, uuid))
Bartek Grzybowski68d93c22019-10-30 10:55:55 +0100261 sys.exit(1)
Kang Xi11d278c2018-04-06 16:56:04 -0400262
263 def create_entire_service(self, csar_file, vnf_template_file, preload_dict, name_suffix, heatbridge=False):
264 """
265 :param csar_file:
266 :param vnf_template_file:
267 :param preload_dict:
268 :param name_suffix:
269 :return: service instance UUID
270 """
271 self.logger.info('\n----------------------------------------------------------------------------------')
272 self.logger.info('Start to create entire service defined in csar: {0}'.format(csar_file))
273 parser = csar_parser.CsarParser()
274 self.logger.info('Parsing csar ...')
275 if not parser.parse_csar(csar_file):
276 self.logger.error('Cannot parse csar: {0}'.format(csar_file))
277 return None
278
279 # create service
280 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
281 parser.svc_model['modelName'], name_suffix])
282 instance_name = instance_name.lower()
283 self.logger.info('Creating service instance: {0}.'.format(instance_name))
284 req = self.generate_service_request(instance_name, parser.svc_model)
285 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
286 req_id, svc_instance_id = self.submit_create_req(req, 'service')
287 if not self.check_progress(req_id, eta=2, interval=1):
288 return None
289
290 # wait for AAI to complete traversal
291 self.wait_for_aai('service', svc_instance_id)
292
293 # create networks
294 for model in parser.net_models:
295 base_name = model['modelCustomizationName'].lower().replace('mux_vg', 'mux_gw')
296 network_name = '_'.join([self.vcpecommon.instance_name_prefix['network'], base_name, name_suffix])
297 network_name = network_name.lower()
298 self.logger.info('Creating network: ' + network_name)
299 req = self.generate_vnf_or_network_request('network', network_name, model, svc_instance_id,
300 parser.svc_model)
301 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
302 req_id, net_instance_id = self.submit_create_req(req, 'network', svc_instance_id)
303 if not self.check_progress(req_id, eta=20):
304 return None
305
306 self.logger.info('Changing subnet name to ' + self.vcpecommon.network_name_to_subnet_name(network_name))
307 self.vcpecommon.set_network_name(network_name)
308 subnet_name_changed = False
309 for i in range(20):
310 time.sleep(3)
311 if self.vcpecommon.set_subnet_name(network_name):
312 subnet_name_changed = True
313 break
314
315 if not subnet_name_changed:
316 self.logger.error('Failed to change subnet name for ' + network_name)
317 return None
318
319
320 vnf_model = None
321 vnf_instance_id = None
322 # create VNF
323 if len(parser.vnf_models) == 1:
324 vnf_model = parser.vnf_models[0]
325 vnf_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vnf'],
326 vnf_model['modelCustomizationName'].split(' ')[0], name_suffix])
327 vnf_instance_name = vnf_instance_name.lower()
328 self.logger.info('Creating VNF: ' + vnf_instance_name)
329 req = self.generate_vnf_or_network_request('vnf', vnf_instance_name, vnf_model, svc_instance_id,
330 parser.svc_model)
331 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
332 req_id, vnf_instance_id = self.submit_create_req(req, 'vnf', svc_instance_id)
333 if not self.check_progress(req_id, eta=2, interval=1):
334 self.logger.error('Failed to create VNF {0}.'.format(vnf_instance_name))
335 return False
336
337 # wait for AAI to complete traversal
338 if not vnf_instance_id:
339 self.logger.error('No VNF instance ID returned!')
Bartek Grzybowski68d93c22019-10-30 10:55:55 +0100340 sys.exit(1)
Kang Xi11d278c2018-04-06 16:56:04 -0400341 self.wait_for_aai('vnf', vnf_instance_id)
342
343 preloader = preload.Preload(self.vcpecommon)
Brian Freeman9b3d6ca2019-11-06 13:22:53 -0500344 if self.vcpecommon.gra_api_flag:
345 preloader.preload_vfmodule(vnf_template_file, svc_instance_id, parser.vnf_models[0], parser.vfmodule_models[0],
346 preload_dict, name_suffix, True)
347 else:
348 preloader.preload_vfmodule(vnf_template_file, svc_instance_id, parser.vnf_models[0], parser.vfmodule_models[0],
349 preload_dict, name_suffix, False)
Kang Xi11d278c2018-04-06 16:56:04 -0400350 # create VF Module
351 if len(parser.vfmodule_models) == 1:
352 if not vnf_instance_id or not vnf_model:
353 self.logger.error('Invalid VNF instance ID or VNF model!')
Bartek Grzybowski68d93c22019-10-30 10:55:55 +0100354 sys.exit(1)
Kang Xi11d278c2018-04-06 16:56:04 -0400355
356 model = parser.vfmodule_models[0]
357 vfmodule_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vfmodule'],
358 model['modelCustomizationName'].split('..')[0], name_suffix])
359 vfmodule_instance_name = vfmodule_instance_name.lower()
360 self.logger.info('Creating VF Module: ' + vfmodule_instance_name)
361 req = self.generate_vfmodule_request(vfmodule_instance_name, model, svc_instance_id, parser.svc_model,
362 vnf_instance_id, vnf_model)
363 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
364 req_id, vfmodule_instance_id = self.submit_create_req(req, 'vfmodule', svc_instance_id, vnf_instance_id)
Yang Xuaa8c5842019-01-02 12:05:40 -0500365 if not self.check_progress(req_id, eta=70, interval=50):
Kang Xi11d278c2018-04-06 16:56:04 -0400366 self.logger.error('Failed to create VF Module {0}.'.format(vfmodule_instance_name))
367 return None
368
369 # run heatbridge
370 if heatbridge:
Bartek Grzybowskibfeeb242019-09-13 08:35:48 +0200371 self.vcpecommon.heatbridge(vfmodule_instance_name, svc_instance_id)
Kang Xi11d278c2018-04-06 16:56:04 -0400372 self.vcpecommon.save_vgmux_vnf_name(vnf_instance_name)
373
374 return svc_instance_id