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 functest_yaml = get_functest_yaml()
156 db_url = functest_yaml.get("results").get("test_db_url")
160 def logger_test_results(project, case_name, status, details):
161 pod_name = get_pod_name()
162 scenario = get_scenario()
163 version = get_version()
164 build_tag = get_build_tag()
168 "****************************************\n"
169 "\t %(p)s/%(n)s results \n\n"
170 "****************************************\n"
176 "build tag:\t%(b)s\n"
189 def push_results_to_db(project, case_name,
190 start_date, stop_date, criteria, details):
192 POST results to the Result target DB
194 # Retrieve params from CI and conf
195 url = get_db_url() + "/results"
198 installer = os.environ['INSTALLER_TYPE']
199 scenario = os.environ['DEPLOY_SCENARIO']
200 pod_name = os.environ['NODE_NAME']
201 build_tag = os.environ['BUILD_TAG']
202 except KeyError as e:
203 logger.error("Please set env var: " + str(e))
205 rule = "daily-(.+?)-[0-9]*"
206 m = re.search(rule, build_tag)
210 logger.error("Please fix BUILD_TAG env var: " + build_tag)
212 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
213 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
215 params = {"project_name": project, "case_name": case_name,
216 "pod_name": pod_name, "installer": installer,
217 "version": version, "scenario": scenario, "criteria": criteria,
218 "build_tag": build_tag, "start_date": test_start,
219 "stop_date": test_stop, "details": details}
222 headers = {'Content-Type': 'application/json'}
224 r = requests.post(url, data=json.dumps(params), headers=headers)
227 except requests.RequestException as exc:
229 error = ("Pushing Result to DB(%s) failed: %s" %
232 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
233 except Exception as e:
234 error = ("Error [push_results_to_db("
236 "project: '%(project)s', "
240 "scenario: '%(s)s', "
241 "criteria: '%(c)s', "
242 "build_tag: '%(t)s', "
243 "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, exit_on_error=True, info=False, error_msg="",
297 verbose=True, output_file=None):
299 error_msg = ("The command '%s' failed." % cmd)
300 msg_exec = ("Executing command: '%s'" % cmd)
303 logger.info(msg_exec)
305 logger.debug(msg_exec)
306 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
307 stderr=subprocess.STDOUT)
309 f = open(output_file, "w")
310 for line in iter(p.stdout.readline, b''):
314 line = line.replace('\n', '')
320 returncode = p.wait()
323 logger.error(error_msg)
330 def get_deployment_dir():
332 Returns current Rally deployment directory
334 functest_yaml = get_functest_yaml()
335 deployment_name = functest_yaml.get("rally").get("deployment_name")
336 rally_dir = functest_yaml.get("general").get("directories").get(
338 cmd = ("rally deployment list | awk '/" + deployment_name +
340 p = subprocess.Popen(cmd, shell=True,
341 stdout=subprocess.PIPE,
342 stderr=subprocess.STDOUT)
343 deployment_uuid = p.stdout.readline().rstrip()
344 if deployment_uuid == "":
345 logger.error("Rally deployment not found.")
347 deployment_dir = (rally_dir + "/tempest/for-deployment-" +
349 return deployment_dir
352 def get_criteria_by_test(testname):
354 file = get_testcases_file()
355 tiers = tb.TierBuilder("", "", file)
356 for tier in tiers.get_tiers():
357 for test in tier.get_tests():
358 if test.get_name() == testname:
359 criteria = test.get_criteria()
364 # ----------------------------------------------------------
368 # -----------------------------------------------------------
369 def get_parameter_from_yaml(parameter, file=None):
371 Returns the value of a given parameter in config_functest.yaml
372 parameter must be given in string format with dots
373 Example: general.openstack.image_name
376 file = os.environ["CONFIG_FUNCTEST_YAML"]
377 with open(file) as f:
378 functest_yaml = yaml.safe_load(f)
380 value = functest_yaml
381 for element in parameter.split("."):
382 value = value.get(element)
384 raise ValueError("The parameter %s is not defined in"
385 " config_functest.yaml" % parameter)
389 def check_success_rate(case_name, success_rate):
390 success_rate = float(success_rate)
391 criteria = get_criteria_by_test(case_name)
393 def get_criteria_value(op):
394 return float(criteria.split(op)[1].rstrip('%'))
400 c_value = get_criteria_value(op)
401 if eval("%s %s %s" % (success_rate, op, c_value)):
408 def merge_dicts(dict1, dict2):
409 for k in set(dict1.keys()).union(dict2.keys()):
410 if k in dict1 and k in dict2:
411 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
412 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
421 def check_test_result(test_name, ret, start_time, stop_time):
422 def get_criteria_value():
423 return get_criteria_by_test(test_name).split('==')[1].strip()
426 if str(ret) == get_criteria_value():
430 'timestart': start_time,
431 'duration': round(stop_time - start_time, 1),
435 return status, details
438 def get_testcases_file():
439 return FUNCTEST_REPO + "/ci/testcases.yaml"
442 def get_functest_yaml():
443 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
444 functest_yaml = yaml.safe_load(f)