blob: 623f12cc3188376e235750363d27b1ef6db52d88 [file] [log] [blame]
Kang Xi11d278c2018-04-06 16:56:04 -04001#! /usr/bin/python
2
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)
26 sys.exit()
27 self.service_req_api_url = self.vcpecommon.so_req_api_url[api_version]
28
29 def submit_create_req(self, req_json, req_type, service_instance_id=None, vnf_instance_id=None):
30 """
31 POST {serverRoot}/serviceInstances/v4
32 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs
33 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/networks
34 POST {serverRoot}/serviceInstances/v4/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules
35 :param req_json:
36 :param service_instance_id: this is required only for networks, vnfs, and vf modules
37 :param req_type:
38 :param vnf_instance_id:
39 :return: req_id, instance_id
40 """
41 if req_type == 'service':
42 url = self.service_req_api_url
43 elif req_type == 'vnf':
44 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs'])
45 elif req_type == 'network':
46 url = '/'.join([self.service_req_api_url, service_instance_id, 'networks'])
47 elif req_type == 'vfmodule':
48 url = '/'.join([self.service_req_api_url, service_instance_id, 'vnfs', vnf_instance_id, 'vfModules'])
49 else:
50 self.logger.error('Invalid request type: {0}. Can only be service/vnf/network/vfmodule'.format(req_type))
51 return None, None
52
Kang Xi268b74d2018-05-23 15:53:42 -040053 self.logger.info(url)
Kang Xi11d278c2018-04-06 16:56:04 -040054 r = requests.post(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass, json=req_json)
Kang Xi268b74d2018-05-23 15:53:42 -040055 self.logger.debug(r)
Kang Xi11d278c2018-04-06 16:56:04 -040056 response = r.json()
57
58 self.logger.debug('---------------------------------------------------------------')
59 self.logger.debug('------- Creation request submitted to SO, got response --------')
60 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
61 self.logger.debug('---------------------------------------------------------------')
62 req_id = response.get('requestReferences', {}).get('requestId', '')
63 instance_id = response.get('requestReferences', {}).get('instanceId', '')
Kang Xi268b74d2018-05-23 15:53:42 -040064
Kang Xi11d278c2018-04-06 16:56:04 -040065 return req_id, instance_id
66
67 def check_progress(self, req_id, eta=0, interval=5):
68 if not req_id:
69 self.logger.error('Error when checking SO request progress, invalid request ID: ' + req_id)
70 return False
71 duration = 0.0
72 bar = progressbar.ProgressBar(redirect_stdout=True)
73 url = self.vcpecommon.so_check_progress_api_url + '/' + req_id
74
75 while True:
76 time.sleep(interval)
77 r = requests.get(url, headers=self.vcpecommon.so_headers, auth=self.vcpecommon.so_userpass)
78 response = r.json()
79
80 duration += interval
81 if eta > 0:
82 percentage = min(95, 100 * duration / eta)
83 else:
84 percentage = int(response['request']['requestStatus']['percentProgress'])
85
86 if response['request']['requestStatus']['requestState'] == 'IN_PROGRESS':
87 self.logger.debug('------------------Request Status-------------------------------')
88 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
89 bar.update(percentage)
90 else:
91 self.logger.debug('---------------------------------------------------------------')
92 self.logger.debug('----------------- Creation Request Results --------------------')
93 self.logger.debug(json.dumps(response, indent=4, sort_keys=True))
94 self.logger.debug('---------------------------------------------------------------')
95 flag = response['request']['requestStatus']['requestState'] == 'COMPLETE'
96 if not flag:
97 self.logger.error('Request failed.')
98 self.logger.error(json.dumps(response, indent=4, sort_keys=True))
99 bar.update(100)
100 bar.finish()
101 return flag
102
103 def add_req_info(self, req_details, instance_name, product_family_id=None):
104 req_details['requestInfo'] = {
105 'instanceName': instance_name,
106 'source': 'VID',
107 'suppressRollback': 'true',
108 'requestorId': 'vCPE-Robot'
109 }
110 if product_family_id:
111 req_details['requestInfo']['productFamilyId'] = product_family_id
112
113 def add_related_instance(self, req_details, instance_id, instance_model):
114 instance = {"instanceId": instance_id, "modelInfo": instance_model}
115 if 'relatedInstanceList' not in req_details:
116 req_details['relatedInstanceList'] = [{"relatedInstance": instance}]
117 else:
118 req_details['relatedInstanceList'].append({"relatedInstance": instance})
119
120 def generate_vnf_or_network_request(self, req_type, instance_name, vnf_or_network_model, service_instance_id,
121 service_model):
122 req_details = {
123 'modelInfo': vnf_or_network_model,
124 'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
125 "tenantId": self.vcpecommon.os_tenant_id},
Kang Xi268b74d2018-05-23 15:53:42 -0400126 'requestParameters': {"userParams": []},
127 'platform': {"platformName": "Platform-Demonstration"}
Kang Xi11d278c2018-04-06 16:56:04 -0400128 }
129 self.add_req_info(req_details, instance_name, self.vcpecommon.product_family_id)
130 self.add_related_instance(req_details, service_instance_id, service_model)
131 return {'requestDetails': req_details}
132
133 def generate_vfmodule_request(self, instance_name, vfmodule_model, service_instance_id,
134 service_model, vnf_instance_id, vnf_model):
135 req_details = {
136 'modelInfo': vfmodule_model,
137 'cloudConfiguration': {"lcpCloudRegionId": self.vcpecommon.os_region_name,
138 "tenantId": self.vcpecommon.os_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)
Kang Xi268b74d2018-05-23 15:53:42 -0400157 self.add_project_info(req_details)
158 self.add_owning_entity(req_details)
Kang Xi11d278c2018-04-06 16:56:04 -0400159 return {'requestDetails': req_details}
160
Kang Xi268b74d2018-05-23 15:53:42 -0400161 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
Kang Xi11d278c2018-04-06 16:56:04 -0400168 def generate_custom_service_request(self, instance_name, model, brg_mac):
169 req_details = {
170 'modelInfo': model,
171 'subscriberInfo': {'subscriberName': 'Kaneohe',
172 'globalSubscriberId': self.vcpecommon.global_subscriber_id},
Kang Xi268b74d2018-05-23 15:53:42 -0400173 'cloudConfiguration': {"lcpCloudRegionId": 'CloudOwner_RegionOne', #self.vcpecommon.os_region_name,
Kang Xi11d278c2018-04-06 16:56:04 -0400174 "tenantId": self.vcpecommon.os_tenant_id},
175 'requestParameters': {
176 "userParams": [
177 {
178 'name': 'BRG_WAN_MAC_Address',
179 'value': brg_mac
180 }
Kang Xi268b74d2018-05-23 15:53:42 -0400181 ,
182 {
183 "name": "Customer_Location",
184 "value": self.vcpecommon.customer_location_used_by_oof
185 },
186 {
187 "name": "Homing_Solution",
188 "value": self.vcpecommon.homing_solution
189 }
Kang Xi11d278c2018-04-06 16:56:04 -0400190 ],
191 "subscriptionServiceType": "vCPE",
192 'aLaCarte': 'false'
193 }
194 }
195 self.add_req_info(req_details, instance_name, self.vcpecommon.custom_product_family_id)
Kang Xi268b74d2018-05-23 15:53:42 -0400196 self.add_project_info(req_details)
197 self.add_owning_entity(req_details)
Kang Xi11d278c2018-04-06 16:56:04 -0400198 return {'requestDetails': req_details}
199
200 def create_custom_service(self, csar_file, brg_mac, name_suffix=None):
201 parser = csar_parser.CsarParser()
202 if not parser.parse_csar(csar_file):
203 return False
204
205 # yyyymmdd_hhmm
206 if not name_suffix:
207 name_suffix = '_' + datetime.now().strftime('%Y%m%d%H%M')
208
209 # create service
210 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
211 parser.svc_model['modelName'], name_suffix])
212 instance_name = instance_name.lower()
213 req = self.generate_custom_service_request(instance_name, parser.svc_model, brg_mac)
Kang Xi268b74d2018-05-23 15:53:42 -0400214 self.logger.info(json.dumps(req, indent=2, sort_keys=True))
Kang Xi11d278c2018-04-06 16:56:04 -0400215 self.logger.info('Creating custom service {0}.'.format(instance_name))
216 req_id, svc_instance_id = self.submit_create_req(req, 'service')
217 if not self.check_progress(req_id, 140):
218 return False
219 return True
220
221 def wait_for_aai(self, node_type, uuid):
222 self.logger.info('Waiting for AAI traversal to complete...')
223 bar = progressbar.ProgressBar()
224 for i in range(30):
225 time.sleep(1)
226 bar.update(i*100.0/30)
227 if self.vcpecommon.is_node_in_aai(node_type, uuid):
228 bar.update(100)
229 bar.finish()
230 return
231
232 self.logger.error("AAI traversal didn't finish in 30 seconds. Something is wrong. Type {0}, UUID {1}".format(
233 node_type, uuid))
234 sys.exit()
235
236 def create_entire_service(self, csar_file, vnf_template_file, preload_dict, name_suffix, heatbridge=False):
237 """
238 :param csar_file:
239 :param vnf_template_file:
240 :param preload_dict:
241 :param name_suffix:
242 :return: service instance UUID
243 """
244 self.logger.info('\n----------------------------------------------------------------------------------')
245 self.logger.info('Start to create entire service defined in csar: {0}'.format(csar_file))
246 parser = csar_parser.CsarParser()
247 self.logger.info('Parsing csar ...')
248 if not parser.parse_csar(csar_file):
249 self.logger.error('Cannot parse csar: {0}'.format(csar_file))
250 return None
251
252 # create service
253 instance_name = '_'.join([self.vcpecommon.instance_name_prefix['service'],
254 parser.svc_model['modelName'], name_suffix])
255 instance_name = instance_name.lower()
256 self.logger.info('Creating service instance: {0}.'.format(instance_name))
257 req = self.generate_service_request(instance_name, parser.svc_model)
258 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
259 req_id, svc_instance_id = self.submit_create_req(req, 'service')
260 if not self.check_progress(req_id, eta=2, interval=1):
261 return None
262
263 # wait for AAI to complete traversal
264 self.wait_for_aai('service', svc_instance_id)
265
266 # create networks
267 for model in parser.net_models:
268 base_name = model['modelCustomizationName'].lower().replace('mux_vg', 'mux_gw')
269 network_name = '_'.join([self.vcpecommon.instance_name_prefix['network'], base_name, name_suffix])
270 network_name = network_name.lower()
271 self.logger.info('Creating network: ' + network_name)
272 req = self.generate_vnf_or_network_request('network', network_name, model, svc_instance_id,
273 parser.svc_model)
274 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
275 req_id, net_instance_id = self.submit_create_req(req, 'network', svc_instance_id)
276 if not self.check_progress(req_id, eta=20):
277 return None
278
279 self.logger.info('Changing subnet name to ' + self.vcpecommon.network_name_to_subnet_name(network_name))
280 self.vcpecommon.set_network_name(network_name)
281 subnet_name_changed = False
282 for i in range(20):
283 time.sleep(3)
284 if self.vcpecommon.set_subnet_name(network_name):
285 subnet_name_changed = True
286 break
287
288 if not subnet_name_changed:
289 self.logger.error('Failed to change subnet name for ' + network_name)
290 return None
291
292
293 vnf_model = None
294 vnf_instance_id = None
295 # create VNF
296 if len(parser.vnf_models) == 1:
297 vnf_model = parser.vnf_models[0]
298 vnf_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vnf'],
299 vnf_model['modelCustomizationName'].split(' ')[0], name_suffix])
300 vnf_instance_name = vnf_instance_name.lower()
301 self.logger.info('Creating VNF: ' + vnf_instance_name)
302 req = self.generate_vnf_or_network_request('vnf', vnf_instance_name, vnf_model, svc_instance_id,
303 parser.svc_model)
304 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
305 req_id, vnf_instance_id = self.submit_create_req(req, 'vnf', svc_instance_id)
306 if not self.check_progress(req_id, eta=2, interval=1):
307 self.logger.error('Failed to create VNF {0}.'.format(vnf_instance_name))
308 return False
309
310 # wait for AAI to complete traversal
311 if not vnf_instance_id:
312 self.logger.error('No VNF instance ID returned!')
313 sys.exit()
314 self.wait_for_aai('vnf', vnf_instance_id)
315
316 preloader = preload.Preload(self.vcpecommon)
317 preloader.preload_vfmodule(vnf_template_file, svc_instance_id, parser.vnf_models[0], parser.vfmodule_models[0],
318 preload_dict, name_suffix)
319 # create VF Module
320 if len(parser.vfmodule_models) == 1:
321 if not vnf_instance_id or not vnf_model:
322 self.logger.error('Invalid VNF instance ID or VNF model!')
323 sys.exit()
324
325 model = parser.vfmodule_models[0]
326 vfmodule_instance_name = '_'.join([self.vcpecommon.instance_name_prefix['vfmodule'],
327 model['modelCustomizationName'].split('..')[0], name_suffix])
328 vfmodule_instance_name = vfmodule_instance_name.lower()
329 self.logger.info('Creating VF Module: ' + vfmodule_instance_name)
330 req = self.generate_vfmodule_request(vfmodule_instance_name, model, svc_instance_id, parser.svc_model,
331 vnf_instance_id, vnf_model)
332 self.logger.debug(json.dumps(req, indent=2, sort_keys=True))
333 req_id, vfmodule_instance_id = self.submit_create_req(req, 'vfmodule', svc_instance_id, vnf_instance_id)
334 if not self.check_progress(req_id, eta=70, interval=5):
335 self.logger.error('Failed to create VF Module {0}.'.format(vfmodule_instance_name))
336 return None
337
338 # run heatbridge
339 if heatbridge:
340 self.vcpecommon.headbridge(vfmodule_instance_name, svc_instance_id)
341 self.vcpecommon.save_vgmux_vnf_name(vnf_instance_name)
342
343 return svc_instance_id