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
10 from datetime import datetime as dt
20 import functest.ci.tier_builder as tb
21 import functest.utils.functest_logger as ft_logger
28 logger = ft_logger.Logger("functest_utils").getLogger()
30 REPOS_DIR = os.getenv('repos_dir')
31 FUNCTEST_REPO = ("%s/functest" % REPOS_DIR)
34 # ----------------------------------------------------------
38 # -----------------------------------------------------------
39 def check_internet_connectivity(url='http://www.opnfv.org/'):
41 Check if there is access to the internet
44 urllib2.urlopen(url, timeout=5)
46 except urllib2.URLError:
50 def download_url(url, dest_path):
52 Download a file to a destination path given a URL
54 name = url.rsplit('/')[-1]
55 dest = dest_path + "/" + name
57 response = urllib2.urlopen(url)
58 except (urllib2.HTTPError, urllib2.URLError):
61 with open(dest, 'wb') as f:
62 shutil.copyfileobj(response, f)
66 # ----------------------------------------------------------
70 # -----------------------------------------------------------
71 def get_git_branch(repo_path):
75 repo = Repo(repo_path)
76 branch = repo.active_branch
80 def get_installer_type():
82 Get installer type (fuel, apex, joid, compass)
85 installer = os.environ['INSTALLER_TYPE']
87 logger.error("Impossible to retrieve the installer type")
88 installer = "Unknown_installer"
98 scenario = os.environ['DEPLOY_SCENARIO']
100 logger.error("Impossible to retrieve the scenario")
101 scenario = "Unknown_scenario"
110 # Use the build tag to retrieve the version
111 # By default version is unknown
112 # if launched through CI the build tag has the following format
113 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
114 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
115 # use regex to match branch info
116 rule = "daily-(.+?)-[0-9]*"
117 build_tag = get_build_tag()
118 m = re.search(rule, build_tag)
127 Get PoD Name from env variable NODE_NAME
130 return os.environ['NODE_NAME']
133 "Unable to retrieve the POD name from environment. " +
134 "Using pod name 'unknown-pod'")
140 Get build tag of jenkins jobs
143 build_tag = os.environ['BUILD_TAG']
145 logger.error("Impossible to retrieve the build tag")
146 build_tag = "unknown_build_tag"
155 return get_functest_config('results.test_db_url')
158 def logger_test_results(project, case_name, status, details):
159 pod_name = get_pod_name()
160 scenario = get_scenario()
161 version = get_version()
162 build_tag = get_build_tag()
166 "****************************************\n"
167 "\t %(p)s/%(n)s results \n\n"
168 "****************************************\n"
174 "build tag:\t%(b)s\n"
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 = [str(ip)]
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(cmd, exit_on_error=True, info=False, error_msg="",
295 verbose=True, output_file=None):
297 error_msg = ("The command '%s' failed." % cmd)
298 msg_exec = ("Executing command: '%s'" % cmd)
301 logger.info(msg_exec)
303 logger.debug(msg_exec)
304 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
305 stderr=subprocess.STDOUT)
307 f = open(output_file, "w")
308 for line in iter(p.stdout.readline, b''):
312 line = line.replace('\n', '')
318 returncode = p.wait()
321 logger.error(error_msg)
328 def get_deployment_dir():
330 Returns current Rally deployment directory
332 deployment_name = get_functest_config('rally.deployment_name')
333 rally_dir = get_functest_config('general.directories.dir_rally_inst')
334 cmd = ("rally deployment list | awk '/" + deployment_name +
336 p = subprocess.Popen(cmd, shell=True,
337 stdout=subprocess.PIPE,
338 stderr=subprocess.STDOUT)
339 deployment_uuid = p.stdout.readline().rstrip()
340 if deployment_uuid == "":
341 logger.error("Rally deployment not found.")
343 deployment_dir = (rally_dir + "/tempest/for-deployment-" +
345 return deployment_dir
348 def get_criteria_by_test(testname):
350 file = get_testcases_file()
351 tiers = tb.TierBuilder("", "", file)
352 for tier in tiers.get_tiers():
353 for test in tier.get_tests():
354 if test.get_name() == testname:
355 criteria = test.get_criteria()
360 # ----------------------------------------------------------
364 # -----------------------------------------------------------
365 def get_parameter_from_yaml(parameter, file):
367 Returns the value of a given parameter in file.yaml
368 parameter must be given in string format with dots
369 Example: general.openstack.image_name
371 with open(file) as f:
372 file_yaml = yaml.safe_load(f)
375 for element in parameter.split("."):
376 value = value.get(element)
378 raise ValueError("The parameter %s is not defined in"
379 " config_functest.yaml" % parameter)
383 def get_functest_config(parameter):
384 yaml_ = os.environ["CONFIG_FUNCTEST_YAML"]
385 return get_parameter_from_yaml(parameter, yaml_)
388 def check_success_rate(case_name, success_rate):
389 success_rate = float(success_rate)
390 criteria = get_criteria_by_test(case_name)
392 def get_criteria_value(op):
393 return float(criteria.split(op)[1].rstrip('%'))
399 c_value = get_criteria_value(op)
400 if eval("%s %s %s" % (success_rate, op, c_value)):
407 def merge_dicts(dict1, dict2):
408 for k in set(dict1.keys()).union(dict2.keys()):
409 if k in dict1 and k in dict2:
410 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
411 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
420 def check_test_result(test_name, ret, start_time, stop_time):
421 def get_criteria_value():
422 return get_criteria_by_test(test_name).split('==')[1].strip()
425 if str(ret) == get_criteria_value():
429 'timestart': start_time,
430 'duration': round(stop_time - start_time, 1),
434 return status, details
437 def get_testcases_file():
438 return FUNCTEST_REPO + "/ci/testcases.yaml"
441 def get_functest_yaml():
442 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
443 functest_yaml = yaml.safe_load(f)