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
11 """ global variables """
13 from datetime import datetime as dt
24 import functest.ci.tier_builder as tb
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(logger=None):
82 Get installer type (fuel, apex, joid, compass)
85 installer = os.environ['INSTALLER_TYPE']
88 logger.error("Impossible to retrieve the installer type")
89 installer = "Unknown_installer"
94 def get_scenario(logger=None):
99 scenario = os.environ['DEPLOY_SCENARIO']
102 logger.error("Impossible to retrieve the scenario")
103 scenario = "Unknown_scenario"
108 def get_version(logger=None):
112 # Use the build tag to retrieve the version
113 # By default version is unknown
114 # if launched through CI the build tag has the following format
115 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
116 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
117 # use regex to match branch info
118 rule = "daily-(.+?)-[0-9]*"
119 build_tag = get_build_tag(logger)
120 m = re.search(rule, build_tag)
127 def get_pod_name(logger=None):
129 Get PoD Name from env variable NODE_NAME
132 return os.environ['NODE_NAME']
136 "Unable to retrieve the POD name from environment. " +
137 "Using pod name 'unknown-pod'")
141 def get_build_tag(logger=None):
143 Get build tag of jenkins jobs
146 build_tag = os.environ['BUILD_TAG']
149 logger.error("Impossible to retrieve the build tag")
150 build_tag = "unknown_build_tag"
155 def get_db_url(logger=None):
159 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
160 functest_yaml = yaml.safe_load(f)
162 db_url = functest_yaml.get("results").get("test_db_url")
166 def logger_test_results(logger, project, case_name, status, details):
167 pod_name = get_pod_name(logger)
168 scenario = get_scenario(logger)
169 version = get_version(logger)
170 build_tag = get_build_tag(logger)
173 "****************************************\n"
174 "\t %(p)s/%(n)s results \n\n"
175 "****************************************\n"
181 "build tag:\t%(b)s\n"
196 def push_results_to_db(project, case_name, logger,
197 start_date, stop_date, criteria, details):
199 POST results to the Result target DB
201 # Retrieve params from CI and conf
202 url = get_db_url(logger) + "/results"
203 installer = get_installer_type(logger)
204 scenario = get_scenario(logger)
205 version = get_version(logger)
206 pod_name = get_pod_name(logger)
207 build_tag = get_build_tag(logger)
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)
224 except requests.RequestException as exc:
226 error = ("Pushing Result to DB(%s) failed: %s" %
229 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
230 except Exception as e:
231 error = ("Error [push_results_to_db("
233 "project: '%(project)s', "
237 "scenario: '%(s)s', "
238 "criteria: '%(c)s', "
239 "build_tag: '%(t)s', "
240 "details: '%(d)s')]: "
264 def get_resolvconf_ns():
266 Get nameservers from current resolv.conf
269 rconf = open("/etc/resolv.conf", "r")
270 line = rconf.readline()
271 resolver = dns.resolver.Resolver()
273 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
275 resolver.nameservers = [str(ip)]
277 result = resolver.query('opnfv.org')[0]
279 nameservers.append(ip.group())
280 except dns.exception.Timeout:
282 line = rconf.readline()
286 def get_ci_envvars():
288 Get the CI env variables
291 "installer": os.environ.get('INSTALLER_TYPE'),
292 "scenario": os.environ.get('DEPLOY_SCENARIO')}
296 def execute_command(cmd, logger=None,
302 error_msg = ("The command '%s' failed." % cmd)
303 msg_exec = ("Executing command: '%s'" % cmd)
307 logger.info(msg_exec)
309 logger.debug(msg_exec)
312 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
313 stderr=subprocess.STDOUT)
314 for line in iter(p.stdout.readline, b''):
315 line = line.replace('\n', '')
324 returncode = p.wait()
328 logger.error(error_msg)
337 def get_deployment_dir(logger=None):
339 Returns current Rally deployment directory
341 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
342 functest_yaml = yaml.safe_load(f)
344 deployment_name = functest_yaml.get("rally").get("deployment_name")
345 rally_dir = functest_yaml.get("general").get("directories").get(
347 cmd = ("rally deployment list | awk '/" + deployment_name +
349 p = subprocess.Popen(cmd, shell=True,
350 stdout=subprocess.PIPE,
351 stderr=subprocess.STDOUT)
352 deployment_uuid = p.stdout.readline().rstrip()
353 if deployment_uuid == "":
355 logger.error("Rally deployment not found.")
357 deployment_dir = (rally_dir + "/tempest/for-deployment-" +
359 return deployment_dir
362 def get_criteria_by_test(testname):
364 file = FUNCTEST_REPO + "/ci/testcases.yaml"
365 tiers = tb.TierBuilder("", "", file)
366 for tier in tiers.get_tiers():
367 for test in tier.get_tests():
368 if test.get_name() == testname:
369 criteria = test.get_criteria()
374 # ----------------------------------------------------------
378 # -----------------------------------------------------------
379 def get_parameter_from_yaml(parameter, file=None):
381 Returns the value of a given parameter in config_functest.yaml
382 parameter must be given in string format with dots
383 Example: general.openstack.image_name
386 file = os.environ["CONFIG_FUNCTEST_YAML"]
387 with open(file) as f:
388 functest_yaml = yaml.safe_load(f)
390 value = functest_yaml
391 for element in parameter.split("."):
392 value = value.get(element)
394 raise ValueError("The parameter %s is not defined in"
395 " config_functest.yaml" % parameter)
399 def check_success_rate(case_name, success_rate):
400 success_rate = float(success_rate)
401 criteria = get_criteria_by_test(case_name)
403 def get_criteria_value(op):
404 return float(criteria.split(op)[1].rstrip('%'))
410 c_value = get_criteria_value(op)
411 if eval("%s %s %s" % (success_rate, op, c_value)):
418 def merge_dicts(dict1, dict2):
419 for k in set(dict1.keys()).union(dict2.keys()):
420 if k in dict1 and k in dict2:
421 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
422 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
431 def check_test_result(test_name, ret, start_time, stop_time):
432 def get_criteria_value():
433 return get_criteria_by_test(test_name).split('==')[1].strip()
436 if str(ret) == get_criteria_value():
440 'timestart': start_time,
441 'duration': round(stop_time - start_time, 1),
445 return status, details