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 @decorators.can_dump_request_to_file
94 def push_results_to_db(project, case_name,
95 start_date, stop_date, result, details):
97 POST results to the Result target DB
99 # Retrieve params from CI and conf
100 if (hasattr(CONST, 'TEST_DB_URL')):
101 url = CONST.__getattribute__('TEST_DB_URL')
103 url = CONST.__getattribute__("results_test_db_url")
106 installer = os.environ['INSTALLER_TYPE']
107 scenario = os.environ['DEPLOY_SCENARIO']
108 pod_name = os.environ['NODE_NAME']
109 build_tag = os.environ['BUILD_TAG']
110 except KeyError as e:
111 logger.error("Please set env var: " + str(e))
113 version = get_version()
114 test_start = dt.fromtimestamp(start_date).strftime('%Y-%m-%d %H:%M:%S')
115 test_stop = dt.fromtimestamp(stop_date).strftime('%Y-%m-%d %H:%M:%S')
117 params = {"project_name": project, "case_name": case_name,
118 "pod_name": pod_name, "installer": installer,
119 "version": version, "scenario": scenario, "criteria": result,
120 "build_tag": build_tag, "start_date": test_start,
121 "stop_date": test_stop, "details": details}
124 headers = {'Content-Type': 'application/json'}
126 r = requests.post(url, data=json.dumps(params, sort_keys=True),
130 except requests.RequestException as exc:
132 error = ("Pushing Result to DB(%s) failed: %s" %
135 error = ("Pushing Result to DB(%s) failed: %s" % (url, exc))
136 except Exception as e:
137 error = ("Error [push_results_to_db("
139 "project: '%(project)s', "
143 "scenario: '%(s)s', "
144 "criteria: '%(c)s', "
145 "build_tag: '%(t)s', "
146 "details: '%(d)s')]: "
167 def get_resolvconf_ns():
169 Get nameservers from current resolv.conf
172 rconf = open("/etc/resolv.conf", "r")
173 line = rconf.readline()
174 resolver = dns.resolver.Resolver()
176 ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
178 resolver.nameservers = [ip.group(0)]
180 result = resolver.query('opnfv.org')[0]
182 nameservers.append(ip.group())
183 except dns.exception.Timeout:
185 line = rconf.readline()
189 def get_ci_envvars():
191 Get the CI env variables
194 "installer": os.environ.get('INSTALLER_TYPE'),
195 "scenario": os.environ.get('DEPLOY_SCENARIO')}
199 def execute_command_raise(cmd, info=False, error_msg="",
200 verbose=True, output_file=None):
201 ret = execute_command(cmd, info, error_msg, verbose, output_file)
203 raise Exception(error_msg)
206 def execute_command(cmd, info=False, error_msg="",
207 verbose=True, output_file=None):
209 error_msg = ("The command '%s' failed." % cmd)
210 msg_exec = ("Executing command: '%s'" % cmd)
213 logger.info(msg_exec)
215 logger.debug(msg_exec)
216 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
217 stderr=subprocess.STDOUT)
219 f = open(output_file, "w")
220 for line in iter(p.stdout.readline, b''):
224 line = line.replace('\n', '')
230 returncode = p.wait()
233 logger.error(error_msg)
238 def get_dict_by_test(testname):
239 with open(pkg_resources.resource_filename(
240 'functest', 'ci/testcases.yaml')) as f:
241 testcases_yaml = yaml.safe_load(f)
243 for dic_tier in testcases_yaml.get("tiers"):
244 for dic_testcase in dic_tier['testcases']:
245 if dic_testcase['case_name'] == testname:
248 logger.error('Project %s is not defined in testcases.yaml' % testname)
252 def get_criteria_by_test(testname):
253 dict = get_dict_by_test(testname)
255 return dict['criteria']
259 # ----------------------------------------------------------
263 # -----------------------------------------------------------
264 def get_parameter_from_yaml(parameter, file):
266 Returns the value of a given parameter in file.yaml
267 parameter must be given in string format with dots
268 Example: general.openstack.image_name
270 with open(file) as f:
271 file_yaml = yaml.safe_load(f)
274 for element in parameter.split("."):
275 value = value.get(element)
277 raise ValueError("The parameter %s is not defined in"
278 " %s" % (parameter, file))
282 def get_functest_config(parameter):
283 yaml_ = constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')
284 return get_parameter_from_yaml(parameter, yaml_)
287 def get_functest_yaml():
288 with open(constants.CONST.__getattribute__('CONFIG_FUNCTEST_YAML')) as f:
289 functest_yaml = yaml.safe_load(f)
294 def print_separator():
295 logger.info("==============================================")
299 """Measure the time it takes for a function to complete"""
300 @functools.wraps(func)
301 def timed(*args, **kwargs):
303 result = func(*args, **kwargs)
305 elapsed = '{0}'.format(te - ts)
306 logger.info('{f}(*{a}, **{kw}) took: {t} sec'.format(
307 f=func.__name__, a=args, kw=kwargs, t=elapsed))
308 return result, elapsed