Switch from CONST to CONF
[functest.git] / functest / utils / functest_utils.py
1 #!/usr/bin/env python
2 #
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
9
10 # pylint: disable=missing-docstring
11
12 from __future__ import print_function
13 import logging
14 import re
15 import shutil
16 import subprocess
17 import sys
18
19 import dns.resolver
20 from six.moves import urllib
21 import yaml
22
23 from functest.utils import constants
24 from functest.utils import env
25
26 LOGGER = logging.getLogger(__name__)
27
28
29 # ----------------------------------------------------------
30 #
31 #               INTERNET UTILS
32 #
33 # -----------------------------------------------------------
34 def check_internet_connectivity(url='http://www.opnfv.org/'):
35     """
36     Check if there is access to the internet
37     """
38     try:
39         urllib.request.urlopen(url, timeout=5)
40         return True
41     except urllib.error.URLError:
42         return False
43
44
45 def download_url(url, dest_path):
46     """
47     Download a file to a destination path given a URL
48     """
49     name = url.rsplit('/')[-1]
50     dest = dest_path + "/" + name
51     try:
52         response = urllib.request.urlopen(url)
53     except (urllib.error.HTTPError, urllib.error.URLError):
54         return False
55
56     with open(dest, 'wb') as lfile:
57         shutil.copyfileobj(response, lfile)
58     return True
59
60
61 # ----------------------------------------------------------
62 #
63 #               CI UTILS
64 #
65 # -----------------------------------------------------------
66 def get_resolvconf_ns():
67     """
68     Get nameservers from current resolv.conf
69     """
70     nameservers = []
71     rconf = open("/etc/resolv.conf", "r")
72     line = rconf.readline()
73     resolver = dns.resolver.Resolver()
74     while line:
75         addr_ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
76         if addr_ip:
77             resolver.nameservers = [addr_ip.group(0)]
78             try:
79                 result = resolver.query('opnfv.org')[0]
80                 if result != "":
81                     nameservers.append(addr_ip.group())
82             except dns.exception.Timeout:
83                 pass
84         line = rconf.readline()
85     return nameservers
86
87
88 def get_ci_envvars():
89     """
90     Get the CI env variables
91     """
92     ci_env_var = {
93         "installer": env.get('INSTALLER_TYPE'),
94         "scenario": env.get('DEPLOY_SCENARIO')}
95     return ci_env_var
96
97
98 def execute_command_raise(cmd, info=False, error_msg="",
99                           verbose=True, output_file=None):
100     ret = execute_command(cmd, info, error_msg, verbose, output_file)
101     if ret != 0:
102         raise Exception(error_msg)
103
104
105 def execute_command(cmd, info=False, error_msg="",
106                     verbose=True, output_file=None):
107     if not error_msg:
108         error_msg = ("The command '%s' failed." % cmd)
109     msg_exec = ("Executing command: '%s'" % cmd)
110     if verbose:
111         if info:
112             LOGGER.info(msg_exec)
113         else:
114             LOGGER.debug(msg_exec)
115     popen = subprocess.Popen(
116         cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
117     if output_file:
118         ofd = open(output_file, "w")
119     for line in iter(popen.stdout.readline, b''):
120         if output_file:
121             ofd.write(line)
122         else:
123             line = line.replace('\n', '')
124             print (line)
125             sys.stdout.flush()
126     if output_file:
127         ofd.close()
128     popen.stdout.close()
129     returncode = popen.wait()
130     if returncode != 0:
131         if verbose:
132             LOGGER.error(error_msg)
133
134     return returncode
135
136
137 # ----------------------------------------------------------
138 #
139 #               YAML UTILS
140 #
141 # -----------------------------------------------------------
142 def get_parameter_from_yaml(parameter, yfile):
143     """
144     Returns the value of a given parameter in file.yaml
145     parameter must be given in string format with dots
146     Example: general.openstack.image_name
147     """
148     with open(yfile) as yfd:
149         file_yaml = yaml.safe_load(yfd)
150     value = file_yaml
151     for element in parameter.split("."):
152         value = value.get(element)
153         if value is None:
154             raise ValueError("The parameter %s is not defined in"
155                              " %s" % (parameter, yfile))
156     return value
157
158
159 def get_functest_config(parameter):
160     yaml_ = constants.CONFIG_FUNCTEST_YAML
161     return get_parameter_from_yaml(parameter, yaml_)
162
163
164 def get_functest_yaml():
165     # pylint: disable=bad-continuation
166     with open(constants.CONFIG_FUNCTEST_YAML) as yaml_fd:
167         functest_yaml = yaml.safe_load(yaml_fd)
168     return functest_yaml
169
170
171 def print_separator():
172     LOGGER.info("==============================================")