blob: 5b3e009a399137d3773a9fc69b732507db74bf9a [file] [log] [blame]
Kang Xi11d278c2018-04-06 16:56:04 -04001import json
2import logging
3import os
4import pickle
5import re
6import sys
7
8import ipaddress
9import mysql.connector
10import requests
11import commands
12import time
13
14
15class VcpeCommon:
16 #############################################################################################
17 # Start: configurations that you must change for a new ONAP installation
18 external_net_addr = '10.12.0.0'
19 external_net_prefix_len = 16
20 #############################################################################################
21 # set the openstack cloud access credentials here
22 cloud = {
23 '--os-auth-url': 'http://10.12.25.2:5000',
24 '--os-username': 'YOUR ID',
25 '--os-user-domain-id': 'default',
26 '--os-project-domain-id': 'default',
27 '--os-tenant-id': '087050388b204c73a3e418dd2c1fe30b',
28 '--os-region-name': 'RegionOne',
29 '--os-password': 'YOUR PASSWD',
30 '--os-project-domain-name': 'Integration-SB-01',
31 '--os-identity-api-version': '3'
32 }
33
34 common_preload_config = {
35 'oam_onap_net': 'oam_onap_c4Uw',
36 'oam_onap_subnet': 'oam_onap_c4Uw',
37 'public_net': 'external',
38 'public_net_id': '971040b2-7059-49dc-b220-4fab50cb2ad4'
39 }
40 # End: configurations that you must change for a new ONAP installation
41 #############################################################################################
42
43 template_variable_symbol = '${'
44 #############################################################################################
45 # preloading network config
46 # key=network role
47 # value = [subnet_start_ip, subnet_gateway_ip]
48 preload_network_config = {
49 'cpe_public': ['10.2.0.2', '10.2.0.1'],
50 'cpe_signal': ['10.4.0.2', '10.4.0.1'],
51 'brg_bng': ['10.3.0.2', '10.3.0.1'],
52 'bng_mux': ['10.1.0.10', '10.1.0.1'],
53 'mux_gw': ['10.5.0.10', '10.5.0.1']
54 }
55
56 global_subscriber_id = 'SDN-ETHERNET-INTERNET'
57
58 def __init__(self, extra_host_names=None):
59 self.logger = logging.getLogger(__name__)
60 self.logger.info('Initializing configuration')
61
62 self.host_names = ['so', 'sdnc', 'robot', 'aai-inst1', 'dcaedoks00']
63 if extra_host_names:
64 self.host_names.extend(extra_host_names)
65 # get IP addresses
66 self.hosts = self.get_vm_ip(self.host_names, self.external_net_addr, self.external_net_prefix_len)
67 # this is the keyword used to name vgw stack, must not be used in other stacks
68 self.vgw_name_keyword = 'base_vcpe_vgw'
69 self.svc_instance_uuid_file = '__var/svc_instance_uuid'
70 self.preload_dict_file = '__var/preload_dict'
71 self.vgmux_vnf_name_file = '__var/vgmux_vnf_name'
72 self.product_family_id = 'f9457e8c-4afd-45da-9389-46acd9bf5116'
73 self.custom_product_family_id = 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb'
74 self.instance_name_prefix = {
75 'service': 'vcpe_svc',
76 'network': 'vcpe_net',
77 'vnf': 'vcpe_vnf',
78 'vfmodule': 'vcpe_vfmodule'
79 }
80 self.aai_userpass = 'AAI', 'AAI'
81 self.pub_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKXDgoo3+WOqcUG8/5uUbk81+yczgwC4Y8ywTmuQqbNxlY1oQ0YxdMUqUnhitSXs5S/yRuAVOYHwGg2mCs20oAINrP+mxBI544AMIb9itPjCtgqtE2EWo6MmnFGbHB4Sx3XioE7F4VPsh7japsIwzOjbrQe+Mua1TGQ5d4nfEOQaaglXLLPFfuc7WbhbJbK6Q7rHqZfRcOwAMXgDoBqlyqKeiKwnumddo2RyNT8ljYmvB6buz7KnMinzo7qB0uktVT05FH9Rg0CTWH5norlG5qXgP2aukL0gk1ph8iAt7uYLf1ktp+LJI2gaF6L0/qli9EmVCSLr1uJ38Q8CBflhkh'
82 self.os_tenant_id = self.cloud['--os-tenant-id']
83 self.os_region_name = self.cloud['--os-region-name']
84 self.common_preload_config['pub_key'] = self.pub_key
85 self.sniro_url = 'http://' + self.hosts['robot'] + ':8080/__admin/mappings'
86 self.sniro_headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
87
88 #############################################################################################
89 # SDNC urls
90 self.sdnc_userpass = 'admin', 'Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U'
91 self.sdnc_db_name = 'sdnctl'
92 self.sdnc_db_user = 'sdnctl'
93 self.sdnc_db_pass = 'gamma'
94 self.sdnc_db_port = '32768'
95 self.sdnc_headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
96 self.sdnc_preload_network_url = 'http://' + self.hosts['sdnc'] + \
97 ':8282/restconf/operations/VNF-API:preload-network-topology-operation'
98 self.sdnc_preload_vnf_url = 'http://' + self.hosts['sdnc'] + \
99 ':8282/restconf/operations/VNF-API:preload-vnf-topology-operation'
100 self.sdnc_ar_cleanup_url = 'http://' + self.hosts['sdnc'] + ':8282/restconf/config/GENERIC-RESOURCE-API:'
101
102 #############################################################################################
103 # SO urls, note: do NOT add a '/' at the end of the url
104 self.so_req_api_url = {'v4': 'http://' + self.hosts['so'] + ':8080/ecomp/mso/infra/serviceInstances/v4',
105 'v5': 'http://' + self.hosts['so'] + ':8080/ecomp/mso/infra/serviceInstances/v5'}
106 self.so_check_progress_api_url = 'http://' + self.hosts['so'] + ':8080/ecomp/mso/infra/orchestrationRequests/v2'
107 self.so_userpass = 'InfraPortalClient', 'password1$'
108 self.so_headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
109 self.so_db_name = 'mso_catalog'
110 self.so_db_user = 'root'
111 self.so_db_pass = 'password'
112 self.so_db_port = '32768'
113
114 self.vpp_inf_url = 'http://{0}:8183/restconf/config/ietf-interfaces:interfaces'
115 self.vpp_api_headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
116 self.vpp_api_userpass = ('admin', 'admin')
117 self.vpp_ves_url= 'http://{0}:8183/restconf/config/vesagent:vesagent'
118
119 def headbridge(self, openstack_stack_name, svc_instance_uuid):
120 """
121 Add vserver information to AAI
122 """
123 self.logger.info('Adding vServer information to AAI for {0}'.format(openstack_stack_name))
124 cmd = '/opt/demo.sh heatbridge {0} {1} vCPE'.format(openstack_stack_name, svc_instance_uuid)
125 ret = commands.getstatusoutput("ssh -i onap_dev root@{0} '{1}'".format(self.hosts['robot'], cmd))
126 self.logger.debug('%s', ret)
127
128 def get_brg_mac_from_sdnc(self):
129 """
130 :return: BRG MAC address. Currently we only support one BRG instance.
131 """
132 cnx = mysql.connector.connect(user=self.sdnc_db_user, password=self.sdnc_db_pass, database=self.sdnc_db_name,
133 host=self.hosts['sdnc'], port=self.sdnc_db_port)
134 cursor = cnx.cursor()
135 query = "SELECT * from DHCP_MAP"
136 cursor.execute(query)
137
138 self.logger.debug('DHCP_MAP table in SDNC')
139 counter = 0
140 mac = None
141 for mac, ip in cursor:
142 counter += 1
143 self.logger.debug(mac + ':' + ip)
144
145 cnx.close()
146
147 if counter != 1:
148 self.logger.error('Found %s MAC addresses in DHCP_MAP', counter)
149 sys.exit()
150 else:
151 self.logger.debug('Found MAC addresses in DHCP_MAP: %s', mac)
152 return mac
153
154 def insert_into_sdnc_db(self, cmds):
155 cnx = mysql.connector.connect(user=self.sdnc_db_user, password=self.sdnc_db_pass, database=self.sdnc_db_name,
156 host=self.hosts['sdnc'], port=self.sdnc_db_port)
157 cursor = cnx.cursor()
158 for cmd in cmds:
159 self.logger.debug(cmd)
160 cursor.execute(cmd)
161 self.logger.debug('%s', cursor)
162 cnx.commit()
163 cursor.close()
164 cnx.close()
165
166 def insert_into_so_db(self, cmds):
167 cnx = mysql.connector.connect(user=self.so_db_user, password=self.so_db_pass, database=self.so_db_name,
168 host=self.hosts['so'], port=self.so_db_port)
169 cursor = cnx.cursor()
170 for cmd in cmds:
171 self.logger.debug(cmd)
172 cursor.execute(cmd)
173 self.logger.debug('%s', cursor)
174 cnx.commit()
175 cursor.close()
176 cnx.close()
177
178 def find_file(self, file_name_keyword, file_ext, search_dir):
179 """
180 :param file_name_keyword: keyword used to look for the csar file, case insensitive matching, e.g, infra
181 :param file_ext: e.g., csar, json
182 :param search_dir path to search
183 :return: path name of the file
184 """
185 file_name_keyword = file_name_keyword.lower()
186 file_ext = file_ext.lower()
187 if not file_ext.startswith('.'):
188 file_ext = '.' + file_ext
189
190 filenamepath = None
191 for file_name in os.listdir(search_dir):
192 file_name_lower = file_name.lower()
193 if file_name_keyword in file_name_lower and file_name_lower.endswith(file_ext):
194 if filenamepath:
195 self.logger.error('Multiple files found for *{0}*.{1} in '
196 'directory {2}'.format(file_name_keyword, file_ext, search_dir))
197 sys.exit()
198 filenamepath = os.path.abspath(os.path.join(search_dir, file_name))
199
200 if filenamepath:
201 return filenamepath
202 else:
203 self.logger.error("Cannot find *{0}*{1} in directory {2}".format(file_name_keyword, file_ext, search_dir))
204 sys.exit()
205
206 @staticmethod
207 def network_name_to_subnet_name(network_name):
208 """
209 :param network_name: example: vcpe_net_cpe_signal_201711281221
210 :return: vcpe_net_cpe_signal_subnet_201711281221
211 """
212 fields = network_name.split('_')
213 fields.insert(-1, 'subnet')
214 return '_'.join(fields)
215
216 def set_network_name(self, network_name):
217 param = ' '.join([k + ' ' + v for k, v in self.cloud.items()])
218 openstackcmd = 'openstack ' + param
219 cmd = ' '.join([openstackcmd, 'network set --name', network_name, 'ONAP-NW1'])
220 os.popen(cmd)
221
222 def set_subnet_name(self, network_name):
223 """
224 Example: network_name = vcpe_net_cpe_signal_201711281221
225 set subnet name to vcpe_net_cpe_signal_subnet_201711281221
226 :return:
227 """
228 param = ' '.join([k + ' ' + v for k, v in self.cloud.items()])
229 openstackcmd = 'openstack ' + param
230
231 # expected results: | subnets | subnet_id |
232 subnet_info = os.popen(openstackcmd + ' network show ' + network_name + ' |grep subnets').read().split('|')
233 if len(subnet_info) > 2 and subnet_info[1].strip() == 'subnets':
234 subnet_id = subnet_info[2].strip()
235 subnet_name = self.network_name_to_subnet_name(network_name)
236 cmd = ' '.join([openstackcmd, 'subnet set --name', subnet_name, subnet_id])
237 os.popen(cmd)
238 self.logger.info("Subnet name set to: " + subnet_name)
239 return True
240 else:
241 self.logger.error("Can't get subnet info from network name: " + network_name)
242 return False
243
244 def is_node_in_aai(self, node_type, node_uuid):
245 key = None
246 search_node_type = None
247 if node_type == 'service':
248 search_node_type = 'service-instance'
249 key = 'service-instance-id'
250 elif node_type == 'vnf':
251 search_node_type = 'generic-vnf'
252 key = 'vnf-id'
253 else:
254 logging.error('Invalid node_type: ' + node_type)
255 sys.exit()
256
257 url = 'https://{0}:8443/aai/v11/search/nodes-query?search-node-type={1}&filter={2}:EQUALS:{3}'.format(
258 self.hosts['aai-inst1'], search_node_type, key, node_uuid)
259
260 headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-FromAppID': 'vCPE-Robot'}
261 requests.packages.urllib3.disable_warnings()
262 r = requests.get(url, headers=headers, auth=self.aai_userpass, verify=False)
263 response = r.json()
264 self.logger.debug('aai query: ' + url)
265 self.logger.debug('aai response:\n' + json.dumps(response, indent=4, sort_keys=True))
266 return 'result-data' in response
267
268 @staticmethod
269 def extract_ip_from_str(net_addr, net_addr_len, sz):
270 """
271 :param net_addr: e.g. 10.5.12.0
272 :param net_addr_len: e.g. 24
273 :param sz: a string
274 :return: the first IP address matching the network, e.g. 10.5.12.3
275 """
276 network = ipaddress.ip_network(unicode('{0}/{1}'.format(net_addr, net_addr_len)), strict=False)
277 ip_list = re.findall(r'[0-9]+(?:\.[0-9]+){3}', sz)
278 for ip in ip_list:
279 this_net = ipaddress.ip_network(unicode('{0}/{1}'.format(ip, net_addr_len)), strict=False)
280 if this_net == network:
281 return str(ip)
282 return None
283
284 def get_vm_ip(self, keywords, net_addr=None, net_addr_len=None):
285 """
286 :param keywords: list of keywords to search for vm, e.g. ['bng', 'gmux', 'brg']
287 :param net_addr: e.g. 10.12.5.0
288 :param net_addr_len: e.g. 24
289 :return: dictionary {keyword: ip}
290 """
291 if not net_addr:
292 net_addr = self.external_net_addr
293
294 if not net_addr_len:
295 net_addr_len = self.external_net_prefix_len
296
297 param = ' '.join([k + ' ' + v for k, v in self.cloud.items() if 'identity' not in k])
298 openstackcmd = 'nova ' + param + ' list'
299 self.logger.debug(openstackcmd)
300
301 ip_dict = {}
302 results = os.popen(openstackcmd).read()
303 for line in results.split('\n'):
304 fields = line.split('|')
305 if len(fields) == 8:
306 vm_name = fields[2]
307 ip_info = fields[-2]
308 for keyword in keywords:
309 if keyword in vm_name:
310 ip = self.extract_ip_from_str(net_addr, net_addr_len, ip_info)
311 if ip:
312 ip_dict[keyword] = ip
313 if len(ip_dict) != len(keywords):
314 self.logger.error('Cannot find all desired IP addresses for %s.', keywords)
315 self.logger.error(json.dumps(ip_dict, indent=4, sort_keys=True))
316 sys.exit()
317 return ip_dict
318
319 def del_vgmux_ves_mode(self):
320 url = self.vpp_ves_url.format(self.hosts['mux']) + '/mode'
321 r = requests.delete(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass)
322 self.logger.debug('%s', r)
323
324 def del_vgmux_ves_collector(self):
325 url = self.vpp_ves_url.format(self.hosts['mux']) + '/config'
326 r = requests.delete(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass)
327 self.logger.debug('%s', r)
328
329 def set_vgmux_ves_collector(self ):
330 url = self.vpp_ves_url.format(self.hosts['mux'])
331 data = {'config':
332 {'server-addr': self.hosts['dcaedoks00'],
333 'server-port': '8080',
334 'read-interval': '10',
335 'is-add':'1'
336 }
337 }
338 r = requests.post(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass, json=data)
339 self.logger.debug('%s', r)
340
341 def set_vgmux_packet_loss_rate(self, lossrate, vg_vnf_instance_name):
342 url = self.vpp_ves_url.format(self.hosts['mux'])
343 data = {"mode":
344 {"working-mode": "demo",
345 "base-packet-loss": str(lossrate),
346 "source-name": vg_vnf_instance_name
347 }
348 }
349 r = requests.post(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass, json=data)
350 self.logger.debug('%s', r)
351
352 # return all the VxLAN interface names of BRG or vGMUX based on the IP address
353 def get_vxlan_interfaces(self, ip, print_info=False):
354 url = self.vpp_inf_url.format(ip)
355 self.logger.debug('url is this: %s', url)
356 r = requests.get(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass)
357 data = r.json()['interfaces']['interface']
358 if print_info:
359 for inf in data:
360 if 'name' in inf and 'type' in inf and inf['type'] == 'v3po:vxlan-tunnel':
361 print(json.dumps(inf, indent=4, sort_keys=True))
362
363 return [inf['name'] for inf in data if 'name' in inf and 'type' in inf and inf['type'] == 'v3po:vxlan-tunnel']
364
365 # delete all VxLAN interfaces of each hosts
366 def delete_vxlan_interfaces(self, host_dic):
367 for host, ip in host_dic.items():
368 deleted = False
369 self.logger.info('{0}: Getting VxLAN interfaces'.format(host))
370 inf_list = self.get_vxlan_interfaces(ip)
371 for inf in inf_list:
372 deleted = True
373 time.sleep(2)
374 self.logger.info("{0}: Deleting VxLAN crossconnect {1}".format(host, inf))
375 url = self.vpp_inf_url.format(ip) + '/interface/' + inf + '/v3po:l2'
376 requests.delete(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass)
377
378 for inf in inf_list:
379 deleted = True
380 time.sleep(2)
381 self.logger.info("{0}: Deleting VxLAN interface {1}".format(host, inf))
382 url = self.vpp_inf_url.format(ip) + '/interface/' + inf
383 requests.delete(url, headers=self.vpp_api_headers, auth=self.vpp_api_userpass)
384
385 if len(self.get_vxlan_interfaces(ip)) > 0:
386 self.logger.error("Error deleting VxLAN from {0}, try to restart the VM, IP is {1}.".format(host, ip))
387 return False
388
389 if not deleted:
390 self.logger.info("{0}: no VxLAN interface found, nothing to delete".format(host))
391 return True
392
393 @staticmethod
394 def save_object(obj, filepathname):
395 with open(filepathname, 'wb') as fout:
396 pickle.dump(obj, fout)
397
398 @staticmethod
399 def load_object(filepathname):
400 with open(filepathname, 'rb') as fin:
401 return pickle.load(fin)
402
403 def save_preload_data(self, preload_data):
404 self.save_object(preload_data, self.preload_dict_file)
405
406 def load_preload_data(self):
407 return self.load_object(self.preload_dict_file)
408
409 def save_vgmux_vnf_name(self, vgmux_vnf_name):
410 self.save_object(vgmux_vnf_name, self.vgmux_vnf_name_file)
411
412 def load_vgmux_vnf_name(self):
413 return self.load_object(self.vgmux_vnf_name_file)
414