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
23 from six.moves import urllib
27 from functest.utils import constants
28 from functest.utils import decorators
29 from functest.utils.constants import CONST
31 logger = logging.getLogger(__name__)
34 # ----------------------------------------------------------
38 # -----------------------------------------------------------
39 def check_internet_connectivity(url='http://www.opnfv.org/'):
41 Check if there is access to the internet
44 urllib.request.urlopen(url, timeout=5)
46 except urllib.error.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 = urllib.request.urlopen(url)
58 except (urllib.error.HTTPError, urllib.error.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.info("Impossible to retrieve the scenario."
101 "Use default os-nosdn-nofeature-noha")
102 scenario = "os-nosdn-nofeature-noha"
111 # Use the build tag to retrieve the version
112 # By default version is unknown
113 # if launched through CI the build tag has the following format
114 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
115 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
116 # jenkins-functest-fuel-baremetal-weekly-master-8
117 # use regex to match branch info
118 rule = "(dai|week)ly-(.+?)-[0-9]*"
119 build_tag = get_build_tag()
120 m = re.search(rule, build_tag)
129 Get PoD Name from env variable NODE_NAME
132 return os.environ['NODE_NAME']
135 "Unable to retrieve the POD name from environment. " +
136 "Using pod name 'unknown-pod'")
142 Get build tag of jenkins jobs
145 build_tag = os.environ['BUILD_TAG']
147 logger.info("Impossible to retrieve the build tag")
153 def logger_test_results(project, case_name, status, details):
155 Format test case results for the logger
157 pod_name = get_pod_name()
158 scenario = get_scenario()
159 version = get_version()
160 build_tag = get_build_tag()
161 db_url = CONST.__getattribute__("results_test_db_url")
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, result, details):
190 POST results to the Result target DB
192 # Retrieve params from CI and conf
193 url = CONST.__getattribute__("results_test_db_url")
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 version = get_version()
204 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
205 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
207 params = {"project_name": project, "case_name": case_name,
208 "pod_name": pod_name, "installer": installer,
209 "version": version, "scenario": scenario, "criteria": result,
210 "build_tag": build_tag, "start_date": test_start,
211 "stop_date": test_stop, "details": details}
214 headers = {'Content-Type': 'application/json'}
216 r = requests.post(url, data=json.dumps(params, sort_keys=True),
220 except requests.RequestException as exc:
222 error = ("Pushing Result to DB(%s) failed: %s" %
225 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
226 except Exception as e:
227 error = ("Error [push_results_to_db("
229 "project: '%(project)s', "
233 "scenario: '%(s)s', "
234 "criteria: '%(c)s', "
235 "build_tag: '%(t)s', "
236 "details: '%(d)s')]: "
257 def get_resolvconf_ns():
259 Get nameservers from current resolv.conf
262 rconf = open("/etc/resolv.conf", "r")
263 line = rconf.readline()
264 resolver = dns.resolver.Resolver()
266 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
268 resolver.nameservers = [ip.group(0)]
270 result = resolver.query('opnfv.org')[0]
272 nameservers.append(ip.group())
273 except dns.exception.Timeout:
275 line = rconf.readline()
279 def get_ci_envvars():
281 Get the CI env variables
284 "installer": os.environ.get('INSTALLER_TYPE'),
285 "scenario": os.environ.get('DEPLOY_SCENARIO')}
289 def execute_command_raise(cmd, info=False, error_msg="",
290 verbose=True, output_file=None):
291 ret = execute_command(cmd, info, error_msg, verbose, output_file)
293 raise Exception(error_msg)
296 def execute_command(cmd, 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)
328 def get_dict_by_test(testname):
329 with open(get_testcases_file_dir()) as f:
330 testcases_yaml = yaml.safe_load(f)
332 for dic_tier in testcases_yaml.get("tiers"):
333 for dic_testcase in dic_tier['testcases']:
334 if dic_testcase['case_name'] == testname:
337 logger.error('Project %s is not defined in testcases.yaml' % testname)
341 def get_criteria_by_test(testname):
342 dict = get_dict_by_test(testname)
344 return dict['criteria']
348 # ----------------------------------------------------------
352 # -----------------------------------------------------------
353 def get_parameter_from_yaml(parameter, file):
355 Returns the value of a given parameter in file.yaml
356 parameter must be given in string format with dots
357 Example: general.openstack.image_name
359 with open(file) as f:
360 file_yaml = yaml.safe_load(f)
363 for element in parameter.split("."):
364 value = value.get(element)
366 raise ValueError("The parameter %s is not defined in"
367 " %s" % (parameter, file))
371 def get_functest_config(parameter):
372 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
373 return get_parameter_from_yaml(parameter, yaml_)
376 def merge_dicts(dict1, dict2):
377 for k in set(dict1.keys()).union(dict2.keys()):
378 if k in dict1 and k in dict2:
379 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
380 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
389 def get_testcases_file_dir():
390 return get_functest_config('general.functest.testcases_yaml')
393 def get_functest_yaml():
394 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
395 functest_yaml = yaml.safe_load(f)
400 def print_separator():
401 logger.info("==============================================")
405 """Measure the time it takes for a function to complete"""
406 @functools.wraps(func)
407 def timed(*args, **kwargs):
409 result = func(*args, **kwargs)
411 elapsed = '{0}'.format(te - ts)
412 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
413 f=func.__name__, a=args, kw=kwargs, t=elapsed))
414 return result, elapsed