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
25 # ############ CREDENTIALS OPENSTACK #############
26 def check_credentials():
28 Check if the OpenStack credentials (openrc) are sourced
30 env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
31 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
34 def get_credentials(service):
35 """Returns a creds dictionary filled with the following keys:
37 * password/api_key (depending on the service)
38 * tenant_name/project_id (depending on the service)
40 :param service: a string indicating the name of the service
41 requesting the credentials.
44 # Unfortunately, each of the OpenStack client will request slightly
45 # different entries in their credentials dict.
46 if service.lower() in ("nova", "cinder"):
51 tenant = "tenant_name"
53 # The most common way to pass these info to the script is to do it through
54 # environment variables.
56 "username": os.environ.get('OS_USERNAME', "admin"),
57 password: os.environ.get("OS_PASSWORD", 'admin'),
58 "auth_url": os.environ.get("OS_AUTH_URL",
59 "http://192.168.20.71:5000/v2.0"),
60 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
66 # ################ NOVA #################
67 def get_instances(nova_client):
69 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
75 def get_instance_status(nova_client, instance):
77 instance = nova_client.servers.get(instance.id)
78 return instance.status
83 def get_instance_by_name(nova_client, instance_name):
85 instance = nova_client.servers.find(name=instance_name)
91 def get_flavor_id(nova_client, flavor_name):
92 flavors = nova_client.flavors.list(detailed=True)
95 if f.name == flavor_name:
101 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
102 flavors = nova_client.flavors.list(detailed=True)
105 if min_ram <= f.ram and f.ram <= max_ram:
111 def delete_instance(nova_client, instance_id):
113 nova_client.servers.force_delete(instance_id)
116 print "Error:", sys.exc_info()[0]
120 def get_floating_ips(nova_client):
122 floating_ips = nova_client.floating_ips.list()
128 def delete_floating_ip(nova_client, floatingip_id):
130 nova_client.floating_ips.delete(floatingip_id)
133 print "Error:", sys.exc_info()[0]
137 # ################ NEUTRON #################
138 def create_neutron_net(neutron_client, name):
139 json_body = {'network': {'name': name,
140 'admin_state_up': True}}
142 network = neutron_client.create_network(body=json_body)
143 network_dict = network['network']
144 return network_dict['id']
146 print "Error:", sys.exc_info()[0]
150 def update_neutron_net(neutron_client, network_id, shared=False):
151 json_body = {'network': {'shared': shared}}
153 neutron_client.update_network(network_id, body=json_body)
156 print "Error:", sys.exc_info()[0]
160 def delete_neutron_net(neutron_client, network_id):
162 neutron_client.delete_network(network_id)
165 print "Error:", sys.exc_info()[0]
169 def create_neutron_subnet(neutron_client, name, cidr, net_id):
170 json_body = {'subnets': [{'name': name, 'cidr': cidr,
171 'ip_version': 4, 'network_id': net_id}]}
173 subnet = neutron_client.create_subnet(body=json_body)
174 return subnet['subnets'][0]['id']
176 print "Error:", sys.exc_info()[0]
180 def delete_neutron_subnet(neutron_client, subnet_id):
182 neutron_client.delete_subnet(subnet_id)
185 print "Error:", sys.exc_info()[0]
189 def create_neutron_router(neutron_client, name):
190 json_body = {'router': {'name': name, 'admin_state_up': True}}
192 router = neutron_client.create_router(json_body)
193 return router['router']['id']
195 print "Error:", sys.exc_info()[0]
199 def delete_neutron_router(neutron_client, router_id):
200 json_body = {'router': {'id': router_id}}
202 neutron_client.delete_router(router=router_id)
205 print "Error:", sys.exc_info()[0]
209 def add_interface_router(neutron_client, router_id, subnet_id):
210 json_body = {"subnet_id": subnet_id}
212 neutron_client.add_interface_router(router=router_id, body=json_body)
215 print "Error:", sys.exc_info()[0]
219 def remove_interface_router(neutron_client, router_id, subnet_id):
220 json_body = {"subnet_id": subnet_id}
222 neutron_client.remove_interface_router(router=router_id,
226 print "Error:", sys.exc_info()[0]
230 def remove_gateway_router(neutron_client, router_id):
232 neutron_client.remove_gateway_router(router_id)
235 print "Error:", sys.exc_info()[0]
239 def create_neutron_port(neutron_client, name, network_id, ip):
240 json_body = {'port': {
241 'admin_state_up': True,
243 'network_id': network_id,
244 'fixed_ips': [{"ip_address": ip}]
247 port = neutron_client.create_port(body=json_body)
248 return port['port']['id']
250 print "Error:", sys.exc_info()[0]
254 def update_neutron_port(neutron_client, port_id, device_owner):
255 json_body = {'port': {
256 'device_owner': device_owner,
259 port = neutron_client.update_port(port=port_id,
261 return port['port']['id']
263 print "Error:", sys.exc_info()[0]
267 def delete_neutron_port(neutron_client, port_id):
269 neutron_client.delete_port(port_id)
272 print "Error:", sys.exc_info()[0]
276 def get_network_id(neutron_client, network_name):
277 networks = neutron_client.list_networks()['networks']
280 if n['name'] == network_name:
286 def check_neutron_net(neutron_client, net_name):
287 for network in neutron_client.list_networks()['networks']:
288 if network['name'] == net_name:
289 for subnet in network['subnets']:
294 def get_network_list(neutron_client):
295 network_list = neutron_client.list_networks()['networks']
296 if len(network_list) == 0:
302 def get_router_list(neutron_client):
303 router_list = neutron_client.list_routers()['routers']
304 if len(router_list) == 0:
310 def get_port_list(neutron_client):
311 port_list = neutron_client.list_ports()['ports']
312 if len(port_list) == 0:
318 def get_external_net(neutron_client):
319 for network in neutron_client.list_networks()['networks']:
320 if network['router:external']:
321 return network['name']
325 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
326 json_body = {"quota": {
327 "security_group": sg_quota,
328 "security_group_rule": sg_rule_quota
332 quota = neutron_client.update_quota(tenant_id=tenant_id,
336 print "Error:", sys.exc_info()[0]
340 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
341 snapshots_quota, gigabytes_quota):
342 quotas_values = {"volumes": vols_quota,
343 "snapshots": snapshots_quota,
344 "gigabytes": gigabytes_quota}
347 quotas_default = cinder_client. quotas.update(tenant_id,
351 print "Error:", sys.exc_info()[0]
355 def get_private_net(neutron_client):
356 # Checks if there is an existing shared private network
357 networks = neutron_client.list_networks()['networks']
358 if len(networks) == 0:
361 if (net['router:external'] is False) and (net['shared'] is True):
366 # ################ GLANCE #################
367 def get_images(nova_client):
369 images = nova_client.images.list()
375 def get_image_id(glance_client, image_name):
376 images = glance_client.images.list()
379 if i.name == image_name:
385 def create_glance_image(glance_client, image_name, file_path, public=True):
386 if not os.path.isfile(file_path):
387 print "Error: file " + file_path + " does not exist."
390 with open(file_path) as fimage:
391 image = glance_client.images.create(name=image_name,
394 container_format="bare",
398 print "Error:", sys.exc_info()[0]
402 def delete_glance_image(nova_client, image_id):
404 nova_client.images.delete(image_id)
407 print "Error:", sys.exc_info()[0]
411 # ################ CINDER #################
412 def get_volumes(cinder_client):
414 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
420 def delete_volume(cinder_client, volume_id, forced=False):
424 cinder_client.volumes.detach(volume_id)
426 print "Error:", sys.exc_info()[0]
427 cinder_client.volumes.force_delete(volume_id)
429 cinder_client.volumes.delete(volume_id)
432 print "Error:", sys.exc_info()[0]
436 # ################ CINDER #################
437 def get_security_groups(neutron_client):
439 security_groups = neutron_client.list_security_groups()[
441 return security_groups
446 def delete_security_group(neutron_client, secgroup_id):
448 neutron_client.delete_security_group(secgroup_id)
451 print "Error:", sys.exc_info()[0]
455 # ################ KEYSTONE #################
456 def get_tenants(keystone_client):
458 tenants = keystone_client.tenants.list()
464 def get_tenant_id(keystone_client, tenant_name):
465 tenants = keystone_client.tenants.list()
468 if t.name == tenant_name:
474 def get_users(keystone_client):
476 users = keystone_client.users.list()
482 def get_role_id(keystone_client, role_name):
483 roles = keystone_client.roles.list()
486 if r.name == role_name:
492 def get_user_id(keystone_client, user_name):
493 users = keystone_client.users.list()
496 if u.name == user_name:
502 def create_tenant(keystone_client, tenant_name, tenant_description):
504 tenant = keystone_client.tenants.create(tenant_name,
509 print "Error:", sys.exc_info()[0]
513 def delete_tenant(keystone_client, tenant_id):
515 tenant = keystone_client.tenants.delete(tenant_id)
518 print "Error:", sys.exc_info()[0]
522 def create_user(keystone_client, user_name, user_password,
523 user_email, tenant_id):
525 user = keystone_client.users.create(user_name, user_password,
526 user_email, tenant_id,
530 print "Error:", sys.exc_info()[0]
534 def delete_user(keystone_client, user_id):
536 tenant = keystone_client.users.delete(user_id)
539 print "Error:", sys.exc_info()[0]
543 def add_role_user(keystone_client, user_id, role_id, tenant_id):
545 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
548 print "Error:", sys.exc_info()[0]
552 # ################ UTILS #################
553 def check_internet_connectivity(url='http://www.opnfv.org/'):
555 Check if there is access to the internet
558 urllib2.urlopen(url, timeout=5)
560 except urllib2.URLError:
564 def download_url(url, dest_path):
566 Download a file to a destination path given a URL
568 name = url.rsplit('/')[-1]
569 dest = dest_path + "/" + name
571 response = urllib2.urlopen(url)
572 except (urllib2.HTTPError, urllib2.URLError):
575 with open(dest, 'wb') as f:
576 shutil.copyfileobj(response, f)
580 def execute_command(cmd, logger=None, exit_on_error=True):
582 Execute Linux command
585 logger.debug('Executing command : {}'.format(cmd))
586 output_file = "output.txt"
587 f = open(output_file, 'w+')
588 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
590 f = open(output_file, 'r')
592 if result != "" and logger:
598 logger.error("Error when executing command %s" % cmd)
604 def get_git_branch(repo_path):
608 repo = Repo(repo_path)
609 branch = repo.active_branch
613 def get_installer_type(logger=None):
615 Get installer type (fuel, apex, joid, compass)
618 installer = os.environ['INSTALLER_TYPE']
621 logger.error("Impossible to retrieve the installer type")
627 def get_pod_name(logger=None):
629 Get PoD Name from env variable NODE_NAME
632 return os.environ['NODE_NAME']
636 "Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
640 def push_results_to_db(db_url, case_name, logger, pod_name,
641 git_version, payload):
642 url = db_url + "/results"
643 installer = get_installer_type(logger)
644 params = {"project_name": "functest", "case_name": case_name,
645 "pod_name": pod_name, "installer": installer,
646 "version": git_version, "details": payload}
648 headers = {'Content-Type': 'application/json'}
650 r = requests.post(url, data=json.dumps(params), headers=headers)
655 print "Error:", sys.exc_info()[0]
659 def get_resolvconf_ns():
661 rconf = open("/etc/resolv.conf", "r")
662 line = rconf.readline()
664 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
666 nameservers.append(ip.group())
667 line = rconf.readline()
670 def getTestEnv(test, functest_yaml):
671 # get the config of the testcase based on functest_config.yaml
673 # - test = test project e.g; ovno
674 # - test = testcase e.g. functest/odl
675 # look for the / to see if it is a test project or a testcase
677 TEST_ENV = functest_yaml.get("test-dependencies")
679 if test.find("/") < 0:
680 config_test = TEST_ENV[test]
682 test_split = test.split("/")
683 testproject = test_split[0]
684 testcase = test_split[1]
685 config_test = TEST_ENV[testproject][testcase]
687 # if not defined in dependencies => no dependencies
690 print "Error getTestEnv:", sys.exc_info()[0]
695 def get_ci_envvars():
697 Get the CI env variables
700 "installer": os.environ.get('INSTALLER_TYPE'),
701 "scenario": os.environ.get('DEPLOY_SCENARIO')}
705 def isTestRunnable(test, functest_yaml):
706 # By default we assume that all the tests are always runnable...
708 # Retrieve CI environment
709 ci_env = get_ci_envvars()
710 # Retrieve test environement from config file
711 test_env = getTestEnv(test, functest_yaml)
713 # if test_env not empty => dependencies to be checked
714 if test_env is not None and len(test_env) > 0:
715 # possible criteria = ["installer", "scenario"]
716 # consider test criteria from config file
717 # compare towards CI env through CI en variable
718 for criteria in test_env:
719 if re.search(test_env[criteria], ci_env[criteria]) is None:
720 # print "Test "+ test + " cannot be run on the environment"
725 def generateTestcaseList(functest_yaml):
728 testcase_list = functest_yaml.get("test-dependencies")
729 projects = testcase_list.keys()
731 for project in projects:
732 testcases = testcase_list[project]
733 # 1 or 2 levels for testcases project[/case]
734 # if only project name without controller or scenario
735 # => shall be runnable on any controller/scenario
736 if testcases is None:
737 test_list += project + " "
739 for testcase in testcases:
740 if testcase == "installer" or testcase == "scenario":
742 if isTestRunnable(project, functest_yaml):
743 test_list += project + " "
745 # project/testcase (2 levels)
746 thetest = project + "/" + testcase
747 if isTestRunnable(thetest, functest_yaml):
748 test_list += testcase + " "
750 # sort the list to execute the test in the right order
751 test_order_list = functest_yaml.get("test_exec_priority")
752 test_sorted_list = ""
753 for test in test_order_list:
754 if test_order_list[test] in test_list:
755 test_sorted_list += test_order_list[test] + " "
757 # create a file that could be consumed by run-test.sh
758 # this method is used only for CI
759 # so it can be run only in container
760 # reuse default conf directory to store the list of runnable tests
761 file = open("/home/opnfv/functest/conf/testcase-list.txt", 'w')
762 file.write(test_sorted_list)
765 return test_sorted_list