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 # -----------------------------------------------------------
71 def get_installer_type():
73 Get installer type (fuel, apex, joid, compass)
76 installer = os.environ['INSTALLER_TYPE']
78 logger.error("Impossible to retrieve the installer type")
79 installer = "Unknown_installer"
89 scenario = os.environ['DEPLOY_SCENARIO']
91 logger.info("Impossible to retrieve the scenario."
92 "Use default os-nosdn-nofeature-noha")
93 scenario = "os-nosdn-nofeature-noha"
102 # Use the build tag to retrieve the version
103 # By default version is unknown
104 # if launched through CI the build tag has the following format
105 # jenkins-<project>-<installer>-<pod>-<job>-<branch>-<id>
106 # e.g. jenkins-functest-fuel-opnfv-jump-2-daily-master-190
107 # jenkins-functest-fuel-baremetal-weekly-master-8
108 # use regex to match branch info
109 rule = "(dai|week)ly-(.+?)-[0-9]*"
110 build_tag = get_build_tag()
111 m = re.search(rule, build_tag)
120 Get PoD Name from env variable NODE_NAME
123 return os.environ['NODE_NAME']
126 "Unable to retrieve the POD name from environment. " +
127 "Using pod name 'unknown-pod'")
133 Get build tag of jenkins jobs
136 build_tag = os.environ['BUILD_TAG']
138 logger.info("Impossible to retrieve the build tag")
144 def logger_test_results(project, case_name, status, details):
146 Format test case results for the logger
148 pod_name = get_pod_name()
149 scenario = get_scenario()
150 version = get_version()
151 build_tag = get_build_tag()
152 db_url = CONST.__getattribute__("results_test_db_url")
156 "****************************************\n"
157 "\t %(p)s/%(n)s results \n\n"
158 "****************************************\n"
164 "build tag:\t%(b)s\n"
177 @decorators.can_dump_request_to_file
178 def push_results_to_db(project, case_name,
179 start_date, stop_date, result, details):
181 POST results to the Result target DB
183 # Retrieve params from CI and conf
184 url = CONST.__getattribute__("results_test_db_url")
187 installer = os.environ['INSTALLER_TYPE']
188 scenario = os.environ['DEPLOY_SCENARIO']
189 pod_name = os.environ['NODE_NAME']
190 build_tag = os.environ['BUILD_TAG']
191 except KeyError as e:
192 logger.error("Please set env var: " + str(e))
194 version = get_version()
195 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
196 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
198 params = {"project_name": project, "case_name": case_name,
199 "pod_name": pod_name, "installer": installer,
200 "version": version, "scenario": scenario, "criteria": result,
201 "build_tag": build_tag, "start_date": test_start,
202 "stop_date": test_stop, "details": details}
205 headers = {'Content-Type': 'application/json'}
207 r = requests.post(url, data=json.dumps(params, sort_keys=True),
211 except requests.RequestException as exc:
213 error = ("Pushing Result to DB(%s) failed: %s" %
216 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
217 except Exception as e:
218 error = ("Error [push_results_to_db("
220 "project: '%(project)s', "
224 "scenario: '%(s)s', "
225 "criteria: '%(c)s', "
226 "build_tag: '%(t)s', "
227 "details: '%(d)s')]: "
248 def get_resolvconf_ns():
250 Get nameservers from current resolv.conf
253 rconf = open("/etc/resolv.conf", "r")
254 line = rconf.readline()
255 resolver = dns.resolver.Resolver()
257 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
259 resolver.nameservers = [ip.group(0)]
261 result = resolver.query('opnfv.org')[0]
263 nameservers.append(ip.group())
264 except dns.exception.Timeout:
266 line = rconf.readline()
270 def get_ci_envvars():
272 Get the CI env variables
275 "installer": os.environ.get('INSTALLER_TYPE'),
276 "scenario": os.environ.get('DEPLOY_SCENARIO')}
280 def execute_command_raise(cmd, info=False, error_msg="",
281 verbose=True, output_file=None):
282 ret = execute_command(cmd, info, error_msg, verbose, output_file)
284 raise Exception(error_msg)
287 def execute_command(cmd, info=False, error_msg="",
288 verbose=True, output_file=None):
290 error_msg = ("The command '%s' failed." % cmd)
291 msg_exec = ("Executing command: '%s'" % cmd)
294 logger.info(msg_exec)
296 logger.debug(msg_exec)
297 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
298 stderr=subprocess.STDOUT)
300 f = open(output_file, "w")
301 for line in iter(p.stdout.readline, b''):
305 line = line.replace('\n', '')
311 returncode = p.wait()
314 logger.error(error_msg)
319 def get_dict_by_test(testname):
320 with open(pkg_resources.resource_filename(
321 'functest', 'ci/testcases.yaml')) as f:
322 testcases_yaml = yaml.safe_load(f)
324 for dic_tier in testcases_yaml.get("tiers"):
325 for dic_testcase in dic_tier['testcases']:
326 if dic_testcase['case_name'] == testname:
329 logger.error('Project %s is not defined in testcases.yaml' % testname)
333 def get_criteria_by_test(testname):
334 dict = get_dict_by_test(testname)
336 return dict['criteria']
340 # ----------------------------------------------------------
344 # -----------------------------------------------------------
345 def get_parameter_from_yaml(parameter, file):
347 Returns the value of a given parameter in file.yaml
348 parameter must be given in string format with dots
349 Example: general.openstack.image_name
351 with open(file) as f:
352 file_yaml = yaml.safe_load(f)
355 for element in parameter.split("."):
356 value = value.get(element)
358 raise ValueError("The parameter %s is not defined in"
359 " %s" % (parameter, file))
363 def get_functest_config(parameter):
364 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
365 return get_parameter_from_yaml(parameter, yaml_)
368 def merge_dicts(dict1, dict2):
369 for k in set(dict1.keys()).union(dict2.keys()):
370 if k in dict1 and k in dict2:
371 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
372 yield (k, dict(merge_dicts(dict1[k], dict2[k])))
381 def get_functest_yaml():
382 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
383 functest_yaml = yaml.safe_load(f)
388 def print_separator():
389 logger.info("==============================================")
393 """Measure the time it takes for a function to complete"""
394 @functools.wraps(func)
395 def timed(*args, **kwargs):
397 result = func(*args, **kwargs)
399 elapsed = '{0}'.format(te - ts)
400 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
401 f=func.__name__, a=args, kw=kwargs, t=elapsed))
402 return result, elapsed