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
22 # ############ CREDENTIALS OPENSTACK #############
23 def check_credentials():
25 Check if the OpenStack credentials (openrc) are sourced
27 env_vars = ['OS_AUTH_URL','OS_USERNAME','OS_PASSWORD','OS_TENANT_NAME']
28 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
31 def get_credentials(service):
32 """Returns a creds dictionary filled with the following keys:
34 * password/api_key (depending on the service)
35 * tenant_name/project_id (depending on the service)
37 :param service: a string indicating the name of the service
38 requesting the credentials.
41 # Unfortunately, each of the OpenStack client will request slightly
42 # different entries in their credentials dict.
43 if service.lower() in ("nova", "cinder"):
48 tenant = "tenant_name"
50 # The most common way to pass these info to the script is to do it through
51 # environment variables.
53 "username": os.environ.get('OS_USERNAME', "admin"),
54 password: os.environ.get("OS_PASSWORD", 'admin'),
55 "auth_url": os.environ.get("OS_AUTH_URL",
56 "http://192.168.20.71:5000/v2.0"),
57 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
63 # ################ NOVA #################
64 def get_instances(nova_client):
66 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
71 def get_instance_status(nova_client, instance):
73 instance = nova_client.servers.get(instance.id)
74 return instance.status
78 def get_instance_by_name(nova_client, instance_name):
80 instance = nova_client.servers.find(name=instance_name)
87 def get_flavor_id(nova_client, flavor_name):
88 flavors = nova_client.flavors.list(detailed=True)
91 if f.name == flavor_name:
97 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
98 flavors = nova_client.flavors.list(detailed=True)
101 if min_ram <= f.ram and f.ram <= max_ram:
107 def delete_instance(nova_client, instance_id):
109 nova_client.servers.force_delete(instance_id)
112 print "Error:", sys.exc_info()[0]
116 def get_floating_ips(nova_client):
118 floating_ips = nova_client.floating_ips.list()
123 def delete_floating_ip(nova_client, floatingip_id):
125 nova_client.floating_ips.delete(floatingip_id)
128 print "Error:", sys.exc_info()[0]
132 # ################ NEUTRON #################
133 def create_neutron_net(neutron_client, name):
134 json_body = {'network': {'name': name,
135 'admin_state_up': True}}
137 network = neutron_client.create_network(body=json_body)
138 network_dict = network['network']
139 return network_dict['id']
141 print "Error:", sys.exc_info()[0]
145 def delete_neutron_net(neutron_client, network_id):
147 neutron_client.delete_network(network_id)
150 print "Error:", sys.exc_info()[0]
154 def create_neutron_subnet(neutron_client, name, cidr, net_id):
155 json_body = {'subnets': [{'name': name, 'cidr': cidr,
156 'ip_version': 4, 'network_id': net_id}]}
158 subnet = neutron_client.create_subnet(body=json_body)
159 return subnet['subnets'][0]['id']
161 print "Error:", sys.exc_info()[0]
165 def delete_neutron_subnet(neutron_client, subnet_id):
167 neutron_client.delete_subnet(subnet_id)
170 print "Error:", sys.exc_info()[0]
174 def create_neutron_router(neutron_client, name):
175 json_body = {'router': {'name': name, 'admin_state_up': True}}
177 router = neutron_client.create_router(json_body)
178 return router['router']['id']
180 print "Error:", sys.exc_info()[0]
184 def delete_neutron_router(neutron_client, router_id):
185 json_body = {'router': {'id': router_id}}
187 neutron_client.delete_router(router=router_id)
190 print "Error:", sys.exc_info()[0]
194 def add_interface_router(neutron_client, router_id, subnet_id):
195 json_body = {"subnet_id": subnet_id}
197 neutron_client.add_interface_router(router=router_id, body=json_body)
200 print "Error:", sys.exc_info()[0]
204 def remove_interface_router(neutron_client, router_id, subnet_id):
205 json_body = {"subnet_id": subnet_id}
207 neutron_client.remove_interface_router(router=router_id,
211 print "Error:", sys.exc_info()[0]
214 def remove_gateway_router(neutron_client, router_id):
216 neutron_client.remove_gateway_router(router_id)
219 print "Error:", sys.exc_info()[0]
223 def create_neutron_port(neutron_client, name, network_id, ip):
224 json_body = {'port': {
225 'admin_state_up': True,
227 'network_id': network_id,
228 'fixed_ips': [{"ip_address": ip}]
231 port = neutron_client.create_port(body=json_body)
232 return port['port']['id']
234 print "Error:", sys.exc_info()[0]
238 def delete_neutron_port(neutron_client, port_id):
240 neutron_client.delete_port(port_id)
243 print "Error:", sys.exc_info()[0]
247 def get_network_id(neutron_client, network_name):
248 networks = neutron_client.list_networks()['networks']
251 if n['name'] == network_name:
257 def check_neutron_net(neutron_client, net_name):
258 for network in neutron_client.list_networks()['networks']:
259 if network['name'] == net_name:
260 for subnet in network['subnets']:
265 def get_network_list(neutron_client):
266 network_list = neutron_client.list_networks()['networks']
267 if len(network_list) == 0:
273 def get_router_list(neutron_client):
274 router_list = neutron_client.list_routers()['routers']
275 if len(router_list) == 0:
280 def get_port_list(neutron_client):
281 port_list = neutron_client.list_ports()['ports']
282 if len(port_list) == 0:
289 def get_external_net(neutron_client):
290 for network in neutron_client.list_networks()['networks']:
291 if network['router:external']:
292 return network['name']
296 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
297 json_body = {"quota": {
298 "security_group": sg_quota,
299 "security_group_rule": sg_rule_quota
303 quota = neutron_client.update_quota(tenant_id=tenant_id,
307 print "Error:", sys.exc_info()[0]
311 def get_private_net(neutron_client):
312 # Checks if there is an existing private network
313 networks = neutron_client.list_networks()['networks']
314 if len(networks) == 0:
317 if net['router:external'] == False:
321 # ################ GLANCE #################
322 def get_images(nova_client):
324 images = nova_client.images.list()
330 def get_image_id(glance_client, image_name):
331 images = glance_client.images.list()
334 if i.name == image_name:
340 def create_glance_image(glance_client, image_name, file_path, public=True):
341 if not os.path.isfile(file_path):
342 print "Error: file "+file_path+" does not exist."
345 with open(file_path) as fimage:
346 image = glance_client.images.create(name=image_name,
349 container_format="bare",
353 print "Error:", sys.exc_info()[0]
356 def delete_glance_image(nova_client, image_id):
358 nova_client.images.delete(image_id)
361 print "Error:", sys.exc_info()[0]
364 # ################ CINDER #################
365 def get_volumes(cinder_client):
367 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
372 def delete_volume(cinder_client, volume_id):
374 cinder_client.volumes.delete(volume_id)
377 print "Error:", sys.exc_info()[0]
380 # ################ CINDER #################
381 def get_security_groups(neutron_client):
383 security_groups = neutron_client.list_security_groups()['security_groups']
384 return security_groups
388 def delete_security_group(neutron_client, secgroup_id):
390 neutron_client.delete_security_group(secgroup_id)
393 print "Error:", sys.exc_info()[0]
397 # ################ KEYSTONE #################
398 def get_tenants(keystone_client):
400 tenants = keystone_client.tenants.list()
406 def get_tenant_id(keystone_client, tenant_name):
407 tenants = keystone_client.tenants.list()
410 if t.name == tenant_name:
415 def get_users(keystone_client):
417 users = keystone_client.users.list()
422 def get_role_id(keystone_client, role_name):
423 roles = keystone_client.roles.list()
426 if r.name == role_name:
432 def get_user_id(keystone_client, user_name):
433 users = keystone_client.users.list()
436 if u.name == user_name:
442 def create_tenant(keystone_client, tenant_name, tenant_description):
444 tenant = keystone_client.tenants.create(tenant_name,
449 print "Error:", sys.exc_info()[0]
453 def delete_tenant(keystone_client, tenant_id):
455 tenant = keystone_client.tenants.delete(tenant_id)
458 print "Error:", sys.exc_info()[0]
462 def create_user(keystone_client, user_name, user_password,
463 user_email, tenant_id):
465 user = keystone_client.users.create(user_name, user_password,
466 user_email, tenant_id,
470 print "Error:", sys.exc_info()[0]
474 def delete_user(keystone_client, user_id):
476 tenant = keystone_client.users.delete(user_id)
479 print "Error:", sys.exc_info()[0]
483 def add_role_user(keystone_client, user_id, role_id, tenant_id):
485 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
488 print "Error:", sys.exc_info()[0]
492 # ################ UTILS #################
493 def check_internet_connectivity(url='http://www.opnfv.org/'):
495 Check if there is access to the internet
498 urllib2.urlopen(url, timeout=5)
500 except urllib2.URLError:
504 def download_url(url, dest_path):
506 Download a file to a destination path given a URL
508 name = url.rsplit('/')[-1]
509 dest = dest_path + "/" + name
511 response = urllib2.urlopen(url)
512 except (urllib2.HTTPError, urllib2.URLError):
515 with open(dest, 'wb') as f:
516 f.write(response.read())
520 def execute_command(cmd, logger=None):
522 Execute Linux command
525 logger.debug('Executing command : {}'.format(cmd))
526 output_file = "output.txt"
527 f = open(output_file, 'w+')
528 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
530 f = open(output_file, 'r')
532 if result != "" and logger:
538 logger.error("Error when executing command %s" % cmd)
542 def get_git_branch(repo_path):
546 repo = Repo(repo_path)
547 branch = repo.active_branch
551 def get_installer_type(logger=None):
553 Get installer type (fuel, foreman, apex, joid, compass)
556 installer = os.environ['INSTALLER_TYPE']
559 logger.error("Impossible to retrieve the installer type")
565 def get_pod_name(logger=None):
567 Get PoD Name from env variable NODE_NAME
570 return os.environ['NODE_NAME']
573 logger.error("Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
577 def push_results_to_db(db_url, case_name, logger, pod_name, git_version, payload):
578 url = db_url + "/results"
579 installer = get_installer_type(logger)
580 params = {"project_name": "functest", "case_name": case_name,
581 "pod_name": pod_name, "installer": installer,
582 "version": git_version, "details": payload}
584 headers = {'Content-Type': 'application/json'}
586 r = requests.post(url, data=json.dumps(params), headers=headers)
590 print "Error:", sys.exc_info()[0]