blob: c52006d4f9ea608f9f3e12a3abf3988e2dd79320 [file] [log] [blame]
Brian Freeman9a56c902019-04-16 11:27:00 -05001#! /usr/bin/python
2
Brian Freeman9a56c902019-04-16 11:27:00 -05003import time
DR695Hae6fedd2019-05-01 18:52:33 -04004
5from .csar_parser import *
6from .preload import *
7from .vcpecommon import *
Brian Freeman9a56c902019-04-16 11:27:00 -05008from robot.api import logger
9
10
11class SoUtils:
12
13 def __init__(self):
14 """
15 :param api_version: must be 'v4' or 'v5'
16 """
17 self.tmp_solution_for_so_bug = False
18 #self.logger = logging.getLogger(__name__)
19 self.logger = logger
20 self.vcpecommon = VcpeCommon()
21 self.api_version = 'v4'
22 self.service_req_api_url = self.vcpecommon.so_req_api_url[self.api_version]
23
24
25 def submit_create_req(self, req_json, req_type, service_instance_id=None, vnf_instance_id=None):
26 """
27 POST {serverRoot}/serviceInstances/v4
28 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs
29 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/networks
30 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules
31 :param req_json:
32 :param service_instance_id: this is required only for networks, vnfs, and vf modules
33 :param req_type:
34 :param vnf_instance_id:
35 :return: req_id, instance_id
36 """
37 if req_type == 'service':
38 url = self.service_req_api_url
39 elif req_type == 'vnf':
40 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs'])
41 elif req_type == 'network':
42 url = '/'.join([self.service_req_api_url, service_instance_id, 'networks'])
43 elif req_type == 'vfmodule':
44 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs', vnf_instance_id, 'vfModules'])
45 else:
46 self.logger.error('Invalid request type: {0}. Can only be service/vnf/network/vfmodule'.format(req_type))
47 return None, None
48
49 self.logger.info(url)
50 r = requests.post(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass, json=req_json)
51 self.logger.debug(r)
52 response = r.json()
53
54 self.logger.debug('---------------------------------------------------------------')
55 self.logger.debug('------- Creation request submitted to SO, got response --------')
56 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
57 self.logger.debug('---------------------------------------------------------------')
58 req_id = response.get('requestReferences', {}).get('requestId', '')
59 instance_id = response.get('requestReferences', {}).get('instanceId', '')
60
61 return req_id, instance_id
62
63 def check_progress(self, req_id, eta=0, interval=5):
64 if not req_id:
65 self.logger.error('Error when checking SO request progress, invalid request ID: ' + req_id)
66 return False
67 duration = 0.0
68 #bar = progressbar.ProgressBar(redirect_stdout=True)
69 url = self.vcpecommon.so_check_progress_api_url + '/' + req_id
70
71 while True:
72 time.sleep(interval)
73 r = requests.get(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass)
74 response = r.json()
75
76 duration += interval
77 if eta > 0:
78 percentage = min(95, 100 * duration / eta)
79 else:
80 percentage = int(response['request']['requestStatus']['percentProgress'])
81
82 if response['request']['requestStatus']['requestState'] == 'IN_PROGRESS':
83 self.logger.debug('------------------Request Status-------------------------------')
84 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
85 #bar.update(percentage)
86 else:
87 self.logger.debug('---------------------------------------------------------------')
88 self.logger.debug('----------------- Creation Request Results --------------------')
89 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
90 self.logger.debug('---------------------------------------------------------------')
91 flag = response['request']['requestStatus']['requestState'] == 'COMPLETE'
92 if not flag:
93 self.logger.error('Request failed.')
94 self.logger.error(json.dumps(response, indent=4, sort_keys=True))
95 #bar.update(100)
96 #bar.finish()
97 return flag
98
99 def add_req_info(self, req_details, instance_name, product_family_id=None):
100 req_details['requestInfo'] = {
101 'instanceName': instance_name,
102 'source': 'VID',
103 'suppressRollback': 'true',
104 'requestorId': 'vCPE-Robot'
105 }
106 if product_family_id:
107 req_details['requestInfo']['productFamilyId'] = product_family_id
108
109 def add_related_instance(self, req_details, instance_id, instance_model):
110 instance = {"instanceId": instance_id, "modelInfo": instance_model}
111 if 'relatedInstanceList' not in req_details:
112 req_details['relatedInstanceList'] = [{"relatedInstance": instance}]
113 else:
114 req_details['relatedInstanceList'].append({"relatedInstance": instance})
115
116 def generate_vnf_or_network_request(self, req_type, instance_name, vnf_or_network_model, service_instance_id,
117 service_model):
118 req_details = {
119 'modelInfo': vnf_or_network_model,
120 #'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
121 # "tenantId": self.vcpecommon.os_tenant_id},
122 'cloudConfiguration': {"lcpCloudRegionId": self.region_name,
123 "tenantId": self.tenant_id},
124 'requestParameters': {"userParams": []},
125 'platform': {"platformName": "Platform-Demonstration"}
126 }
127 self.add_req_info(req_details, instance_name, self.vcpecommon.product_family_id)
128 self.add_related_instance(req_details, service_instance_id, service_model)
129 return {'requestDetails': req_details}
130
131 def generate_vfmodule_request(self, instance_name, vfmodule_model, service_instance_id,
132 service_model, vnf_instance_id, vnf_model):
133 req_details = {
134 'modelInfo': vfmodule_model,
135 #'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
136 # "tenantId": self.vcpecommon.os_tenant_id},
137 'cloudConfiguration': {"lcpCloudRegionId": self.region_name,
138 "tenantId": self.tenant_id},
139 'requestParameters': {"usePreload": 'true'}
140 }
141 self.add_req_info(req_details, instance_name, self.vcpecommon.product_family_id)
142 self.add_related_instance(req_details, service_instance_id, service_model)
143 self.add_related_instance(req_details, vnf_instance_id, vnf_model)
144 return {'requestDetails': req_details}
145
146 def generate_service_request(self, instance_name, model):
147 req_details = {
148 'modelInfo': model,
149 'subscriberInfo': {'globalSubscriberId': self.vcpecommon.global_subscriber_id},
150 'requestParameters': {
151 "userParams": [],
152 "subscriptionServiceType": "vCPE",
153 "aLaCarte": 'true'
154 }
155 }
156 self.add_req_info(req_details, instance_name)
157 self.add_project_info(req_details)
158 self.add_owning_entity(req_details)
159 return {'requestDetails': req_details}
160
161 def add_project_info(self, req_details):
162 req_details['project'] = {'projectName': self.vcpecommon.project_name}
163
164 def add_owning_entity(self, req_details):
165 req_details['owningEntity'] = {'owningEntityId': self.vcpecommon.owning_entity_id,
166 'owningEntityName': self.vcpecommon.owning_entity_name}
167
168 def generate_custom_service_request(self, instance_name, model, brg_mac):
169 brg_mac_enc = brg_mac.replace(':', '-')
170 req_details = {
171 'modelInfo': model,
172 'subscriberInfo': {'subscriberName': 'Kaneohe',
173 'globalSubscriberId': self.vcpecommon.global_subscriber_id},
174 'cloudConfiguration': {"lcpCloudRegionId": self.region_name,
175 "tenantId": self.tenant_id},
176 'requestParameters': {
177 "userParams": [
178 {
179 'name': 'BRG_WAN_MAC_Address',
180 'value': brg_mac
181 },
182 {
183 'name': 'VfModuleNames',
184 'value': [
185 {
186 'VfModuleModelInvariantUuid': self.vcpecommon.vgw_VfModuleModelInvariantUuid,
187 'VfModuleName': 'VGW2BRG-{0}'.format(brg_mac_enc)
188 }
189 ]
190 },
191 {
192 "name": "Customer_Location",
193 "value": self.vcpecommon.customer_location_used_by_oof
194 },
195 {
196 "name": "Homing_Solution",
197 "value": self.vcpecommon.homing_solution
198 }
199 ],
200 "subscriptionServiceType": "vCPE",
201 'aLaCarte': 'false'
202 }
203 }
204 self.add_req_info(req_details, instance_name, self.vcpecommon.custom_product_family_id)
205 self.add_project_info(req_details)
206 self.add_owning_entity(req_details)
207 return {'requestDetails': req_details}
208
209 def create_custom_service(self, csar_file, brg_mac, name_suffix=None):
DR695Hae6fedd2019-05-01 18:52:33 -0400210 parser = CsarParser()
Brian Freeman9a56c902019-04-16 11:27:00 -0500211 if not parser.parse_csar(csar_file):
212 return False
213
214 # yyyymmdd_hhmm
215 if not name_suffix:
216 name_suffix = '_' + datetime.now().strftime('%Y%m%d%H%M')
217
218 # create service
219 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
220 parser.svc_model['modelName'][0:10], name_suffix])
221 instance_name = instance_name.lower()
222 req = self.generate_custom_service_request(instance_name, parser.svc_model, brg_mac)
223 self.logger.info(json.dumps(req, indent=2, sort_keys=True))
224 self.logger.info('Creating custom service {0}.'.format(instance_name))
225 req_id, svc_instance_id = self.submit_create_req(req, 'service')
226 if not self.check_progress(req_id, 140):
227 return False
228 return True
229
230 def wait_for_aai(self, node_type, uuid):
231 self.logger.info('Waiting for AAI traversal to complete...')
232 #bar = progressbar.ProgressBar()
233 for i in range(30):
234 time.sleep(1)
235 #bar.update(i*100.0/30)
236 if self.vcpecommon.is_node_in_aai(node_type, uuid):
237 #bar.update(100)
238 #bar.finish()
239 return
240
241 self.logger.error("AAI traversal didn't finish in 30 seconds. Something is wrong. Type {0}, UUID {1}".format(
242 node_type, uuid))
243 sys.exit()
244
245 def create_entire_service(self, csar_file, vnf_template_file, preload_dict, name_suffix, region_name, tenant_id, heatbridge=False):
246 """
247 :param csar_file:
248 :param vnf_template_file:
249 :param preload_dict:
250 :param name_suffix:
251 :return: service instance UUID
252 """
253 self.region_name=region_name
254 self.tenant_id=tenant_id
255 self.logger.info('\n----------------------------------------------------------------------------------')
256 self.logger.info('Start to create entire service defined in csar: {0}'.format(csar_file))
DR695Hae6fedd2019-05-01 18:52:33 -0400257 parser = CsarParser()
Brian Freeman9a56c902019-04-16 11:27:00 -0500258 self.logger.info('Parsing csar ...')
259 if not parser.parse_csar(csar_file):
260 self.logger.error('Cannot parse csar: {0}'.format(csar_file))
261 return None
262
263 # Set Global timestamp for instancenames
264 global_timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
265 # create service
266 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
267 parser.svc_model['modelName'], global_timestamp, name_suffix])
268 instance_name = instance_name.lower()
269 instance_name = instance_name.replace(' ','')
270 instance_name = instance_name.replace(':','')
271 self.logger.info('Creating service instance: {0}.'.format(instance_name))
272 req = self.generate_service_request(instance_name, parser.svc_model)
273 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
274 req_id, svc_instance_id = self.submit_create_req(req, 'service')
275 if not self.check_progress(req_id, eta=2, interval=5):
276 return None
277
278 # wait for AAI to complete traversal
279 self.wait_for_aai('service', svc_instance_id)
280
281 # create networks
282 for model in parser.net_models:
283 base_name = model['modelCustomizationName'].lower().replace('mux_vg', 'mux_gw')
284 network_name = '_'.join([self.vcpecommon.instance_name_prefix['network'], base_name, name_suffix])
285 network_name = network_name.lower()
286 self.logger.info('Creating network: ' + network_name)
287 req = self.generate_vnf_or_network_request('network', network_name, model, svc_instance_id,
288 parser.svc_model)
289 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
290 req_id, net_instance_id = self.submit_create_req(req, 'network', svc_instance_id)
291 if not self.check_progress(req_id, eta=20):
292 return None
293
294 self.logger.info('Changing subnet name to ' + self.vcpecommon.network_name_to_subnet_name(network_name))
295 self.vcpecommon.set_network_name(network_name)
296 subnet_name_changed = False
297 for i in range(20):
298 time.sleep(3)
299 if self.vcpecommon.set_subnet_name(network_name):
300 subnet_name_changed = True
301 break
302
303 if not subnet_name_changed:
304 self.logger.error('Failed to change subnet name for ' + network_name)
305 return None
306
307
308 vnf_model = None
309 vnf_instance_id = None
310 # create VNF
311 if len(parser.vnf_models) == 1:
312 vnf_model = parser.vnf_models[0]
313 vnf_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vnf'],
314 vnf_model['modelCustomizationName'].split(' ')[0], name_suffix])
315 vnf_instance_name = vnf_instance_name.lower()
316 vnf_instance_name = vnf_instance_name.replace(' ','')
317 vnf_instance_name = vnf_instance_name.replace(':','')
318 self.logger.info('Creating VNF: ' + vnf_instance_name)
319 req = self.generate_vnf_or_network_request('vnf', vnf_instance_name, vnf_model, svc_instance_id,
320 parser.svc_model)
321 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
322 req_id, vnf_instance_id = self.submit_create_req(req, 'vnf', svc_instance_id)
323 if not self.check_progress(req_id, eta=2, interval=5):
324 self.logger.error('Failed to create VNF {0}.'.format(vnf_instance_name))
325 return False
326
327 # wait for AAI to complete traversal
328 if not vnf_instance_id:
329 self.logger.error('No VNF instance ID returned!')
330 sys.exit()
331 self.wait_for_aai('vnf', vnf_instance_id)
332
333 # SDNC Preload
334
DR695Hae6fedd2019-05-01 18:52:33 -0400335 preloader = Preload(self.vcpecommon)
Brian Freeman9a56c902019-04-16 11:27:00 -0500336 preloader.preload_vfmodule(vnf_template_file, svc_instance_id, parser.vnf_models[0], parser.vfmodule_models[0],
337 preload_dict, name_suffix)
338
339 # create VF Module
340 if len(parser.vfmodule_models) == 1:
341 if not vnf_instance_id or not vnf_model:
342 self.logger.error('Invalid VNF instance ID or VNF model!')
343 sys.exit()
344
345 model = parser.vfmodule_models[0]
346 vfmodule_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vfmodule'],
347 model['modelCustomizationName'].split('..')[0], name_suffix])
348 vfmodule_instance_name = vfmodule_instance_name.lower()
349 vfmodule_instance_name = vfmodule_instance_name.replace(' ','')
350 vfmoduel_instance_name = vfmodule_instance_name.replace(':','')
351 self.logger.info('Creating VF Module: ' + vfmodule_instance_name)
352 req = self.generate_vfmodule_request(vfmodule_instance_name, model, svc_instance_id, parser.svc_model,
353 vnf_instance_id, vnf_model)
354 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
355 req_id, vfmodule_instance_id = self.submit_create_req(req, 'vfmodule', svc_instance_id, vnf_instance_id)
356 if not self.check_progress(req_id, eta=70, interval=50):
357 self.logger.error('Failed to create VF Module {0}.'.format(vfmodule_instance_name))
358 return None
359
360 # run heatbridge
Brian Freeman5709f892019-04-17 13:51:48 -0500361 # removed until we fold in heatbridge
362 #if heatbridge:
363 #self.vcpecommon.heatbridge(vfmodule_instance_name, svc_instance_id)
364 #self.vcpecommon.save_vgmux_vnf_name(vnf_instance_name)
Brian Freeman9a56c902019-04-16 11:27:00 -0500365
366 return svc_instance_id