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
24 # ----------------------------------------------------------
28 # -----------------------------------------------------------
31 #*********************************************
33 #*********************************************
34 def check_credentials():
36 Check if the OpenStack credentials (openrc) are sourced
38 env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
39 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"),
73 #*********************************************
75 #*********************************************
76 def get_instances(nova_client):
78 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
81 print "Error [get_instances(nova_client)]:", e
85 def get_instance_status(nova_client, instance):
87 instance = nova_client.servers.get(instance.id)
88 return instance.status
90 #print "Error [get_instance_status(nova_client, '%s')]:" % \
95 def get_instance_by_name(nova_client, instance_name):
97 instance = nova_client.servers.find(name=instance_name)
100 print "Error [get_instance_by_name(nova_client, '%s')]:" % \
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 fip_addr = ip_json['floatingip']['floating_ip_address']
150 fip_id = ip_json['floatingip']['id']
152 print "Error [create_floating_ip(neutron_client)]:", e
154 return {'fip_addr': fip_addr, 'fip_id': fip_id}
157 def add_floating_ip(nova_client, server_id, floatingip_id):
159 nova_client.servers.add_floating_ip(server_id, floatingip_id)
162 print "Error [add_floating_ip(nova_client, '%s', '%s')]:" % \
163 (server_id, floatingip_id), e
167 def delete_instance(nova_client, instance_id):
169 nova_client.servers.force_delete(instance_id)
172 print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
176 def delete_floating_ip(nova_client, floatingip_id):
178 nova_client.floating_ips.delete(floatingip_id)
181 print "Error [delete_floating_ip(nova_client, '%s')]:" % floatingip_id, e
185 #*********************************************
187 #*********************************************
188 def get_network_list(neutron_client):
189 network_list = neutron_client.list_networks()['networks']
190 if len(network_list) == 0:
196 def get_router_list(neutron_client):
197 router_list = neutron_client.list_routers()['routers']
198 if len(router_list) == 0:
204 def get_port_list(neutron_client):
205 port_list = neutron_client.list_ports()['ports']
206 if len(port_list) == 0:
212 def get_network_id(neutron_client, network_name):
213 networks = neutron_client.list_networks()['networks']
216 if n['name'] == network_name:
222 def get_subnet_id(neutron_client, subnet_name):
223 subnets = neutron_client.list_subnets()['subnets']
226 if s['name'] == subnet_name:
232 def get_router_id(neutron_client, router_name):
233 routers = neutron_client.list_routers()['routers']
236 if r['name'] == router_name:
242 def get_private_net(neutron_client):
243 # Checks if there is an existing shared private network
244 networks = neutron_client.list_networks()['networks']
245 if len(networks) == 0:
248 if (net['router:external'] is False) and (net['shared'] is True):
253 def get_external_net(neutron_client):
254 for network in neutron_client.list_networks()['networks']:
255 if network['router:external']:
256 return network['name']
260 def get_external_net_id(neutron_client):
261 for network in neutron_client.list_networks()['networks']:
262 if network['router:external']:
267 def check_neutron_net(neutron_client, net_name):
268 for network in neutron_client.list_networks()['networks']:
269 if network['name'] == net_name:
270 for subnet in network['subnets']:
275 def create_neutron_net(neutron_client, name):
276 json_body = {'network': {'name': name,
277 'admin_state_up': True}}
279 network = neutron_client.create_network(body=json_body)
280 network_dict = network['network']
281 return network_dict['id']
283 print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
287 def create_neutron_subnet(neutron_client, name, cidr, net_id):
288 json_body = {'subnets': [{'name': name, 'cidr': cidr,
289 'ip_version': 4, 'network_id': net_id}]}
291 subnet = neutron_client.create_subnet(body=json_body)
292 return subnet['subnets'][0]['id']
294 print "Error [create_neutron_subnet(neutron_client, '%s', '%s', "\
295 "'%s')]:" % (name, cidr, net_id), e
299 def create_neutron_router(neutron_client, name):
300 json_body = {'router': {'name': name, 'admin_state_up': True}}
302 router = neutron_client.create_router(json_body)
303 return router['router']['id']
305 print "Error [create_neutron_router(neutron_client, '%s')]:" % name, e
309 def create_neutron_port(neutron_client, name, network_id, ip):
310 json_body = {'port': {
311 'admin_state_up': True,
313 'network_id': network_id,
314 'fixed_ips': [{"ip_address": ip}]
317 port = neutron_client.create_port(body=json_body)
318 return port['port']['id']
320 print "Error [create_neutron_port(neutron_client, '%s', '%s', "\
321 "'%s')]:" % (name, network_id, ip), e
325 def update_neutron_net(neutron_client, network_id, shared=False):
326 json_body = {'network': {'shared': shared}}
328 neutron_client.update_network(network_id, body=json_body)
331 print "Error [update_neutron_net(neutron_client, '%s', '%s')]:" % \
332 (network_id, str(shared)), e
336 def update_neutron_port(neutron_client, port_id, device_owner):
337 json_body = {'port': {
338 'device_owner': device_owner,
341 port = neutron_client.update_port(port=port_id,
343 return port['port']['id']
345 print "Error [update_neutron_port(neutron_client, '%s', '%s')]:" % \
346 (port_id, device_owner), e
350 def add_interface_router(neutron_client, router_id, subnet_id):
351 json_body = {"subnet_id": subnet_id}
353 neutron_client.add_interface_router(router=router_id, body=json_body)
356 print "Error [add_interface_router(neutron_client, '%s', '%s')]:" % \
357 (router_id, subnet_id), e
361 def add_gateway_router(neutron_client, router_id):
362 ext_net_id = get_external_net_id(neutron_client)
363 router_dict = {'network_id': ext_net_id}
365 neutron_client.add_gateway_router(router_id, router_dict)
368 print "Error [add_gateway_router(neutron_client, '%s')]:" % router_id, e
372 def delete_neutron_net(neutron_client, network_id):
374 neutron_client.delete_network(network_id)
377 print "Error [delete_neutron_net(neutron_client, '%s')]:" % network_id, e
381 def delete_neutron_subnet(neutron_client, subnet_id):
383 neutron_client.delete_subnet(subnet_id)
386 print "Error [delete_neutron_subnet(neutron_client, '%s')]:" % subnet_id, e
390 def delete_neutron_router(neutron_client, router_id):
391 json_body = {'router': {'id': router_id}}
393 neutron_client.delete_router(router=router_id)
396 print "Error [delete_neutron_router(neutron_client, '%s')]:" % \
401 def delete_neutron_port(neutron_client, port_id):
403 neutron_client.delete_port(port_id)
406 print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
410 def remove_interface_router(neutron_client, router_id, subnet_id):
411 json_body = {"subnet_id": subnet_id}
413 neutron_client.remove_interface_router(router=router_id,
417 print "Error [remove_interface_router(neutron_client, '%s', '%s')]:" % \
418 (router_id, subnet_id), e
422 def remove_gateway_router(neutron_client, router_id):
424 neutron_client.remove_gateway_router(router_id)
427 print "Error [remove_gateway_router(neutron_client, '%s')]:" % router_id, e
431 #*********************************************
433 #*********************************************
434 def get_security_groups(neutron_client):
436 security_groups = neutron_client.list_security_groups()[
438 return security_groups
440 print "Error [get_security_groups(neutron_client)]:", e
443 def get_security_group_id(neutron_client, sg_name):
444 security_groups = get_security_groups(neutron_client)
446 for sg in security_groups:
447 if sg['name'] == sg_name:
453 def create_security_group(neutron_client, sg_name, sg_description):
454 json_body = {'security_group': {'name': sg_name,
455 'description': sg_description}}
457 secgroup = neutron_client.create_security_group(json_body)
458 return secgroup['security_group']
460 print "Error [create_security_group(neutron_client, '%s', '%s')]:" % \
461 (sg_name, sg_description), e
465 def create_secgroup_rule(neutron_client, sg_id, direction, protocol,
466 port_range_min=None, port_range_max=None):
467 if port_range_min is None and port_range_max is None:
468 json_body = {'security_group_rule': {'direction': direction,
469 'security_group_id': sg_id,
470 'protocol': protocol}}
471 elif port_range_min is not None and port_range_max is not None:
472 json_body = {'security_group_rule': {'direction': direction,
473 'security_group_id': sg_id,
474 'port_range_min': port_range_min,
475 'port_range_max': port_range_max,
476 'protocol': protocol}}
478 print "Error [create_secgroup_rule(neutron_client, '%s', '%s', "\
479 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction, \
480 port_range_min, port_range_max, protocol),\
481 " Invalid values for port_range_min, port_range_max"
484 neutron_client.create_security_group_rule(json_body)
487 print "Error [create_secgroup_rule(neutron_client, '%s', '%s', "\
488 "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
489 port_range_min, port_range_max,
494 def add_secgroup_to_instance(nova_client, instance_id, secgroup_id):
496 nova_client.servers.add_security_group(instance_id, secgroup_id)
499 print "Error [add_secgroup_to_instance(nova_client, '%s', '%s')]: " % \
500 (instance_id, secgroup_id), e
504 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
505 json_body = {"quota": {
506 "security_group": sg_quota,
507 "security_group_rule": sg_rule_quota
511 quota = neutron_client.update_quota(tenant_id=tenant_id,
515 print "Error [update_sg_quota(neutron_client, '%s', '%s', "\
516 "'%s')]:" % (tenant_id, sg_quota, sg_rule_quota), e
520 def delete_security_group(neutron_client, secgroup_id):
522 neutron_client.delete_security_group(secgroup_id)
525 print "Error [delete_security_group(neutron_client, '%s')]:" % secgroup_id, e
529 #*********************************************
531 #*********************************************
532 def get_images(nova_client):
534 images = nova_client.images.list()
537 print "Error [get_images]:", e
541 def get_image_id(glance_client, image_name):
542 images = glance_client.images.list()
545 if i.name == image_name:
551 def create_glance_image(glance_client, image_name, file_path, public=True):
552 if not os.path.isfile(file_path):
553 print "Error: file " + file_path + " does not exist."
556 with open(file_path) as fimage:
557 image = glance_client.images.create(name=image_name,
560 container_format="bare",
564 print "Error [create_glance_image(glance_client, '%s', '%s', "\
565 "'%s')]:" % (image_name, file_path, str(public)), e
569 def delete_glance_image(nova_client, image_id):
571 nova_client.images.delete(image_id)
574 print "Error [delete_glance_image(nova_client, '%s')]:" % image_id, e
578 #*********************************************
580 #*********************************************
581 def get_volumes(cinder_client):
583 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
586 print "Error [get_volumes(cinder_client)]:", e
590 def list_volume_types(cinder_client, public=True, private=True):
592 volume_types = cinder_client.volume_types.list()
594 volume_types = [vt for vt in volume_types if not vt.is_public]
596 volume_types = [vt for vt in volume_types if vt.is_public]
599 print "Error [list_volume_types(cinder_client)]:", e
603 def create_volume_type(cinder_client, name):
605 volume_type = cinder_client.volume_types.create(name)
608 print "Error [create_volume_type(cinder_client, '%s')]:" % name, e
612 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
613 snapshots_quota, gigabytes_quota):
614 quotas_values = {"volumes": vols_quota,
615 "snapshots": snapshots_quota,
616 "gigabytes": gigabytes_quota}
619 quotas_default = cinder_client.quotas.update(tenant_id,
623 print "Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'" \
624 "'%s')]:" % (tenant_id, vols_quota, snapshots_quota, gigabytes_quota), e
628 def delete_volume(cinder_client, volume_id, forced=False):
632 cinder_client.volumes.detach(volume_id)
634 print "Error:", sys.exc_info()[0]
635 cinder_client.volumes.force_delete(volume_id)
637 cinder_client.volumes.delete(volume_id)
640 print "Error [delete_volume(cinder_client, '%s', '%s')]:" % \
641 (volume_id, str(forced)), e
645 def delete_volume_type(cinder_client, volume_type):
647 cinder_client.volume_types.delete(volume_type)
650 print "Error [delete_volume_type(cinder_client, '%s')]:" % volume_type, e
654 #*********************************************
656 #*********************************************
657 def get_tenants(keystone_client):
659 tenants = keystone_client.tenants.list()
662 print "Error [get_tenants(keystone_client)]:", e
666 def get_users(keystone_client):
668 users = keystone_client.users.list()
671 print "Error [get_users(keystone_client)]:", e
675 def get_tenant_id(keystone_client, tenant_name):
676 tenants = keystone_client.tenants.list()
679 if t.name == tenant_name:
685 def get_user_id(keystone_client, user_name):
686 users = keystone_client.users.list()
689 if u.name == user_name:
695 def get_role_id(keystone_client, role_name):
696 roles = keystone_client.roles.list()
699 if r.name == role_name:
705 def create_tenant(keystone_client, tenant_name, tenant_description):
707 tenant = keystone_client.tenants.create(tenant_name,
712 print "Error [create_tenant(cinder_client, '%s', '%s')]:" % \
713 (tenant_name, tenant_description), e
717 def create_user(keystone_client, user_name, user_password,
718 user_email, tenant_id):
720 user = keystone_client.users.create(user_name, user_password,
721 user_email, tenant_id,
725 print "Error [create_user(keystone_client, '%s', '%s', '%s'" \
726 "'%s')]:" % (user_name, user_password, user_email, tenant_id), e
730 def add_role_user(keystone_client, user_id, role_id, tenant_id):
732 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
735 print "Error [add_role_user(keystone_client, '%s', '%s'" \
736 "'%s')]:" % (user_id, role_id, tenant_id), e
740 def delete_tenant(keystone_client, tenant_id):
742 tenant = keystone_client.tenants.delete(tenant_id)
745 print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
749 def delete_user(keystone_client, user_id):
751 tenant = keystone_client.users.delete(user_id)
754 print "Error [delete_user(keystone_client, '%s')]:" % user_id, e
763 # ----------------------------------------------------------
767 # -----------------------------------------------------------
768 def check_internet_connectivity(url='http://www.opnfv.org/'):
770 Check if there is access to the internet
773 urllib2.urlopen(url, timeout=5)
775 except urllib2.URLError:
779 def download_url(url, dest_path):
781 Download a file to a destination path given a URL
783 name = url.rsplit('/')[-1]
784 dest = dest_path + "/" + name
786 response = urllib2.urlopen(url)
787 except (urllib2.HTTPError, urllib2.URLError):
790 with open(dest, 'wb') as f:
791 shutil.copyfileobj(response, f)
797 # ----------------------------------------------------------
801 # -----------------------------------------------------------
802 def get_git_branch(repo_path):
806 repo = Repo(repo_path)
807 branch = repo.active_branch
811 def get_installer_type(logger=None):
813 Get installer type (fuel, apex, joid, compass)
816 installer = os.environ['INSTALLER_TYPE']
819 logger.error("Impossible to retrieve the installer type")
820 installer = "Unknown_installer"
825 def get_scenario(logger=None):
830 scenario = os.environ['DEPLOY_SCENARIO']
833 logger.error("Impossible to retrieve the scenario")
834 scenario = "Unknown_scenario"
839 def get_pod_name(logger=None):
841 Get PoD Name from env variable NODE_NAME
844 return os.environ['NODE_NAME']
848 "Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
852 def push_results_to_db(db_url, project, case_name, logger, pod_name,
855 POST results to the Result target DB
857 url = db_url + "/results"
858 installer = get_installer_type(logger)
859 params = {"project_name": project, "case_name": case_name,
860 "pod_name": pod_name, "installer": installer,
861 "version": version, "details": payload}
863 headers = {'Content-Type': 'application/json'}
865 r = requests.post(url, data=json.dumps(params), headers=headers)
870 print "Error [push_results_to_db('%s', '%s', '%s', '%s', '%s', '%s')]:" \
871 % (db_url, project, case_name, pod_name, version, payload), e
875 def get_resolvconf_ns():
877 Get nameservers from current resolv.conf
880 rconf = open("/etc/resolv.conf", "r")
881 line = rconf.readline()
883 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
884 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
886 result = sock.connect_ex((ip.group(), 53))
888 nameservers.append(ip.group())
889 line = rconf.readline()
893 def getTestEnv(test, functest_yaml):
895 Get the config of the testcase based on functest_config.yaml
897 - test = test project e.g; ovno
898 - test = testcase e.g. functest/odl
899 look for the / to see if it is a test project or a testcase
902 TEST_ENV = functest_yaml.get("test-dependencies")
904 if test.find("/") < 0:
905 config_test = TEST_ENV[test]
907 test_split = test.split("/")
908 testproject = test_split[0]
909 testcase = test_split[1]
910 config_test = TEST_ENV[testproject][testcase]
912 # if not defined in dependencies => no dependencies
915 print "Error [getTestEnv]:", e
920 def get_ci_envvars():
922 Get the CI env variables
925 "installer": os.environ.get('INSTALLER_TYPE'),
926 "scenario": os.environ.get('DEPLOY_SCENARIO')}
930 def isTestRunnable(test, functest_yaml):
932 Return True if the test is runnable in the current scenario
934 # By default we assume that all the tests are always runnable...
936 # Retrieve CI environment
937 ci_env = get_ci_envvars()
938 # Retrieve test environement from config file
939 test_env = getTestEnv(test, functest_yaml)
941 # if test_env not empty => dependencies to be checked
942 if test_env is not None and len(test_env) > 0:
943 # possible criteria = ["installer", "scenario"]
944 # consider test criteria from config file
945 # compare towards CI env through CI en variable
946 for criteria in test_env:
947 if re.search(test_env[criteria], ci_env[criteria]) is None:
948 # print "Test "+ test + " cannot be run on the environment"
953 def generateTestcaseList(functest_yaml):
955 Generate a test file with the runnable test according to
960 testcase_list = functest_yaml.get("test-dependencies")
961 projects = testcase_list.keys()
963 for project in projects:
964 testcases = testcase_list[project]
965 # 1 or 2 levels for testcases project[/case]l
966 # if only project name without controller or scenario
967 # => shall be runnable on any controller/scenario
968 if testcases is None:
969 test_list += project + " "
971 for testcase in testcases:
972 if testcase == "installer" or testcase == "scenario":
974 if isTestRunnable(project, functest_yaml):
975 test_list += project + " "
977 # project/testcase (2 levels)
978 thetest = project + "/" + testcase
979 if isTestRunnable(thetest, functest_yaml):
980 test_list += testcase + " "
982 # sort the list to execute the test in the right order
983 test_order_list = functest_yaml.get("test_exec_priority")
984 test_sorted_list = ""
985 for test in test_order_list:
986 if test_order_list[test] in test_list:
987 test_sorted_list += test_order_list[test] + " "
989 # create a file that could be consumed by run-test.sh
990 # this method is used only for CI
991 # so it can be run only in container
992 # reuse default conf directory to store the list of runnable tests
993 file = open("/home/opnfv/functest/conf/testcase-list.txt", 'w')
994 file.write(test_sorted_list)
997 return test_sorted_list
1000 def execute_command(cmd, logger=None, exit_on_error=True):
1002 Execute Linux command
1003 prints stdout to a file and depending on if there
1004 is a logger defined, it will print it or not.
1007 logger.debug('Executing command : {}'.format(cmd))
1008 output_file = "output.txt"
1009 f = open(output_file, 'w+')
1010 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
1012 f = open(output_file, 'r')
1014 if result != "" and logger:
1015 logger.debug(result)
1020 logger.error("Error when executing command %s" % cmd)