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
26 # ############ CREDENTIALS OPENSTACK #############
27 def check_credentials():
29 Check if the OpenStack credentials (openrc) are sourced
31 env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
32 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
35 def get_credentials(service):
36 """Returns a creds dictionary filled with the following keys:
38 * password/api_key (depending on the service)
39 * tenant_name/project_id (depending on the service)
41 :param service: a string indicating the name of the service
42 requesting the credentials.
45 # Unfortunately, each of the OpenStack client will request slightly
46 # different entries in their credentials dict.
47 if service.lower() in ("nova", "cinder"):
52 tenant = "tenant_name"
54 # The most common way to pass these info to the script is to do it through
55 # environment variables.
57 "username": os.environ.get('OS_USERNAME', "admin"),
58 password: os.environ.get("OS_PASSWORD", 'admin'),
59 "auth_url": os.environ.get("OS_AUTH_URL",
60 "http://192.168.20.71:5000/v2.0"),
61 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
67 # ################ NOVA #################
68 def get_instances(nova_client):
70 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
76 def get_instance_status(nova_client, instance):
78 instance = nova_client.servers.get(instance.id)
79 return instance.status
84 def get_instance_by_name(nova_client, instance_name):
86 instance = nova_client.servers.find(name=instance_name)
92 def get_flavor_id(nova_client, flavor_name):
93 flavors = nova_client.flavors.list(detailed=True)
96 if f.name == flavor_name:
102 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
103 flavors = nova_client.flavors.list(detailed=True)
106 if min_ram <= f.ram and f.ram <= max_ram:
112 def delete_instance(nova_client, instance_id):
114 nova_client.servers.force_delete(instance_id)
117 print "Error:", sys.exc_info()[0]
120 def create_floating_ip(neutron_client):
121 extnet_id = get_external_net_id(neutron_client)
122 props = {'floating_network_id': extnet_id}
124 ip_json = neutron_client.create_floatingip({'floatingip': props})
125 floating_ip = ip_json['floatingip']['floating_ip_address']
130 def get_floating_ips(nova_client):
132 floating_ips = nova_client.floating_ips.list()
137 def add_floating_ip(nova_client, server_id, floatingip_id):
139 nova_client.servers.add_floating_ip(server_id,floatingip_id)
142 print "Error:", sys.exc_info()[0]
145 def delete_floating_ip(nova_client, floatingip_id):
147 nova_client.floating_ips.delete(floatingip_id)
150 print "Error:", sys.exc_info()[0]
154 # ################ NEUTRON #################
155 def create_neutron_net(neutron_client, name):
156 json_body = {'network': {'name': name,
157 'admin_state_up': True}}
159 network = neutron_client.create_network(body=json_body)
160 network_dict = network['network']
161 return network_dict['id']
163 print "Error:", sys.exc_info()[0]
167 def update_neutron_net(neutron_client, network_id, shared=False):
168 json_body = {'network': {'shared': shared}}
170 neutron_client.update_network(network_id, body=json_body)
173 print "Error:", sys.exc_info()[0]
177 def delete_neutron_net(neutron_client, network_id):
179 neutron_client.delete_network(network_id)
182 print "Error:", sys.exc_info()[0]
186 def create_neutron_subnet(neutron_client, name, cidr, net_id):
187 json_body = {'subnets': [{'name': name, 'cidr': cidr,
188 'ip_version': 4, 'network_id': net_id}]}
190 subnet = neutron_client.create_subnet(body=json_body)
191 return subnet['subnets'][0]['id']
193 print "Error:", sys.exc_info()[0]
197 def delete_neutron_subnet(neutron_client, subnet_id):
199 neutron_client.delete_subnet(subnet_id)
202 print "Error:", sys.exc_info()[0]
206 def create_neutron_router(neutron_client, name):
207 json_body = {'router': {'name': name, 'admin_state_up': True}}
209 router = neutron_client.create_router(json_body)
210 return router['router']['id']
212 print "Error:", sys.exc_info()[0]
216 def delete_neutron_router(neutron_client, router_id):
217 json_body = {'router': {'id': router_id}}
219 neutron_client.delete_router(router=router_id)
222 print "Error:", sys.exc_info()[0]
226 def add_interface_router(neutron_client, router_id, subnet_id):
227 json_body = {"subnet_id": subnet_id}
229 neutron_client.add_interface_router(router=router_id, body=json_body)
232 print "Error:", sys.exc_info()[0]
236 def remove_interface_router(neutron_client, router_id, subnet_id):
237 json_body = {"subnet_id": subnet_id}
239 neutron_client.remove_interface_router(router=router_id,
243 print "Error:", sys.exc_info()[0]
246 def add_gateway_router(neutron_client, router_id):
247 ext_net_id = get_external_net_id(neutron_client)
248 router_dict = {'network_id': ext_net_id}
250 neutron_client.add_gateway_router(router_id,router_dict)
253 print "Error:", sys.exc_info()[0]
256 def remove_gateway_router(neutron_client, router_id):
258 neutron_client.remove_gateway_router(router_id)
261 print "Error:", sys.exc_info()[0]
265 def create_neutron_port(neutron_client, name, network_id, ip):
266 json_body = {'port': {
267 'admin_state_up': True,
269 'network_id': network_id,
270 'fixed_ips': [{"ip_address": ip}]
273 port = neutron_client.create_port(body=json_body)
274 return port['port']['id']
276 print "Error:", sys.exc_info()[0]
280 def update_neutron_port(neutron_client, port_id, device_owner):
281 json_body = {'port': {
282 'device_owner': device_owner,
285 port = neutron_client.update_port(port=port_id,
287 return port['port']['id']
289 print "Error:", sys.exc_info()[0]
293 def delete_neutron_port(neutron_client, port_id):
295 neutron_client.delete_port(port_id)
298 print "Error:", sys.exc_info()[0]
302 def get_network_id(neutron_client, network_name):
303 networks = neutron_client.list_networks()['networks']
306 if n['name'] == network_name:
312 def check_neutron_net(neutron_client, net_name):
313 for network in neutron_client.list_networks()['networks']:
314 if network['name'] == net_name:
315 for subnet in network['subnets']:
320 def get_network_list(neutron_client):
321 network_list = neutron_client.list_networks()['networks']
322 if len(network_list) == 0:
328 def get_router_list(neutron_client):
329 router_list = neutron_client.list_routers()['routers']
330 if len(router_list) == 0:
336 def get_port_list(neutron_client):
337 port_list = neutron_client.list_ports()['ports']
338 if len(port_list) == 0:
344 def get_external_net(neutron_client):
345 for network in neutron_client.list_networks()['networks']:
346 if network['router:external']:
347 return network['name']
351 def get_external_net_id(neutron_client):
352 for network in neutron_client.list_networks()['networks']:
353 if network['router:external']:
358 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
359 json_body = {"quota": {
360 "security_group": sg_quota,
361 "security_group_rule": sg_rule_quota
365 quota = neutron_client.update_quota(tenant_id=tenant_id,
369 print "Error:", sys.exc_info()[0]
373 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
374 snapshots_quota, gigabytes_quota):
375 quotas_values = {"volumes": vols_quota,
376 "snapshots": snapshots_quota,
377 "gigabytes": gigabytes_quota}
380 quotas_default = cinder_client.quotas.update(tenant_id,
384 print "Error:", sys.exc_info()[0]
388 def get_private_net(neutron_client):
389 # Checks if there is an existing shared private network
390 networks = neutron_client.list_networks()['networks']
391 if len(networks) == 0:
394 if (net['router:external'] is False) and (net['shared'] is True):
399 # ################ GLANCE #################
400 def get_images(nova_client):
402 images = nova_client.images.list()
408 def get_image_id(glance_client, image_name):
409 images = glance_client.images.list()
412 if i.name == image_name:
418 def create_glance_image(glance_client, image_name, file_path, public=True):
419 if not os.path.isfile(file_path):
420 print "Error: file " + file_path + " does not exist."
423 with open(file_path) as fimage:
424 image = glance_client.images.create(name=image_name,
427 container_format="bare",
431 print "Error:", sys.exc_info()[0]
435 def delete_glance_image(nova_client, image_id):
437 nova_client.images.delete(image_id)
440 print "Error:", sys.exc_info()[0]
444 # ################ CINDER #################
445 def get_volumes(cinder_client):
447 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
453 def delete_volume(cinder_client, volume_id, forced=False):
457 cinder_client.volumes.detach(volume_id)
459 print "Error:", sys.exc_info()[0]
460 cinder_client.volumes.force_delete(volume_id)
462 cinder_client.volumes.delete(volume_id)
465 print "Error:", sys.exc_info()[0]
469 # ################ CINDER #################
470 def get_security_groups(neutron_client):
472 security_groups = neutron_client.list_security_groups()[
474 return security_groups
479 def delete_security_group(neutron_client, secgroup_id):
481 neutron_client.delete_security_group(secgroup_id)
484 print "Error:", sys.exc_info()[0]
488 # ################ KEYSTONE #################
489 def get_tenants(keystone_client):
491 tenants = keystone_client.tenants.list()
497 def get_tenant_id(keystone_client, tenant_name):
498 tenants = keystone_client.tenants.list()
501 if t.name == tenant_name:
507 def get_users(keystone_client):
509 users = keystone_client.users.list()
515 def get_role_id(keystone_client, role_name):
516 roles = keystone_client.roles.list()
519 if r.name == role_name:
525 def get_user_id(keystone_client, user_name):
526 users = keystone_client.users.list()
529 if u.name == user_name:
535 def create_tenant(keystone_client, tenant_name, tenant_description):
537 tenant = keystone_client.tenants.create(tenant_name,
542 print "Error:", sys.exc_info()[0]
546 def delete_tenant(keystone_client, tenant_id):
548 tenant = keystone_client.tenants.delete(tenant_id)
551 print "Error:", sys.exc_info()[0]
555 def create_user(keystone_client, user_name, user_password,
556 user_email, tenant_id):
558 user = keystone_client.users.create(user_name, user_password,
559 user_email, tenant_id,
563 print "Error:", sys.exc_info()[0]
567 def delete_user(keystone_client, user_id):
569 tenant = keystone_client.users.delete(user_id)
572 print "Error:", sys.exc_info()[0]
576 def add_role_user(keystone_client, user_id, role_id, tenant_id):
578 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
581 print "Error:", sys.exc_info()[0]
585 # ################ UTILS #################
586 def check_internet_connectivity(url='http://www.opnfv.org/'):
588 Check if there is access to the internet
591 urllib2.urlopen(url, timeout=5)
593 except urllib2.URLError:
597 def download_url(url, dest_path):
599 Download a file to a destination path given a URL
601 name = url.rsplit('/')[-1]
602 dest = dest_path + "/" + name
604 response = urllib2.urlopen(url)
605 except (urllib2.HTTPError, urllib2.URLError):
608 with open(dest, 'wb') as f:
609 shutil.copyfileobj(response, f)
613 def execute_command(cmd, logger=None, exit_on_error=True):
615 Execute Linux command
618 logger.debug('Executing command : {}'.format(cmd))
619 output_file = "output.txt"
620 f = open(output_file, 'w+')
621 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
623 f = open(output_file, 'r')
625 if result != "" and logger:
631 logger.error("Error when executing command %s" % cmd)
637 def get_git_branch(repo_path):
641 repo = Repo(repo_path)
642 branch = repo.active_branch
646 def get_installer_type(logger=None):
648 Get installer type (fuel, apex, joid, compass)
651 installer = os.environ['INSTALLER_TYPE']
654 logger.error("Impossible to retrieve the installer type")
655 installer = "Unknown_installer"
660 def get_scenario(logger=None):
665 scenario = os.environ['DEPLOY_SCENARIO']
668 logger.error("Impossible to retrieve the scenario")
669 scenario = "Unknown_scenario"
674 def get_pod_name(logger=None):
676 Get PoD Name from env variable NODE_NAME
679 return os.environ['NODE_NAME']
683 "Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
687 def push_results_to_db(db_url, case_name, logger, pod_name,
689 url = db_url + "/results"
690 installer = get_installer_type(logger)
691 params = {"project_name": "functest", "case_name": case_name,
692 "pod_name": pod_name, "installer": installer,
693 "version": version, "details": payload}
695 headers = {'Content-Type': 'application/json'}
697 r = requests.post(url, data=json.dumps(params), headers=headers)
702 print "Error:", sys.exc_info()[0]
706 def get_resolvconf_ns():
708 rconf = open("/etc/resolv.conf", "r")
709 line = rconf.readline()
711 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
712 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
714 result = sock.connect_ex((ip.group(),53))
716 nameservers.append(ip.group())
717 line = rconf.readline()
720 def getTestEnv(test, functest_yaml):
721 # get the config of the testcase based on functest_config.yaml
723 # - test = test project e.g; ovno
724 # - test = testcase e.g. functest/odl
725 # look for the / to see if it is a test project or a testcase
727 TEST_ENV = functest_yaml.get("test-dependencies")
729 if test.find("/") < 0:
730 config_test = TEST_ENV[test]
732 test_split = test.split("/")
733 testproject = test_split[0]
734 testcase = test_split[1]
735 config_test = TEST_ENV[testproject][testcase]
737 # if not defined in dependencies => no dependencies
740 print "Error getTestEnv:", sys.exc_info()[0]
745 def get_ci_envvars():
747 Get the CI env variables
750 "installer": os.environ.get('INSTALLER_TYPE'),
751 "scenario": os.environ.get('DEPLOY_SCENARIO')}
755 def isTestRunnable(test, functest_yaml):
756 # By default we assume that all the tests are always runnable...
758 # Retrieve CI environment
759 ci_env = get_ci_envvars()
760 # Retrieve test environement from config file
761 test_env = getTestEnv(test, functest_yaml)
763 # if test_env not empty => dependencies to be checked
764 if test_env is not None and len(test_env) > 0:
765 # possible criteria = ["installer", "scenario"]
766 # consider test criteria from config file
767 # compare towards CI env through CI en variable
768 for criteria in test_env:
769 if re.search(test_env[criteria], ci_env[criteria]) is None:
770 # print "Test "+ test + " cannot be run on the environment"
775 def generateTestcaseList(functest_yaml):
778 testcase_list = functest_yaml.get("test-dependencies")
779 projects = testcase_list.keys()
781 for project in projects:
782 testcases = testcase_list[project]
783 # 1 or 2 levels for testcases project[/case]
784 # if only project name without controller or scenario
785 # => shall be runnable on any controller/scenario
786 if testcases is None:
787 test_list += project + " "
789 for testcase in testcases:
790 if testcase == "installer" or testcase == "scenario":
792 if isTestRunnable(project, functest_yaml):
793 test_list += project + " "
795 # project/testcase (2 levels)
796 thetest = project + "/" + testcase
797 if isTestRunnable(thetest, functest_yaml):
798 test_list += testcase + " "
800 # sort the list to execute the test in the right order
801 test_order_list = functest_yaml.get("test_exec_priority")
802 test_sorted_list = ""
803 for test in test_order_list:
804 if test_order_list[test] in test_list:
805 test_sorted_list += test_order_list[test] + " "
807 # create a file that could be consumed by run-test.sh
808 # this method is used only for CI
809 # so it can be run only in container
810 # reuse default conf directory to store the list of runnable tests
811 file = open("/home/opnfv/functest/conf/testcase-list.txt", 'w')
812 file.write(test_sorted_list)
815 return test_sorted_list