3 # jose.lausuch@ericsson.com
4 # valentin.boucher@orange.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
21 # ############ CREDENTIALS OPENSTACK #############
22 def check_credentials():
24 Check if the OpenStack credentials (openrc) are sourced
26 env_vars = ['OS_AUTH_URL','OS_USERNAME','OS_PASSWORD','OS_TENANT_NAME']
27 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
30 def get_credentials(service):
31 """Returns a creds dictionary filled with the following keys:
33 * password/api_key (depending on the service)
34 * tenant_name/project_id (depending on the service)
36 :param service: a string indicating the name of the service
37 requesting the credentials.
40 # Unfortunately, each of the OpenStack client will request slightly
41 # different entries in their credentials dict.
42 if service.lower() in ("nova", "cinder"):
47 tenant = "tenant_name"
49 # The most common way to pass these info to the script is to do it through
50 # environment variables.
52 "username": os.environ.get('OS_USERNAME', "admin"),
53 password: os.environ.get("OS_PASSWORD", 'admin'),
54 "auth_url": os.environ.get("OS_AUTH_URL",
55 "http://192.168.20.71:5000/v2.0"),
56 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
62 # ################ NOVA #################
63 def get_instances(nova_client):
65 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
70 def get_instance_status(nova_client, instance):
72 instance = nova_client.servers.get(instance.id)
73 return instance.status
77 def get_instance_by_name(nova_client, instance_name):
79 instance = nova_client.servers.find(name=instance_name)
86 def get_flavor_id(nova_client, flavor_name):
87 flavors = nova_client.flavors.list(detailed=True)
90 if f.name == flavor_name:
96 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
97 flavors = nova_client.flavors.list(detailed=True)
100 if min_ram <= f.ram and f.ram <= max_ram:
106 def delete_instance(nova_client, instance_id):
108 nova_client.servers.force_delete(instance_id)
111 print "Error:", sys.exc_info()[0]
115 def get_floating_ips(nova_client):
117 floating_ips = nova_client.floating_ips.list()
122 def delete_floating_ip(nova_client, floatingip_id):
124 nova_client.floating_ips.delete(floatingip_id)
127 print "Error:", sys.exc_info()[0]
131 # ################ NEUTRON #################
132 def create_neutron_net(neutron_client, name):
133 json_body = {'network': {'name': name,
134 'admin_state_up': True}}
136 network = neutron_client.create_network(body=json_body)
137 network_dict = network['network']
138 return network_dict['id']
140 print "Error:", sys.exc_info()[0]
144 def delete_neutron_net(neutron_client, network_id):
146 neutron_client.delete_network(network_id)
149 print "Error:", sys.exc_info()[0]
153 def create_neutron_subnet(neutron_client, name, cidr, net_id):
154 json_body = {'subnets': [{'name': name, 'cidr': cidr,
155 'ip_version': 4, 'network_id': net_id}]}
157 subnet = neutron_client.create_subnet(body=json_body)
158 return subnet['subnets'][0]['id']
160 print "Error:", sys.exc_info()[0]
164 def delete_neutron_subnet(neutron_client, subnet_id):
166 neutron_client.delete_subnet(subnet_id)
169 print "Error:", sys.exc_info()[0]
173 def create_neutron_router(neutron_client, name):
174 json_body = {'router': {'name': name, 'admin_state_up': True}}
176 router = neutron_client.create_router(json_body)
177 return router['router']['id']
179 print "Error:", sys.exc_info()[0]
183 def delete_neutron_router(neutron_client, router_id):
184 json_body = {'router': {'id': router_id}}
186 neutron_client.delete_router(router=router_id)
189 print "Error:", sys.exc_info()[0]
193 def add_interface_router(neutron_client, router_id, subnet_id):
194 json_body = {"subnet_id": subnet_id}
196 neutron_client.add_interface_router(router=router_id, body=json_body)
199 print "Error:", sys.exc_info()[0]
203 def remove_interface_router(neutron_client, router_id, subnet_id):
204 json_body = {"subnet_id": subnet_id}
206 neutron_client.remove_interface_router(router=router_id,
210 print "Error:", sys.exc_info()[0]
213 def remove_gateway_router(neutron_client, router_id):
215 neutron_client.remove_gateway_router(router_id)
218 print "Error:", sys.exc_info()[0]
222 def create_neutron_port(neutron_client, name, network_id, ip):
223 json_body = {'port': {
224 'admin_state_up': True,
226 'network_id': network_id,
227 'fixed_ips': [{"ip_address": ip}]
230 port = neutron_client.create_port(body=json_body)
231 return port['port']['id']
233 print "Error:", sys.exc_info()[0]
237 def delete_neutron_port(neutron_client, port_id):
239 neutron_client.delete_port(port_id)
242 print "Error:", sys.exc_info()[0]
246 def get_network_id(neutron_client, network_name):
247 networks = neutron_client.list_networks()['networks']
250 if n['name'] == network_name:
256 def check_neutron_net(neutron_client, net_name):
257 for network in neutron_client.list_networks()['networks']:
258 if network['name'] == net_name:
259 for subnet in network['subnets']:
264 def get_network_list(neutron_client):
265 network_list = neutron_client.list_networks()['networks']
266 if len(network_list) == 0:
272 def get_router_list(neutron_client):
273 router_list = neutron_client.list_routers()['routers']
274 if len(router_list) == 0:
279 def get_port_list(neutron_client):
280 port_list = neutron_client.list_ports()['ports']
281 if len(port_list) == 0:
288 def get_external_net(neutron_client):
289 for network in neutron_client.list_networks()['networks']:
290 if network['router:external']:
291 return network['name']
295 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
296 json_body = {"quota": {
297 "security_group": sg_quota,
298 "security_group_rule": sg_rule_quota
302 quota = neutron_client.update_quota(tenant_id=tenant_id,
306 print "Error:", sys.exc_info()[0]
310 def get_private_net(neutron_client):
311 # Checks if there is an existing private network
312 networks = neutron_client.list_networks()['networks']
313 if len(networks) == 0:
316 if net['router:external'] == False:
320 # ################ GLANCE #################
321 def get_images(nova_client):
323 images = nova_client.images.list()
329 def get_image_id(glance_client, image_name):
330 images = glance_client.images.list()
333 if i.name == image_name:
339 def create_glance_image(glance_client, image_name, file_path, is_public=True):
341 with open(file_path) as fimage:
342 image = glance_client.images.create(name=image_name,
345 container_format="bare",
351 def delete_glance_image(nova_client, image_id):
353 nova_client.images.delete(image_id)
356 print "Error:", sys.exc_info()[0]
359 # ################ CINDER #################
360 def get_volumes(cinder_client):
362 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
367 def delete_volume(cinder_client, volume_id):
369 cinder_client.volumes.delete(volume_id)
372 print "Error:", sys.exc_info()[0]
375 # ################ CINDER #################
376 def get_security_groups(neutron_client):
378 security_groups = neutron_client.list_security_groups()['security_groups']
379 return security_groups
383 def delete_security_group(neutron_client, secgroup_id):
385 neutron_client.delete_security_group(secgroup_id)
388 print "Error:", sys.exc_info()[0]
392 # ################ KEYSTONE #################
393 def get_tenants(keystone_client):
395 tenants = keystone_client.tenants.list()
401 def get_tenant_id(keystone_client, tenant_name):
402 tenants = keystone_client.tenants.list()
405 if t.name == tenant_name:
410 def get_users(keystone_client):
412 users = keystone_client.users.list()
417 def get_role_id(keystone_client, role_name):
418 roles = keystone_client.roles.list()
421 if r.name == role_name:
427 def get_user_id(keystone_client, user_name):
428 users = keystone_client.users.list()
431 if u.name == user_name:
437 def create_tenant(keystone_client, tenant_name, tenant_description):
439 tenant = keystone_client.tenants.create(tenant_name,
444 print "Error:", sys.exc_info()[0]
448 def delete_tenant(keystone_client, tenant_id):
450 tenant = keystone_client.tenants.delete(tenant_id)
453 print "Error:", sys.exc_info()[0]
457 def create_user(keystone_client, user_name, user_password,
458 user_email, tenant_id):
460 user = keystone_client.users.create(user_name, user_password,
461 user_email, tenant_id,
465 print "Error:", sys.exc_info()[0]
469 def delete_user(keystone_client, user_id):
471 tenant = keystone_client.users.delete(user_id)
474 print "Error:", sys.exc_info()[0]
478 def add_role_user(keystone_client, user_id, role_id, tenant_id):
480 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
483 print "Error:", sys.exc_info()[0]
487 # ################ UTILS #################
488 def check_internet_connectivity(url='http://www.opnfv.org/'):
490 Check if there is access to the internet
493 urllib2.urlopen(url, timeout=5)
495 except urllib2.URLError:
499 def download_url(url, dest_path):
501 Download a file to a destination path given a URL
503 name = url.rsplit('/')[-1]
504 dest = dest_path + "/" + name
506 response = urllib2.urlopen(url)
507 except (urllib2.HTTPError, urllib2.URLError):
510 with open(dest, 'wb') as f:
511 f.write(response.read())
515 def execute_command(cmd, logger=None):
517 Execute Linux command
520 logger.debug('Executing command : {}'.format(cmd))
521 output_file = "output.txt"
522 f = open(output_file, 'w+')
523 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
525 f = open(output_file, 'r')
527 if result != "" and logger:
533 logger.error("Error when executing command %s" % cmd)
537 def get_git_branch(repo_path):
541 repo = Repo(repo_path)
542 branch = repo.active_branch
546 def get_installer_type(logger=None):
548 Get installer type (fuel, foreman, apex, joid, compass)
551 installer = os.environ['INSTALLER_TYPE']
554 logger.error("Impossible to retrieve the installer type")
560 def get_pod_name(logger=None):
562 Get PoD Name from env variable NODE_NAME
565 return os.environ['NODE_NAME']
568 logger.error("Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
572 def push_results_to_db(db_url, case_name, logger, pod_name, git_version, payload):
573 url = db_url + "/results"
574 installer = get_installer_type(logger)
575 params = {"project_name": "functest", "case_name": case_name,
576 "pod_name": pod_name, "installer": installer,
577 "version": git_version, "details": payload}
579 headers = {'Content-Type': 'application/json'}
581 r = requests.post(url, data=json.dumps(params), headers=headers)
585 print "Error:", sys.exc_info()[0]