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
20 from datetime import datetime as dt
24 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 # -----------------------------------------------------------
75 # Use the build tag to retrieve the version
76 # By default version is unknown
77 # if launched through CI the build tag has the following format
78 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
79 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
80 # jenkins-functest-fuel-baremetal-weekly-master-8
81 # use regex to match branch info
82 rule = "(dai|week)ly-(.+?)-[0-9]*"
83 build_tag = CONST.__getattribute__('BUILD_TAG')
86 m = re.search(rule, build_tag)
93 def logger_test_results(project, case_name, status, details):
95 Format test case results for the logger
97 pod_name = CONST.__getattribute__('NODE_NAME')
98 scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
99 version = get_version()
100 build_tag = CONST.__getattribute__('BUILD_TAG')
101 db_url = CONST.__getattribute__("results_test_db_url")
105 "****************************************\n"
106 "\t %(p)s/%(n)s results \n\n"
107 "****************************************\n"
113 "build tag:\t%(b)s\n"
126 @decorators.can_dump_request_to_file
127 def push_results_to_db(project, case_name,
128 start_date, stop_date, result, details):
130 POST results to the Result target DB
132 # Retrieve params from CI and conf
133 url = CONST.__getattribute__("results_test_db_url")
136 installer = os.environ['INSTALLER_TYPE']
137 scenario = os.environ['DEPLOY_SCENARIO']
138 pod_name = os.environ['NODE_NAME']
139 build_tag = os.environ['BUILD_TAG']
140 except KeyError as e:
141 logger.error("Please set env var: " + str(e))
143 version = get_version()
144 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
145 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
147 params = {"project_name": project, "case_name": case_name,
148 "pod_name": pod_name, "installer": installer,
149 "version": version, "scenario": scenario, "criteria": result,
150 "build_tag": build_tag, "start_date": test_start,
151 "stop_date": test_stop, "details": details}
154 headers = {'Content-Type': 'application/json'}
156 r = requests.post(url, data=json.dumps(params, sort_keys=True),
160 except requests.RequestException as exc:
162 error = ("Pushing Result to DB(%s) failed: %s" %
165 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
166 except Exception as e:
167 error = ("Error [push_results_to_db("
169 "project: '%(project)s', "
173 "scenario: '%(s)s', "
174 "criteria: '%(c)s', "
175 "build_tag: '%(t)s', "
176 "details: '%(d)s')]: "
197 def get_resolvconf_ns():
199 Get nameservers from current resolv.conf
202 rconf = open("/etc/resolv.conf", "r")
203 line = rconf.readline()
204 resolver = dns.resolver.Resolver()
206 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
208 resolver.nameservers = [ip.group(0)]
210 result = resolver.query('opnfv.org')[0]
212 nameservers.append(ip.group())
213 except dns.exception.Timeout:
215 line = rconf.readline()
219 def get_ci_envvars():
221 Get the CI env variables
224 "installer": os.environ.get('INSTALLER_TYPE'),
225 "scenario": os.environ.get('DEPLOY_SCENARIO')}
229 def execute_command_raise(cmd, info=False, error_msg="",
230 verbose=True, output_file=None):
231 ret = execute_command(cmd, info, error_msg, verbose, output_file)
233 raise Exception(error_msg)
236 def execute_command(cmd, info=False, error_msg="",
237 verbose=True, output_file=None):
239 error_msg = ("The command '%s' failed." % cmd)
240 msg_exec = ("Executing command: '%s'" % cmd)
243 logger.info(msg_exec)
245 logger.debug(msg_exec)
246 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
247 stderr=subprocess.STDOUT)
249 f = open(output_file, "w")
250 for line in iter(p.stdout.readline, b''):
254 line = line.replace('\n', '')
260 returncode = p.wait()
263 logger.error(error_msg)
268 def get_dict_by_test(testname):
269 with open(pkg_resources.resource_filename(
270 'functest', 'ci/testcases.yaml')) as f:
271 testcases_yaml = yaml.safe_load(f)
273 for dic_tier in testcases_yaml.get("tiers"):
274 for dic_testcase in dic_tier['testcases']:
275 if dic_testcase['case_name'] == testname:
278 logger.error('Project %s is not defined in testcases.yaml' % testname)
282 def get_criteria_by_test(testname):
283 dict = get_dict_by_test(testname)
285 return dict['criteria']
289 # ----------------------------------------------------------
293 # -----------------------------------------------------------
294 def get_parameter_from_yaml(parameter, file):
296 Returns the value of a given parameter in file.yaml
297 parameter must be given in string format with dots
298 Example: general.openstack.image_name
300 with open(file) as f:
301 file_yaml = yaml.safe_load(f)
304 for element in parameter.split("."):
305 value = value.get(element)
307 raise ValueError("The parameter %s is not defined in"
308 " %s" % (parameter, file))
312 def get_functest_config(parameter):
313 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
314 return get_parameter_from_yaml(parameter, yaml_)
317 def merge_dicts(dict1, dict2):
318 for k in set(dict1.keys()).union(dict2.keys()):
319 if k in dict1 and k in dict2:
320 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
321 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
330 def get_functest_yaml():
331 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
332 functest_yaml = yaml.safe_load(f)
337 def print_separator():
338 logger.info("==============================================")
342 """Measure the time it takes for a function to complete"""
343 @functools.wraps(func)
344 def timed(*args, **kwargs):
346 result = func(*args, **kwargs)
348 elapsed = '{0}'.format(te - ts)
349 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
350 f=func.__name__, a=args, kw=kwargs, t=elapsed))
351 return result, elapsed