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]
121 def get_floating_ips(nova_client):
123 floating_ips = nova_client.floating_ips.list()
129 def delete_floating_ip(nova_client, floatingip_id):
131 nova_client.floating_ips.delete(floatingip_id)
134 print "Error:", sys.exc_info()[0]
138 # ################ NEUTRON #################
139 def create_neutron_net(neutron_client, name):
140 json_body = {'network': {'name': name,
141 'admin_state_up': True}}
143 network = neutron_client.create_network(body=json_body)
144 network_dict = network['network']
145 return network_dict['id']
147 print "Error:", sys.exc_info()[0]
151 def update_neutron_net(neutron_client, network_id, shared=False):
152 json_body = {'network': {'shared': shared}}
154 neutron_client.update_network(network_id, body=json_body)
157 print "Error:", sys.exc_info()[0]
161 def delete_neutron_net(neutron_client, network_id):
163 neutron_client.delete_network(network_id)
166 print "Error:", sys.exc_info()[0]
170 def create_neutron_subnet(neutron_client, name, cidr, net_id):
171 json_body = {'subnets': [{'name': name, 'cidr': cidr,
172 'ip_version': 4, 'network_id': net_id}]}
174 subnet = neutron_client.create_subnet(body=json_body)
175 return subnet['subnets'][0]['id']
177 print "Error:", sys.exc_info()[0]
181 def delete_neutron_subnet(neutron_client, subnet_id):
183 neutron_client.delete_subnet(subnet_id)
186 print "Error:", sys.exc_info()[0]
190 def create_neutron_router(neutron_client, name):
191 json_body = {'router': {'name': name, 'admin_state_up': True}}
193 router = neutron_client.create_router(json_body)
194 return router['router']['id']
196 print "Error:", sys.exc_info()[0]
200 def delete_neutron_router(neutron_client, router_id):
201 json_body = {'router': {'id': router_id}}
203 neutron_client.delete_router(router=router_id)
206 print "Error:", sys.exc_info()[0]
210 def add_interface_router(neutron_client, router_id, subnet_id):
211 json_body = {"subnet_id": subnet_id}
213 neutron_client.add_interface_router(router=router_id, body=json_body)
216 print "Error:", sys.exc_info()[0]
220 def remove_interface_router(neutron_client, router_id, subnet_id):
221 json_body = {"subnet_id": subnet_id}
223 neutron_client.remove_interface_router(router=router_id,
227 print "Error:", sys.exc_info()[0]
231 def remove_gateway_router(neutron_client, router_id):
233 neutron_client.remove_gateway_router(router_id)
236 print "Error:", sys.exc_info()[0]
240 def create_neutron_port(neutron_client, name, network_id, ip):
241 json_body = {'port': {
242 'admin_state_up': True,
244 'network_id': network_id,
245 'fixed_ips': [{"ip_address": ip}]
248 port = neutron_client.create_port(body=json_body)
249 return port['port']['id']
251 print "Error:", sys.exc_info()[0]
255 def update_neutron_port(neutron_client, port_id, device_owner):
256 json_body = {'port': {
257 'device_owner': device_owner,
260 port = neutron_client.update_port(port=port_id,
262 return port['port']['id']
264 print "Error:", sys.exc_info()[0]
268 def delete_neutron_port(neutron_client, port_id):
270 neutron_client.delete_port(port_id)
273 print "Error:", sys.exc_info()[0]
277 def get_network_id(neutron_client, network_name):
278 networks = neutron_client.list_networks()['networks']
281 if n['name'] == network_name:
287 def check_neutron_net(neutron_client, net_name):
288 for network in neutron_client.list_networks()['networks']:
289 if network['name'] == net_name:
290 for subnet in network['subnets']:
295 def get_network_list(neutron_client):
296 network_list = neutron_client.list_networks()['networks']
297 if len(network_list) == 0:
303 def get_router_list(neutron_client):
304 router_list = neutron_client.list_routers()['routers']
305 if len(router_list) == 0:
311 def get_port_list(neutron_client):
312 port_list = neutron_client.list_ports()['ports']
313 if len(port_list) == 0:
319 def get_external_net(neutron_client):
320 for network in neutron_client.list_networks()['networks']:
321 if network['router:external']:
322 return network['name']
326 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
327 json_body = {"quota": {
328 "security_group": sg_quota,
329 "security_group_rule": sg_rule_quota
333 quota = neutron_client.update_quota(tenant_id=tenant_id,
337 print "Error:", sys.exc_info()[0]
341 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
342 snapshots_quota, gigabytes_quota):
343 quotas_values = {"volumes": vols_quota,
344 "snapshots": snapshots_quota,
345 "gigabytes": gigabytes_quota}
348 quotas_default = cinder_client.quotas.update(tenant_id,
352 print "Error:", sys.exc_info()[0]
356 def get_private_net(neutron_client):
357 # Checks if there is an existing shared private network
358 networks = neutron_client.list_networks()['networks']
359 if len(networks) == 0:
362 if (net['router:external'] is False) and (net['shared'] is True):
367 # ################ GLANCE #################
368 def get_images(nova_client):
370 images = nova_client.images.list()
376 def get_image_id(glance_client, image_name):
377 images = glance_client.images.list()
380 if i.name == image_name:
386 def create_glance_image(glance_client, image_name, file_path, public=True):
387 if not os.path.isfile(file_path):
388 print "Error: file " + file_path + " does not exist."
391 with open(file_path) as fimage:
392 image = glance_client.images.create(name=image_name,
395 container_format="bare",
399 print "Error:", sys.exc_info()[0]
403 def delete_glance_image(nova_client, image_id):
405 nova_client.images.delete(image_id)
408 print "Error:", sys.exc_info()[0]
412 # ################ CINDER #################
413 def get_volumes(cinder_client):
415 volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
421 def delete_volume(cinder_client, volume_id, forced=False):
425 cinder_client.volumes.detach(volume_id)
427 print "Error:", sys.exc_info()[0]
428 cinder_client.volumes.force_delete(volume_id)
430 cinder_client.volumes.delete(volume_id)
433 print "Error:", sys.exc_info()[0]
437 # ################ CINDER #################
438 def get_security_groups(neutron_client):
440 security_groups = neutron_client.list_security_groups()[
442 return security_groups
447 def delete_security_group(neutron_client, secgroup_id):
449 neutron_client.delete_security_group(secgroup_id)
452 print "Error:", sys.exc_info()[0]
456 # ################ KEYSTONE #################
457 def get_tenants(keystone_client):
459 tenants = keystone_client.tenants.list()
465 def get_tenant_id(keystone_client, tenant_name):
466 tenants = keystone_client.tenants.list()
469 if t.name == tenant_name:
475 def get_users(keystone_client):
477 users = keystone_client.users.list()
483 def get_role_id(keystone_client, role_name):
484 roles = keystone_client.roles.list()
487 if r.name == role_name:
493 def get_user_id(keystone_client, user_name):
494 users = keystone_client.users.list()
497 if u.name == user_name:
503 def create_tenant(keystone_client, tenant_name, tenant_description):
505 tenant = keystone_client.tenants.create(tenant_name,
510 print "Error:", sys.exc_info()[0]
514 def delete_tenant(keystone_client, tenant_id):
516 tenant = keystone_client.tenants.delete(tenant_id)
519 print "Error:", sys.exc_info()[0]
523 def create_user(keystone_client, user_name, user_password,
524 user_email, tenant_id):
526 user = keystone_client.users.create(user_name, user_password,
527 user_email, tenant_id,
531 print "Error:", sys.exc_info()[0]
535 def delete_user(keystone_client, user_id):
537 tenant = keystone_client.users.delete(user_id)
540 print "Error:", sys.exc_info()[0]
544 def add_role_user(keystone_client, user_id, role_id, tenant_id):
546 keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
549 print "Error:", sys.exc_info()[0]
553 # ################ UTILS #################
554 def check_internet_connectivity(url='http://www.opnfv.org/'):
556 Check if there is access to the internet
559 urllib2.urlopen(url, timeout=5)
561 except urllib2.URLError:
565 def download_url(url, dest_path):
567 Download a file to a destination path given a URL
569 name = url.rsplit('/')[-1]
570 dest = dest_path + "/" + name
572 response = urllib2.urlopen(url)
573 except (urllib2.HTTPError, urllib2.URLError):
576 with open(dest, 'wb') as f:
577 shutil.copyfileobj(response, f)
581 def execute_command(cmd, logger=None, exit_on_error=True):
583 Execute Linux command
586 logger.debug('Executing command : {}'.format(cmd))
587 output_file = "output.txt"
588 f = open(output_file, 'w+')
589 p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT)
591 f = open(output_file, 'r')
593 if result != "" and logger:
599 logger.error("Error when executing command %s" % cmd)
605 def get_git_branch(repo_path):
609 repo = Repo(repo_path)
610 branch = repo.active_branch
614 def get_installer_type(logger=None):
616 Get installer type (fuel, apex, joid, compass)
619 installer = os.environ['INSTALLER_TYPE']
622 logger.error("Impossible to retrieve the installer type")
628 def get_pod_name(logger=None):
630 Get PoD Name from env variable NODE_NAME
633 return os.environ['NODE_NAME']
637 "Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'")
641 def push_results_to_db(db_url, case_name, logger, pod_name,
642 git_version, payload):
643 url = db_url + "/results"
644 installer = get_installer_type(logger)
645 params = {"project_name": "functest", "case_name": case_name,
646 "pod_name": pod_name, "installer": installer,
647 "version": git_version, "details": payload}
649 headers = {'Content-Type': 'application/json'}
651 r = requests.post(url, data=json.dumps(params), headers=headers)
656 print "Error:", sys.exc_info()[0]
660 def get_resolvconf_ns():
662 rconf = open("/etc/resolv.conf", "r")
663 line = rconf.readline()
665 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
666 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
668 result = sock.connect_ex((ip.group(),53))
670 nameservers.append(ip.group())
671 line = rconf.readline()
674 def getTestEnv(test, functest_yaml):
675 # get the config of the testcase based on functest_config.yaml
677 # - test = test project e.g; ovno
678 # - test = testcase e.g. functest/odl
679 # look for the / to see if it is a test project or a testcase
681 TEST_ENV = functest_yaml.get("test-dependencies")
683 if test.find("/") < 0:
684 config_test = TEST_ENV[test]
686 test_split = test.split("/")
687 testproject = test_split[0]
688 testcase = test_split[1]
689 config_test = TEST_ENV[testproject][testcase]
691 # if not defined in dependencies => no dependencies
694 print "Error getTestEnv:", sys.exc_info()[0]
699 def get_ci_envvars():
701 Get the CI env variables
704 "installer": os.environ.get('INSTALLER_TYPE'),
705 "scenario": os.environ.get('DEPLOY_SCENARIO')}
709 def isTestRunnable(test, functest_yaml):
710 # By default we assume that all the tests are always runnable...
712 # Retrieve CI environment
713 ci_env = get_ci_envvars()
714 # Retrieve test environement from config file
715 test_env = getTestEnv(test, functest_yaml)
717 # if test_env not empty => dependencies to be checked
718 if test_env is not None and len(test_env) > 0:
719 # possible criteria = ["installer", "scenario"]
720 # consider test criteria from config file
721 # compare towards CI env through CI en variable
722 for criteria in test_env:
723 if re.search(test_env[criteria], ci_env[criteria]) is None:
724 # print "Test "+ test + " cannot be run on the environment"
729 def generateTestcaseList(functest_yaml):
732 testcase_list = functest_yaml.get("test-dependencies")
733 projects = testcase_list.keys()
735 for project in projects:
736 testcases = testcase_list[project]
737 # 1 or 2 levels for testcases project[/case]
738 # if only project name without controller or scenario
739 # => shall be runnable on any controller/scenario
740 if testcases is None:
741 test_list += project + " "
743 for testcase in testcases:
744 if testcase == "installer" or testcase == "scenario":
746 if isTestRunnable(project, functest_yaml):
747 test_list += project + " "
749 # project/testcase (2 levels)
750 thetest = project + "/" + testcase
751 if isTestRunnable(thetest, functest_yaml):
752 test_list += testcase + " "
754 # sort the list to execute the test in the right order
755 test_order_list = functest_yaml.get("test_exec_priority")
756 test_sorted_list = ""
757 for test in test_order_list:
758 if test_order_list[test] in test_list:
759 test_sorted_list += test_order_list[test] + " "
761 # create a file that could be consumed by run-test.sh
762 # this method is used only for CI
763 # so it can be run only in container
764 # reuse default conf directory to store the list of runnable tests
765 file = open("/home/opnfv/functest/conf/testcase-list.txt", 'w')
766 file.write(test_sorted_list)
769 return test_sorted_list