#!/usr/bin/env python # # jose.lausuch@ericsson.com # valentin.boucher@orange.com # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # import os import os.path import urllib2 import subprocess import sys import requests import json import shutil from git import Repo # ############ CREDENTIALS OPENSTACK ############# def check_credentials(): """ Check if the OpenStack credentials (openrc) are sourced """ env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME'] return all(map(lambda v: v in os.environ and os.environ[v], env_vars)) def get_credentials(service): """Returns a creds dictionary filled with the following keys: * username * password/api_key (depending on the service) * tenant_name/project_id (depending on the service) * auth_url :param service: a string indicating the name of the service requesting the credentials. """ creds = {} # Unfortunately, each of the OpenStack client will request slightly # different entries in their credentials dict. if service.lower() in ("nova", "cinder"): password = "api_key" tenant = "project_id" else: password = "password" tenant = "tenant_name" # The most common way to pass these info to the script is to do it through # environment variables. creds.update({ "username": os.environ.get('OS_USERNAME', "admin"), password: os.environ.get("OS_PASSWORD", 'admin'), "auth_url": os.environ.get("OS_AUTH_URL", "http://192.168.20.71:5000/v2.0"), tenant: os.environ.get("OS_TENANT_NAME", "admin"), }) return creds # ################ NOVA ################# def get_instances(nova_client): try: instances = nova_client.servers.list(search_opts={'all_tenants': 1}) return instances except: return None def get_instance_status(nova_client, instance): try: instance = nova_client.servers.get(instance.id) return instance.status except: return None def get_instance_by_name(nova_client, instance_name): try: instance = nova_client.servers.find(name=instance_name) return instance except: return None def get_flavor_id(nova_client, flavor_name): flavors = nova_client.flavors.list(detailed=True) id = '' for f in flavors: if f.name == flavor_name: id = f.id break return id def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram): flavors = nova_client.flavors.list(detailed=True) id = '' for f in flavors: if min_ram <= f.ram and f.ram <= max_ram: id = f.id break return id def delete_instance(nova_client, instance_id): try: nova_client.servers.force_delete(instance_id) return True except: print "Error:", sys.exc_info()[0] return False def get_floating_ips(nova_client): try: floating_ips = nova_client.floating_ips.list() return floating_ips except: return None def delete_floating_ip(nova_client, floatingip_id): try: nova_client.floating_ips.delete(floatingip_id) return True except: print "Error:", sys.exc_info()[0] return None # ################ NEUTRON ################# def create_neutron_net(neutron_client, name): json_body = {'network': {'name': name, 'admin_state_up': True}} try: network = neutron_client.create_network(body=json_body) network_dict = network['network'] return network_dict['id'] except: print "Error:", sys.exc_info()[0] return False def update_neutron_net(neutron_client, network_id, shared=False): json_body = {'network': {'shared': shared}} try: neutron_client.update_network(network_id, body=json_body) return True except: print "Error:", sys.exc_info()[0] return False def delete_neutron_net(neutron_client, network_id): try: neutron_client.delete_network(network_id) return True except: print "Error:", sys.exc_info()[0] return False def c

############## def check_internet_connectivity(url='http://www.opnfv.org/'): """ Check if there is access to the internet """ try: urllib2.urlopen(url, timeout=5) return True except urllib2.URLError: return False def download_url(url, dest_path): """ Download a file to a destination path given a URL """ name = url.rsplit('/')[-1] dest = dest_path + "/" + name try: response = urllib2.urlopen(url) except (urllib2.HTTPError, urllib2.URLError): return False with open(dest, 'wb') as f: shutil.copyfileobj(response, f) return True def execute_command(cmd, logger=None): """ Execute Linux command """ if logger: logger.debug('Executing command : {}'.format(cmd)) output_file = "output.txt" f = open(output_file, 'w+') p = subprocess.call(cmd, shell=True, stdout=f, stderr=subprocess.STDOUT) f.close() f = open(output_file, 'r') result = f.read() if result != "" and logger: logger.debug(result) if p == 0: return True else: if logger: logger.error("Error when executing command %s" % cmd) exit(-1) def get_git_branch(repo_path): """ Get git branch name """ repo = Repo(repo_path) branch = repo.active_branch return branch.name def get_installer_type(logger=None): """ Get installer type (fuel, foreman, apex, joid, compass) """ try: installer = os.environ['INSTALLER_TYPE'] except KeyError: if logger: logger.error("Impossible to retrieve the installer type") installer = "Unkown" return installer def get_pod_name(logger=None): """ Get PoD Name from env variable NODE_NAME """ try: return os.environ['NODE_NAME'] except KeyError: if logger: logger.error("Unable to retrieve the POD name from environment.Using pod name 'unknown-pod'") return "unknown-pod" def push_results_to_db(db_url, case_name, logger, pod_name, git_version, payload): url = db_url + "/results" installer = get_installer_type(logger) params = {"project_name": "functest", "case_name": case_name, "pod_name": pod_name, "installer": installer, "version": git_version, "details": payload} headers = {'Content-Type': 'application/json'} try: r = requests.post(url, data=json.dumps(params), headers=headers) logger.debug(r) return True except: print "Error:", sys.exc_info()[0] return False def getTestEnv(test, functest_yaml): # get the config of the testcase based on functest_config.yaml # 2 options # - test = test project e.g; ovno # - test = testcase e.g. functest/odl # look for the / to see if it is a test project or a testcase try: TEST_ENV = functest_yaml.get("test-dependencies") if test.find("/") < 0: config_test = TEST_ENV[test] else: test_split = test.split("/") testproject = test_split[0] testcase = test_split[1] config_test = TEST_ENV[testproject][testcase] except KeyError: # if not defined in dependencies => no dependencies config_test = "" except: print "Error getTestEnv:", sys.exc_info()[0] return config_test def get_ci_envvars(): """ Get the CI env variables """ ci_env_var = { "installer": os.environ.get('INSTALLER_TYPE'), "controller": os.environ.get('SDN_CONTROLLER'), "options": os.environ.get("OPNFV_FEATURE")} return ci_env_var def isTestRunnable(test, functest_yaml): # check getTestEnv(test) and CI env var # check installer, controller and options # e.g. if test needs onos => do not run odl suite try: # By default we assume that all the tests are always runnable... is_runnable = True # Retrieve CI environment ci_env = get_ci_envvars() # Retrieve test environement from config file test_env = getTestEnv(test, functest_yaml) # if test_env not empty => dependencies to be checked if test_env is not None and len(test_env) > 0: # possible criteria = ["installer", "controller", "options"] # consider test criteria from config file # compare towards CI env through CI en variable for criteria in test_env: if test_env[criteria] != ci_env[criteria]: # print "Test "+ test + " cannot be run on the environment" is_runnable = False except: print "Error isTestRunnable:", sys.exc_info()[0] return is_runnable def generateTestcaseList(functest_yaml): try: test_list = "" # Retrieve CI environment get_ci_envvars() # get testcases testcase_list = functest_yaml.get("test-dependencies") projects = testcase_list.keys() for project in projects: testcases = testcase_list[project] # 1 or 2 levels for testcases project[/case] # if only project name without controller or scenario # => shall be runnable on any controller/scenario if testcases is None: test_list += project + " " else: for testcase in testcases: if testcase == "controller" or testcase == "scenario": # project (1 level) if isTestRunnable(project, functest_yaml): test_list += project + " " else: # project/testcase (2 levels) thetest = project + "/" + testcase if isTestRunnable(thetest, functest_yaml): test_list += testcase + " " # create a file that could be consumed by run-test.sh file = open("testcase-list.txt", 'w') file.write(test_list) file.close() return test_list # test for each testcase if it is runnable # towards the declared configuration # generate the test config file except: print "Error generateTestcaseList:", sys.exc_info()[0]