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
19 from datetime import datetime as dt
23 from six.moves import urllib
26 from functest.utils import constants
27 from functest.utils import decorators
28 from functest.utils.constants import CONST
30 logger = logging.getLogger(__name__)
33 # ----------------------------------------------------------
37 # -----------------------------------------------------------
38 def check_internet_connectivity(url='http://www.opnfv.org/'):
40 Check if there is access to the internet
43 urllib.request.urlopen(url, timeout=5)
45 except urllib.error.URLError:
49 def download_url(url, dest_path):
51 Download a file to a destination path given a URL
53 name = url.rsplit('/')[-1]
54 dest = dest_path + "/" + name
56 response = urllib.request.urlopen(url)
57 except (urllib.error.HTTPError, urllib.error.URLError):
60 with open(dest, 'wb') as f:
61 shutil.copyfileobj(response, f)
65 # ----------------------------------------------------------
69 # -----------------------------------------------------------
70 def get_installer_type():
72 Get installer type (fuel, apex, joid, compass)
75 installer = os.environ['INSTALLER_TYPE']
77 logger.error("Impossible to retrieve the installer type")
78 installer = "Unknown_installer"
88 scenario = os.environ['DEPLOY_SCENARIO']
90 logger.info("Impossible to retrieve the scenario."
91 "Use default os-nosdn-nofeature-noha")
92 scenario = "os-nosdn-nofeature-noha"
101 # Use the build tag to retrieve the version
102 # By default version is unknown
103 # if launched through CI the build tag has the following format
104 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
105 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
106 # jenkins-functest-fuel-baremetal-weekly-master-8
107 # use regex to match branch info
108 rule = "(dai|week)ly-(.+?)-[0-9]*"
109 build_tag = get_build_tag()
110 m = re.search(rule, build_tag)
119 Get PoD Name from env variable NODE_NAME
122 return os.environ['NODE_NAME']
125 "Unable to retrieve the POD name from environment. " +
126 "Using pod name 'unknown-pod'")
132 Get build tag of jenkins jobs
135 build_tag = os.environ['BUILD_TAG']
137 logger.info("Impossible to retrieve the build tag")
143 def logger_test_results(project, case_name, status, details):
145 Format test case results for the logger
147 pod_name = get_pod_name()
148 scenario = get_scenario()
149 version = get_version()
150 build_tag = get_build_tag()
151 db_url = CONST.__getattribute__("results_test_db_url")
155 "****************************************\n"
156 "\t %(p)s/%(n)s results \n\n"
157 "****************************************\n"
163 "build tag:\t%(b)s\n"
176 @decorators.can_dump_request_to_file
177 def push_results_to_db(project, case_name,
178 start_date, stop_date, result, details):
180 POST results to the Result target DB
182 # Retrieve params from CI and conf
183 url = CONST.__getattribute__("results_test_db_url")
186 installer = os.environ['INSTALLER_TYPE']
187 scenario = os.environ['DEPLOY_SCENARIO']
188 pod_name = os.environ['NODE_NAME']
189 build_tag = os.environ['BUILD_TAG']
190 except KeyError as e:
191 logger.error("Please set env var: " + str(e))
193 version = get_version()
194 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
195 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
197 params = {"project_name": project, "case_name": case_name,
198 "pod_name": pod_name, "installer": installer,
199 "version": version, "scenario": scenario, "criteria": result,
200 "build_tag": build_tag, "start_date": test_start,
201 "stop_date": test_stop, "details": details}
204 headers = {'Content-Type': 'application/json'}
206 r = requests.post(url, data=json.dumps(params, sort_keys=True),
210 except requests.RequestException as exc:
212 error = ("Pushing Result to DB(%s) failed: %s" %
215 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
216 except Exception as e:
217 error = ("Error [push_results_to_db("
219 "project: '%(project)s', "
223 "scenario: '%(s)s', "
224 "criteria: '%(c)s', "
225 "build_tag: '%(t)s', "
226 "details: '%(d)s')]: "
247 def get_resolvconf_ns():
249 Get nameservers from current resolv.conf
252 rconf = open("/etc/resolv.conf", "r")
253 line = rconf.readline()
254 resolver = dns.resolver.Resolver()
256 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
258 resolver.nameservers = [ip.group(0)]
260 result = resolver.query('opnfv.org')[0]
262 nameservers.append(ip.group())
263 except dns.exception.Timeout:
265 line = rconf.readline()
269 def get_ci_envvars():
271 Get the CI env variables
274 "installer": os.environ.get('INSTALLER_TYPE'),
275 "scenario": os.environ.get('DEPLOY_SCENARIO')}
279 def execute_command_raise(cmd, info=False, error_msg="",
280 verbose=True, output_file=None):
281 ret = execute_command(cmd, info, error_msg, verbose, output_file)
283 raise Exception(error_msg)
286 def execute_command(cmd, info=False, error_msg="",
287 verbose=True, output_file=None):
289 error_msg = ("The command '%s' failed." % cmd)
290 msg_exec = ("Executing command: '%s'" % cmd)
293 logger.info(msg_exec)
295 logger.debug(msg_exec)
296 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
297 stderr=subprocess.STDOUT)
299 f = open(output_file, "w")
300 for line in iter(p.stdout.readline, b''):
304 line = line.replace('\n', '')
310 returncode = p.wait()
313 logger.error(error_msg)
318 def get_dict_by_test(testname):
319 with open(get_testcases_file_dir()) as f:
320 testcases_yaml = yaml.safe_load(f)
322 for dic_tier in testcases_yaml.get("tiers"):
323 for dic_testcase in dic_tier['testcases']:
324 if dic_testcase['case_name'] == testname:
327 logger.error('Project %s is not defined in testcases.yaml' % testname)
331 def get_criteria_by_test(testname):
332 dict = get_dict_by_test(testname)
334 return dict['criteria']
338 # ----------------------------------------------------------
342 # -----------------------------------------------------------
343 def get_parameter_from_yaml(parameter, file):
345 Returns the value of a given parameter in file.yaml
346 parameter must be given in string format with dots
347 Example: general.openstack.image_name
349 with open(file) as f:
350 file_yaml = yaml.safe_load(f)
353 for element in parameter.split("."):
354 value = value.get(element)
356 raise ValueError("The parameter %s is not defined in"
357 " %s" % (parameter, file))
361 def get_functest_config(parameter):
362 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
363 return get_parameter_from_yaml(parameter, yaml_)
366 def merge_dicts(dict1, dict2):
367 for k in set(dict1.keys()).union(dict2.keys()):
368 if k in dict1 and k in dict2:
369 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
370 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
379 def get_testcases_file_dir():
380 return get_functest_config('general.functest.testcases_yaml')
383 def get_functest_yaml():
384 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
385 functest_yaml = yaml.safe_load(f)
390 def print_separator():
391 logger.info("==============================================")
395 """Measure the time it takes for a function to complete"""
396 @functools.wraps(func)
397 def timed(*args, **kwargs):
399 result = func(*args, **kwargs)
401 elapsed = '{0}'.format(te - ts)
402 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
403 f=func.__name__, a=args, kw=kwargs, t=elapsed))
404 return result, elapsed