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 # ----------------------------------------------------------
29 # -----------------------------------------------------------
32 #*********************************************
34 #*********************************************
35 def check_credentials():
37 Check if the OpenStack credentials (openrc) are sourced
39 env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
40 return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
42 def get_credentials(service):
43 """Returns a creds dictionary filled with the following keys:
45 * password/api_key (depending on the service)
46 * tenant_name/project_id (depending on the service)
48 :param service: a string indicating the name of the service
49 requesting the credentials.
52 # Unfortunately, each of the OpenStack client will request slightly
53 # different entries in their credentials dict.
54 if service.lower() in ("nova", "cinder"):
59 tenant = "tenant_name"
61 # The most common way to pass these info to the script is to do it through
62 # environment variables.
64 "username": os.environ.get('OS_USERNAME', "admin"),
65 password: os.environ.get("OS_PASSWORD", 'admin'),
66 "auth_url": os.environ.get("OS_AUTH_URL",
67 "http://192.168.20.71:5000/v2.0"),
68 tenant: os.environ.get("OS_TENANT_NAME", "admin"),
74 #*********************************************
76 #*********************************************
77 def get_instances(nova_client):
79 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
82 print "Error [get_instances(nova_client)]:", e
86 def get_instance_status(nova_client, instance):
88 instance = nova_client.servers.get(instance.id)
89 return instance.status
91 print "Error [get_instance_status(nova_client, instance)]:" % \
96 def get_instance_by_name(nova_client, instance_name):
98 instance = nova_client.servers.find(name=instance_name)
101 print "Error [get_instance_by_name(nova_client, '%s')]:" %instance_name, e
105 def get_flavor_id(nova_client, flavor_name):
106 flavors = nova_client.flavors.list(detailed=True)
109 if f.name == flavor_name:
115 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
116 flavors = nova_client.flavors.list(detailed=True)
119 if min_ram <= f.ram and f.ram <= max_ram:
125 def get_floating_ips(nova_client):
127 floating_ips = nova_client.floating_ips.list()
130 print "Error [get_floating_ips(nova_client)]:", e
134 def create_flavor(nova_client, flavor_name, ram, disk, vcpus):
136 flavor = nova_client.flavors.create(flavor_name,ram,vcpus,disk)
138 print "Error [create_flavor(nova_client, '%s', '%s', '%s', "\
139 "'%s')]:" %(flavor_name,ram, disk, vcpus), e
144 def create_floating_ip(neutron_client):
145 extnet_id = get_external_net_id(neutron_client)
146 props = {'floating_network_id': extnet_id}
148 ip_json = neutron_client.create_floatingip({'floatingip': props})
149 floating_ip = ip_json['floatingip']['floating_ip_address']
151 print "Error [create_floating_ip(neutron_client)]:", e
156 def add_floating_ip(nova_client, server_id, floatingip_id):
158 nova_client.servers.add_floating_ip(server_id,floatingip_id)
161 print "Error [add_floating_ip(nova_client, '%s', '%s')]:" % \
162 (server_id, floatingip_id), e
166 def delete_instance(nova_client, instance_id):
168 nova_client.servers.force_delete(instance_id)
171 print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
175 def delete_floating_ip(nova_client, floatingip_id):
177 nova_client.floating_ips.delete(floatingip_id)
180 print "Error [delete_floating_ip(nova_client, '%s')]:" % floatingip_id, e
186 #*********************************************
188 #*********************************************
189 def get_network_list(neutron_client):
190 network_list = neutron_client.list_networks()['networks']
191 if len(network_list) == 0:
197 def get_router_list(neutron_client):
198 router_list = neutron_client.list_routers()['routers']
199 if len(router_list) == 0:
205 def get_port_list(neutron_client):
206 port_list = neutron_client.list_ports()['ports']
207 if len(port_list) == 0:
213 def get_network_id(neutron_client, network_name):
214 networks = neutron_client.list_networks()['networks']
217 if n['name'] == network_name:
223 def get_private_net(neutron_client):
224 # Checks if there is an existing shared private network
225 networks = neutron_client.list_networks()['networks']
226 if len(networks) == 0:
229 if (net['router:external'] is False) and (net['shared'] is True):
234 def get_external_net(neutron_client):
235 for network in neutron_client.list_networks()['networks']:
236 if network['router:external']:
237 return network['name']
241 def get_external_net_id(neutron_client):
242 for network in neutron_client.list_networks()['networks']:
243 if network['router:external']:
248 def check_neutron_net(neutron_client, net_name):
249 for network in neutron_client.list_networks()['networks']:
250 if network['name'] == net_name:
251 for subnet in network['subnets']:
256 def create_neutron_net(neutron_client, name):
257 json_body = {'network': {'name': name,
258 'admin_state_up': True}}
260 network = neutron_client.create_network(body=json_body)
261 network_dict = network['network']
262 return network_dict['id']
264 print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
268 def create_neutron_subnet(neutron_client, name, cidr, net_id):
269 json_body = {'subnets': [{'name': name, 'cidr': cidr,
270 'ip_version': 4, 'network_id': net_id}]}
272 subnet = neutron_client.create_subnet(body=json_body)
273 return subnet['subnets'][0]['id']
275 print "Error [create_neutron_subnet(neutron_client, '%s', '%s', "\
276 "'%s')]:" %(name,cidr, net_id), e
280 def create_neutron_router(neutron_client, name):
281 json_body = {'router': {'name': name, 'admin_state_up': True}}
283 router = neutron_client.create_router(json_body)
284 return router['router']['id']
286 print "Error [create_neutron_router(neutron_client, name)]:" % name, e
290 def create_neutron_port(neutron_client, name, network_id, ip):
291 json_body = {'port': {
292 'admin_state_up': True,
294 'network_id': network_id,
295 'fixed_ips': [{"ip_address": ip}]
298 port = neutron_client.create_port(body=json_body)
299 return port['port']['id']
301 print "Error [create_neutron_port(neutron_client, '%s', '%s', "\
302 "'%s')]:" %(name,network_id, ip), e
306 def update_neutron_net(neutron_client, network_id, shared=False):
307 json_body = {'network': {'shared': shared}}
309 neutron_client.update_network(network_id, body=json_body)
312 print "Error [update_neutron_net(neutron_client, '%s', '%s')]:" % \
313 (network_id,str(shared)), e
317 def update_neutron_port(neutron_client, port_id, device_owner):
318 json_body = {'port': {
319 'device_owner': device_owner,
322 port = neutron_client.update_port(port=port_id,
324 return port['port']['id']
326 print "Error [update_neutron_port(neutron_client, '%s', '%s')]:" % \
327 (port_id,device_owner), e
331 def add_interface_router(neutron_client, router_id, subnet_id):
332 json_body = {"subnet_id": subnet_id}
334 neutron_client.add_interface_router(router=router_id, body=json_body)
337 print "Error [add_interface_router(neutron_client, '%s', '%s')]:" % \
338 (router_id,subnet_id), e
341 def add_gateway_router(neutron_client, router_id):
342 ext_net_id = get_external_net_id(neutron_client)
343 router_dict = {'network_id': ext_net_id}
345 neutron_client.add_gateway_router(router_id,router_dict)
348 print "Error [add_gateway_router(neutron_client, '%s')]:" % router_id, e
352 def delete_neutron_net(neutron_client, network_id):
354 neutron_client.delete_network(network_id)
357 print "Error [delete_neutron_net(neutron_client, '%s')]:" % network_id, e
361 def delete_neutron_subnet(neutron_client, subnet_id):
363 neutron_client.delete_subnet(subnet_id)
366 print "Error [delete_neutron_subnet(neutron_client, '%s')]:" % subnet_id, e
370 def delete_neutron_router(neutron_client, router_id):
371 json_body = {'router': {'id': router_id}}
373 neutron_client.delete_router(router=router_id)
376 print "Error [delete_neutron_router(neutron_client, '%s')]:" % \
381 def delete_neutron_port(neutron_client, port_id):
383 neutron_client.delete_port(port_id)
386 print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
390 def remove_interface_router(neutron_client, router_id, subnet_id):
391 json_body = {"subnet_id": subnet_id}
393 neutron_client.remove_interface_router(router=router_id,
397 print "Error [remove_interface_router(neutron_client, '%s', '%s')]:" % \
398 (router_id,subnet_id), e
402 def remove_gateway_router(neutron_client, router_id):
404 neutron_client.remove_gateway_router(router_id)
407 print "Error [remove_gateway_router(neutron_client, '%s')]:" % router_id, e
412 #*********************************************
414 #*********************************************
415 def get_security_groups(neutron_client):
417 security_groups = neutron_client.list_security_groups()[
419 return security_groups
421 print "Error [get_security_groups(neutron_client)]:", e
425 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
426 json_body = {"quota": {
427 "security_group": sg_quota,
428 "security_group_rule": sg_rule_quota
432 quota = neutron_client.update_quota(tenant_id=tenant_id,
436 print "Error [update_sg_quota(neutron_client, '%s', '%s', "\
437 "'%s')]:" %(tenant_id,sg_quota, sg_rule_quota), e
441 def delete_security_group(neutron_client, secgroup_id):
443 neutron_client.delete_security_group(secgroup_id)
446 print "Error [delete_security_group(neutron_client, '%s')]:" % secgroup_id, e
451 #*********************************************
453 #*********************************************
454 def get_images(nova_client):
456 images = nova_client.images.list()
459 print "Error [get_images]:", e
463 def get_image_id(glance_client, image_name):
464 images = glance_client.images.list()
467 if i.name == image_name:
473 def create_glance_image(glance_client, image_name, file_path, public=True):
474 if not os.path.isfile(file_path):
475 print "Error: file " + file_path + " does not exist."
478 with open(file_path) as fimage:
479 image = glance_client.images.create(name=image_name,
482 container_format="bare",
486 print "Error [create_glance_image(glance_client, '%s', '%s', "\
487 "'%s')]:" %(image_name,file_path, str(public)), e
491 def delete_glance_image(nova_client, image_id):
493 nova_client.images.delete(image_id)
496 print "Error [delete_glance_image(nova_client, image_id)]:" % image_id, e
501 #*********************************************
503 #*********************************************
504 def get_volumes(cinder_client):
506 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
509 print "Error [get_volumes(cinder_client)]:", e
513 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
514 snapshots_quota, gigabytes_quota):
515 quotas_values = {"volumes": vols_quota,
516 "snapshots": snapshots_quota,
517 "gigabytes": gigabytes_quota}
520 quotas_default = cinder_client.quotas.update(tenant_id,
524 print "Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'" \
525 "'%s')]:" %(tenant_id, vols_quota, snapshots_quota, gigabytes_quota), e
529 def delete_volume(cinder_client, volume_id, forced=False):
533 cinder_client.volumes.detach(volume_id)
535 print "Error:", sys.exc_info()[0]
536 cinder_client.volumes.force_delete(volume_id)
538 cinder_client.volumes.delete(volume_id)
541 print "Error [delete_volume(cinder_client, '%s', '%s')]:" % \
542 (volume_id, str(forced)), e
547 #*********************************************
549 #*********************************************
550 def get_tenants(keystone_client):
552 tenants = keystone_client.tenants.list()
555 print "Error [get_tenants(keystone_client)]:", e
559 def get_users(keystone_client):
561 users = keystone_client.users.list()
564 print "Error [get_users(keystone_client)]:", e
568 def get_tenant_id(keystone_client, tenant_name):
569 tenants = keystone_client.tenants.list()
572 if t.name == tenant_name:
578 def get_user_id(keystone_client, user_name):
579 users = keystone_client.users.list()
582 if u.name == user_name:
588 def get_role_id(keystone_client, role_name):
589 roles = keystone_client.roles.list()
592 if r.name == role_name:
598 def create_tenant(keystone_client, tenant_name, tenant_description):
600 tenant = keystone_client.tenants.create(tenant_name,
605 print "Error [create_tenant(cinder_client, '%s', '%s')]:" % \
606 (tenant_name, tenant_description), e
610 def create_user(keystone_client, user_name, user_password,
611 user_email, tenant_id):
613 user = keystone_client.users.create(user_name, user_password,
614 user_email, tenant_id,
618 print "Error [create_user(keystone_client, '%s', '%s', '%s'" \
619 "'%s')]:" %(user_name, user_password, user_email, tenant_id), e
623 def add_role_user(keystone_client, user_id, role_id, tenant_id):
625 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
628 print "Error [add_role_user(keystone_client, '%s', '%s'" \
629 "'%s')]:" %(user_id, role_id, tenant_id), e
633 def delete_tenant(keystone_client, tenant_id):
635 tenant = keystone_client.tenants.delete(tenant_id)
638 print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
642 def delete_user(keystone_client, user_id):
644 tenant = keystone_client.users.delete(user_id)
647 print "Error [delete_user(keystone_client, '%s')]:" % user_id, e
656 # ----------------------------------------------------------
660 # -----------------------------------------------------------
661 def check_internet_connectivity(url='http://www.opnfv.org/'):
663 Check if there is access to the internet
666 urllib2.urlopen(url, timeout=5)
668 except urllib2.URLError:
672 def download_url(url, dest_path):
674 Download a file to a destination path given a URL
676 name = url.rsplit('/')[-1]
677 dest = dest_path + "/" + name
679 response = urllib2.urlopen(url)
680 except (urllib2.HTTPError, urllib2.URLError):
683 with open(dest, 'wb') as f:
684 shutil.copyfileobj(response, f)
690 # ----------------------------------------------------------
694 # -----------------------------------------------------------
695 def get_git_branch(repo_path):
699 repo = Repo(repo_path)
700 branch = repo.active_branch
704 def get_installer_type(logger=None):
706 Get installer type (fuel, apex, joid, compass)
709 installer = os.environ['INSTALLER_TYPE']
712 logger.error("Impossible to retrieve the installer type")
713 installer = "Unknown_installer"
718 def get_scenario(logger=None):
723 scenario = os.environ['DEPLOY_SCENARIO']
726 logger.error("Impossible to retrieve the scenario")
727 scenario = "Unknown_scenario"
732 def get_pod_name(logger=None):
734 Get PoD Name from env variable NODE_NAME
737 return os.environ['NODE_NAME']
741 "Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
745 def push_results_to_db(db_url, case_name, logger, pod_name,
748 POST results to the Result target DB
750 url = db_url + "/results"
751 installer = get_installer_type(logger)
752 params = {"project_name": "functest", "case_name": case_name,
753 "pod_name": pod_name, "installer": installer,
754 "version": version, "details": payload}
756 headers = {'Content-Type': 'application/json'}
758 r = requests.post(url, data=json.dumps(params), headers=headers)
767 def get_resolvconf_ns():
769 Get nameservers from current resolv.conf
772 rconf = open("/etc/resolv.conf", "r")
773 line = rconf.readline()
775 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
776 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
778 result = sock.connect_ex((ip.group(),53))
780 nameservers.append(ip.group())
781 line = rconf.readline()
785 def getTestEnv(test, functest_yaml):
787 Get the config of the testcase based on functest_config.yaml
789 - test = test project e.g; ovno
790 - test = testcase e.g. functest/odl
791 look for the / to see if it is a test project or a testcase
794 TEST_ENV = functest_yaml.get("test-dependencies")
796 if test.find("/") < 0:
797 config_test = TEST_ENV[test]
799 test_split = test.split("/")
800 testproject = test_split[0]
801 testcase = test_split[1]
802 config_test = TEST_ENV[testproject][testcase]
804 # if not defined in dependencies => no dependencies
812 def get_ci_envvars():
814 Get the CI env variables
817 "installer": os.environ.get('INSTALLER_TYPE'),
818 "scenario": os.environ.get('DEPLOY_SCENARIO')}
822 def isTestRunnable(test, functest_yaml):
824 Return True if the test is runnable in the current scenario
826 # By default we assume that all the tests are always runnable...
828 # Retrieve CI environment
829 ci_env = get_ci_envvars()
830 # Retrieve test environement from config file
831 test_env = getTestEnv(test, functest_yaml)
833 # if test_env not empty => dependencies to be checked
834 if test_env is not None and len(test_env) > 0:
835 # possible criteria = ["installer", "scenario"]
836 # consider test criteria from config file
837 # compare towards CI env through CI en variable
838 for criteria in test_env:
839 if re.search(test_env[criteria], ci_env[criteria]) is None:
840 # print "Test "+ test + " cannot be run on the environment"
845 def generateTestcaseList(functest_yaml):
847 Generate a test file with the runnable test according to
852 testcase_list = functest_yaml.get("test-dependencies")
853 projects = testcase_list.keys()
855 for project in projects:
856 testcases = testcase_list[project]
857 # 1 or 2 levels for testcases project[/case]l
858 # if only project name without controller or scenario
859 # => shall be runnable on any controller/scenario
860 if testcases is None:
861 test_list += project + " "
863 for testcase in testcases:
864 if testcase == "installer" or testcase == "scenario":
866 if isTestRunnable(project, functest_yaml):
867 test_list += project + " "
869 # project/testcase (2 levels)
870 thetest = project + "/" + testcase
871 if isTestRunnable(thetest, functest_yaml):
872 test_list += testcase + " "
874 # sort the list to execute the test in the right order
875 test_order_list = functest_yaml.get("test_exec_priority")
876 test_sorted_list = ""
877 for test in test_order_list:
878 if test_order_list[test] in test_list:
879 test_sorted_list += test_order_list[test] + " "
881 # create a file that could be consumed by run-test.sh
882 # this method is used only for CI
883 # so it can be run only in container
884 # reuse default conf directory to store the list of runnable tests
885 file = open("/home/opnfv/functest/conf/testcase-list.txt", 'w')
886 file.write(test_sorted_list)
889 return test_sorted_list
892 def execute_command(cmd, logger=None, exit_on_error=True):
894 Execute Linux command
895 prints stdout to a file and depending on if there
896 is a logger defined, it will print it or not.
899 logger.debug('Executing command : {}'.format(cmd))
900 output_file = "output.txt"
901 f = open(output_file, 'w+')
902 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
904 f = open(output_file, 'r')
906 if result != "" and logger:
912 logger.error("Error when executing command %s" % cmd)