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
17 from datetime import datetime as dt
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.error("Impossible to retrieve the scenario")
99 scenario = "Unknown_scenario"
108 # Use the build tag to retrieve the version
109 # By default version is unknown
110 # if launched through CI the build tag has the following format
111 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
112 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
113 # use regex to match branch info
114 rule = "daily-(.+?)-[0-9]*"
115 build_tag = get_build_tag()
116 m = re.search(rule, build_tag)
125 Get PoD Name from env variable NODE_NAME
128 return os.environ['NODE_NAME']
131 "Unable to retrieve the POD name from environment. " +
132 "Using pod name 'unknown-pod'")
138 Get build tag of jenkins jobs
141 build_tag = os.environ['BUILD_TAG']
143 logger.error("Impossible to retrieve the build tag")
144 build_tag = "unknown_build_tag"
153 return get_functest_config('results.test_db_url')
156 def logger_test_results(project, case_name, status, details):
157 pod_name = get_pod_name()
158 scenario = get_scenario()
159 version = get_version()
160 build_tag = get_build_tag()
164 "****************************************\n"
165 "\t %(p)s/%(n)s results \n\n"
166 "****************************************\n"
172 "build tag:\t%(b)s\n"
185 def push_results_to_db(project, case_name,
186 start_date, stop_date, criteria, details):
188 POST results to the Result target DB
190 # Retrieve params from CI and conf
191 url = get_db_url() + "/results"
194 installer = os.environ['INSTALLER_TYPE']
195 scenario = os.environ['DEPLOY_SCENARIO']
196 pod_name = os.environ['NODE_NAME']
197 build_tag = os.environ['BUILD_TAG']
198 except KeyError as e:
199 logger.error("Please set env var: " + str(e))
201 rule = "daily-(.+?)-[0-9]*"
202 m = re.search(rule, build_tag)
206 logger.error("Please fix BUILD_TAG env var: " + build_tag)
208 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
209 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
211 params = {"project_name": project, "case_name": case_name,
212 "pod_name": pod_name, "installer": installer,
213 "version": version, "scenario": scenario, "criteria": criteria,
214 "build_tag": build_tag, "start_date": test_start,
215 "stop_date": test_stop, "details": details}
218 headers = {'Content-Type': 'application/json'}
220 r = requests.post(url, data=json.dumps(params), headers=headers)
223 except requests.RequestException as exc:
225 error = ("Pushing Result to DB(%s) failed: %s" %
228 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
229 except Exception as e:
230 error = ("Error [push_results_to_db("
232 "project: '%(project)s', "
236 "scenario: '%(s)s', "
237 "criteria: '%(c)s', "
238 "build_tag: '%(t)s', "
239 "details: '%(d)s')]: "
260 def get_resolvconf_ns():
262 Get nameservers from current resolv.conf
265 rconf = open("/etc/resolv.conf", "r")
266 line = rconf.readline()
267 resolver = dns.resolver.Resolver()
269 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
271 resolver.nameservers = [str(ip)]
273 result = resolver.query('opnfv.org')[0]
275 nameservers.append(ip.group())
276 except dns.exception.Timeout:
278 line = rconf.readline()
282 def get_ci_envvars():
284 Get the CI env variables
287 "installer": os.environ.get('INSTALLER_TYPE'),
288 "scenario": os.environ.get('DEPLOY_SCENARIO')}
292 def execute_command(cmd, info=False, error_msg="",
293 verbose=True, output_file=None):
295 error_msg = ("The command '%s' failed." % cmd)
296 msg_exec = ("Executing command: '%s'" % cmd)
299 logger.info(msg_exec)
301 logger.debug(msg_exec)
302 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
303 stderr=subprocess.STDOUT)
305 f = open(output_file, "w")
306 for line in iter(p.stdout.readline, b''):
310 line = line.replace('\n', '')
316 returncode = p.wait()
319 logger.error(error_msg)
324 def get_deployment_dir():
326 Returns current Rally deployment directory
328 deployment_name = get_functest_config('rally.deployment_name')
329 rally_dir = get_functest_config('general.directories.dir_rally_inst')
330 cmd = ("rally deployment list | awk '/" + deployment_name +
332 p = subprocess.Popen(cmd, shell=True,
333 stdout=subprocess.PIPE,
334 stderr=subprocess.STDOUT)
335 deployment_uuid = p.stdout.readline().rstrip()
336 if deployment_uuid == "":
337 logger.error("Rally deployment not found.")
339 deployment_dir = (rally_dir + "/tempest/for-deployment-" +
341 return deployment_dir
344 def get_dict_by_test(testname):
345 with open(get_testcases_file_dir()) as f:
346 testcases_yaml = yaml.safe_load(f)
348 for dic_tier in testcases_yaml.get("tiers"):
349 for dic_testcase in dic_tier['testcases']:
350 if dic_testcase['name'] == testname:
353 logger.error('Project %s is not defined in testcases.yaml' % testname)
357 def get_criteria_by_test(testname):
358 dict = get_dict_by_test(testname)
360 return dict['criteria']
364 # ----------------------------------------------------------
368 # -----------------------------------------------------------
369 def get_parameter_from_yaml(parameter, file):
371 Returns the value of a given parameter in file.yaml
372 parameter must be given in string format with dots
373 Example: general.openstack.image_name
375 with open(file) as f:
376 file_yaml = yaml.safe_load(f)
379 for element in parameter.split("."):
380 value = value.get(element)
382 raise ValueError("The parameter %s is not defined in"
383 " config_functest.yaml" % parameter)
387 def get_functest_config(parameter):
388 yaml_ = os.environ["CONFIG_FUNCTEST_YAML"]
389 return get_parameter_from_yaml(parameter, yaml_)
392 def check_success_rate(case_name, success_rate):
393 success_rate = float(success_rate)
394 criteria = get_criteria_by_test(case_name)
396 def get_criteria_value(op):
397 return float(criteria.split(op)[1].rstrip('%'))
403 c_value = get_criteria_value(op)
404 if eval("%s %s %s" % (success_rate, op, c_value)):
411 def merge_dicts(dict1, dict2):
412 for k in set(dict1.keys()).union(dict2.keys()):
413 if k in dict1 and k in dict2:
414 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
415 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
424 def get_testcases_file_dir():
425 return get_functest_config('general.functest.testcases_yaml')
428 def get_functest_yaml():
429 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
430 functest_yaml = yaml.safe_load(f)
435 def print_separator():
436 logger.info("==============================================")
440 """Measure the time it takes for a function to complete"""
441 @functools.wraps(func)
442 def timed(*args, **kwargs):
444 result = func(*args, **kwargs)
446 elapsed = '{0}'.format(te - ts)
447 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
448 f=func.__name__, a=args, kw=kwargs, t=elapsed))
449 return result, elapsed