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
26 from functest.utils import decorators
27 import functest.utils.functest_logger as ft_logger
29 logger = ft_logger.Logger("functest_utils").getLogger()
32 # ----------------------------------------------------------
36 # -----------------------------------------------------------
37 def check_internet_connectivity(url='http://www.opnfv.org/'):
39 Check if there is access to the internet
42 urllib2.urlopen(url, timeout=5)
44 except urllib2.URLError:
48 def download_url(url, dest_path):
50 Download a file to a destination path given a URL
52 name = url.rsplit('/')[-1]
53 dest = dest_path + "/" + name
55 response = urllib2.urlopen(url)
56 except (urllib2.HTTPError, urllib2.URLError):
59 with open(dest, 'wb') as f:
60 shutil.copyfileobj(response, f)
64 # ----------------------------------------------------------
68 # -----------------------------------------------------------
69 def get_git_branch(repo_path):
73 repo = Repo(repo_path)
74 branch = repo.active_branch
78 def get_installer_type():
80 Get installer type (fuel, apex, joid, compass)
83 installer = os.environ['INSTALLER_TYPE']
85 logger.error("Impossible to retrieve the installer type")
86 installer = "Unknown_installer"
96 scenario = os.environ['DEPLOY_SCENARIO']
98 logger.info("Impossible to retrieve the scenario."
99 "Use default os-nosdn-nofeature-noha")
100 scenario = "os-nosdn-nofeature-noha"
109 # Use the build tag to retrieve the version
110 # By default version is unknown
111 # if launched through CI the build tag has the following format
112 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
113 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
114 # use regex to match branch info
115 rule = "daily-(.+?)-[0-9]*"
116 build_tag = get_build_tag()
117 m = re.search(rule, build_tag)
126 Get PoD Name from env variable NODE_NAME
129 return os.environ['NODE_NAME']
132 "Unable to retrieve the POD name from environment. " +
133 "Using pod name 'unknown-pod'")
139 Get build tag of jenkins jobs
142 build_tag = os.environ['BUILD_TAG']
144 logger.info("Impossible to retrieve the build tag")
154 return get_functest_config('results.test_db_url')
157 def logger_test_results(project, case_name, status, details):
158 pod_name = get_pod_name()
159 scenario = get_scenario()
160 version = get_version()
161 build_tag = get_build_tag()
165 "****************************************\n"
166 "\t %(p)s/%(n)s results \n\n"
167 "****************************************\n"
173 "build tag:\t%(b)s\n"
186 @decorators.can_dump_request_to_file
187 def push_results_to_db(project, case_name,
188 start_date, stop_date, criteria, details):
190 POST results to the Result target DB
192 # Retrieve params from CI and conf
193 url = get_db_url() + "/results"
196 installer = os.environ['INSTALLER_TYPE']
197 scenario = os.environ['DEPLOY_SCENARIO']
198 pod_name = os.environ['NODE_NAME']
199 build_tag = os.environ['BUILD_TAG']
200 except KeyError as e:
201 logger.error("Please set env var: " + str(e))
203 rule = "daily-(.+?)-[0-9]*"
204 m = re.search(rule, build_tag)
208 logger.error("Please fix BUILD_TAG env var: " + build_tag)
210 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
211 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
213 params = {"project_name": project, "case_name": case_name,
214 "pod_name": pod_name, "installer": installer,
215 "version": version, "scenario": scenario, "criteria": criteria,
216 "build_tag": build_tag, "start_date": test_start,
217 "stop_date": test_stop, "details": details}
220 headers = {'Content-Type': 'application/json'}
222 r = requests.post(url, data=json.dumps(params), headers=headers)
225 except requests.RequestException as exc:
227 error = ("Pushing Result to DB(%s) failed: %s" %
230 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
231 except Exception as e:
232 error = ("Error [push_results_to_db("
234 "project: '%(project)s', "
238 "scenario: '%(s)s', "
239 "criteria: '%(c)s', "
240 "build_tag: '%(t)s', "
241 "details: '%(d)s')]: "
262 def get_resolvconf_ns():
264 Get nameservers from current resolv.conf
267 rconf = open("/etc/resolv.conf", "r")
268 line = rconf.readline()
269 resolver = dns.resolver.Resolver()
271 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
273 resolver.nameservers = [ip.group(0)]
275 result = resolver.query('opnfv.org')[0]
277 nameservers.append(ip.group())
278 except dns.exception.Timeout:
280 line = rconf.readline()
284 def get_ci_envvars():
286 Get the CI env variables
289 "installer": os.environ.get('INSTALLER_TYPE'),
290 "scenario": os.environ.get('DEPLOY_SCENARIO')}
294 def execute_command_raise(cmd, info=False, error_msg="",
295 verbose=True, output_file=None):
296 ret = execute_command(cmd, info, error_msg, verbose, output_file)
298 raise Exception(error_msg)
301 def execute_command(cmd, info=False, error_msg="",
302 verbose=True, output_file=None):
304 error_msg = ("The command '%s' failed." % cmd)
305 msg_exec = ("Executing command: '%s'" % cmd)
308 logger.info(msg_exec)
310 logger.debug(msg_exec)
311 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
312 stderr=subprocess.STDOUT)
314 f = open(output_file, "w")
315 for line in iter(p.stdout.readline, b''):
319 line = line.replace('\n', '')
325 returncode = p.wait()
328 logger.error(error_msg)
333 def get_dict_by_test(testname):
334 with open(get_testcases_file_dir()) as f:
335 testcases_yaml = yaml.safe_load(f)
337 for dic_tier in testcases_yaml.get("tiers"):
338 for dic_testcase in dic_tier['testcases']:
339 if dic_testcase['name'] == testname:
342 logger.error('Project %s is not defined in testcases.yaml' % testname)
346 def get_criteria_by_test(testname):
347 dict = get_dict_by_test(testname)
349 return dict['criteria']
353 # ----------------------------------------------------------
357 # -----------------------------------------------------------
358 def get_parameter_from_yaml(parameter, file):
360 Returns the value of a given parameter in file.yaml
361 parameter must be given in string format with dots
362 Example: general.openstack.image_name
364 with open(file) as f:
365 file_yaml = yaml.safe_load(f)
368 for element in parameter.split("."):
369 value = value.get(element)
371 raise ValueError("The parameter %s is not defined in"
372 " %s" % (parameter, file))
376 def get_functest_config(parameter):
377 yaml_ = os.environ["CONFIG_FUNCTEST_YAML"]
378 return get_parameter_from_yaml(parameter, yaml_)
381 def check_success_rate(case_name, success_rate):
382 success_rate = float(success_rate)
383 criteria = get_criteria_by_test(case_name)
385 def get_criteria_value(op):
386 return float(criteria.split(op)[1].rstrip('%'))
392 c_value = get_criteria_value(op)
393 if eval("%s %s %s" % (success_rate, op, c_value)):
400 def merge_dicts(dict1, dict2):
401 for k in set(dict1.keys()).union(dict2.keys()):
402 if k in dict1 and k in dict2:
403 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
404 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
413 def get_testcases_file_dir():
414 return get_functest_config('general.functest.testcases_yaml')
417 def get_functest_yaml():
418 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
419 functest_yaml = yaml.safe_load(f)
424 def print_separator():
425 logger.info("==============================================")
429 """Measure the time it takes for a function to complete"""
430 @functools.wraps(func)
431 def timed(*args, **kwargs):
433 result = func(*args, **kwargs)
435 elapsed = '{0}'.format(te - ts)
436 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
437 f=func.__name__, a=args, kw=kwargs, t=elapsed))
438 return result, elapsed