Create a private shared network for Rally
[functest.git] / 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
11 import json
12 import os
13 import os.path
14 import re
15 import requests
16 import shutil
17 import socket
18 import subprocess
19 import sys
20 import urllib2
21 from git import Repo
22
23
24 # ----------------------------------------------------------
25 #
26 #               INTERNET UTILS
27 #
28 # -----------------------------------------------------------
29 def check_internet_connectivity(url='http://www.opnfv.org/'):
30     """
31     Check if there is access to the internet
32     """
33     try:
34         urllib2.urlopen(url, timeout=5)
35         return True
36     except urllib2.URLError:
37         return False
38
39
40 def download_url(url, dest_path):
41     """
42     Download a file to a destination path given a URL
43     """
44     name = url.rsplit('/')[-1]
45     dest = dest_path + "/" + name
46     try:
47         response = urllib2.urlopen(url)
48     except (urllib2.HTTPError, urllib2.URLError):
49         return False
50
51     with open(dest, 'wb') as f:
52         shutil.copyfileobj(response, f)
53     return True
54
55
56 # ----------------------------------------------------------
57 #
58 #               CI UTILS
59 #
60 # -----------------------------------------------------------
61 def get_git_branch(repo_path):
62     """
63     Get git branch name
64     """
65     repo = Repo(repo_path)
66     branch = repo.active_branch
67     return branch.name
68
69
70 def get_installer_type(logger=None):
71     """
72     Get installer type (fuel, apex, joid, compass)
73     """
74     try:
75         installer = os.environ['INSTALLER_TYPE']
76     except KeyError:
77         if logger:
78             logger.error("Impossible to retrieve the installer type")
79         installer = "Unknown_installer"
80
81     return installer
82
83
84 def get_scenario(logger=None):
85     """
86     Get scenario
87     """
88     try:
89         scenario = os.environ['DEPLOY_SCENARIO']
90     except KeyError:
91         if logger:
92             logger.error("Impossible to retrieve the scenario")
93         scenario = "Unknown_scenario"
94
95     return scenario
96
97
98 def get_version(logger=None):
99     """
100     Get version
101     """
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     # use regex to match branch info
108     rule = "daily-(.+?)-[0-9]*"
109     build_tag = get_build_tag(logger)
110     m = re.search(rule, build_tag)
111     if m:
112         return m.group(1)
113     else:
114         return "unknown"
115
116
117 def get_pod_name(logger=None):
118     """
119     Get PoD Name from env variable NODE_NAME
120     """
121     try:
122         return os.environ['NODE_NAME']
123     except KeyError:
124         if logger:
125             logger.error(
126                 "Unable to retrieve the POD name from environment. " +
127                 "Using pod name 'unknown-pod'")
128         return "unknown-pod"
129
130
131 def get_build_tag(logger=None):
132     """
133     Get build tag of jenkins jobs
134     """
135     try:
136         build_tag = os.environ['BUILD_TAG']
137     except KeyError:
138         if logger:
139             logger.error("Impossible to retrieve the build tag")
140         build_tag = "unknown_build_tag"
141
142     return build_tag
143
144
145 def push_results_to_db(db_url, project, case_name, logger, pod_name,
146                        version, scenario, criteria, build_tag, payload):
147     """
148     POST results to the Result target DB
149     """
150     url = db_url + "/results"
151     installer = get_installer_type(logger)
152     params = {"project_name": project, "case_name": case_name,
153               "pod_name": pod_name, "installer": installer,
154               "version": version, "scenario": scenario, "criteria": criteria,
155               "build_tag": build_tag, "details": payload}
156
157     headers = {'Content-Type': 'application/json'}
158     try:
159         r = requests.post(url, data=json.dumps(params), headers=headers)
160         if logger:
161             logger.debug(r)
162         return True
163     except Exception, e:
164         print ("Error [push_results_to_db('%s', '%s', '%s', " +
165                "'%s', '%s', '%s', '%s', '%s', '%s')]:" %
166                (db_url, project, case_name, pod_name, version,
167                 scenario, criteria, build_tag, payload), e)
168         return False
169
170
171 def get_resolvconf_ns():
172     """
173     Get nameservers from current resolv.conf
174     """
175     nameservers = []
176     rconf = open("/etc/resolv.conf", "r")
177     line = rconf.readline()
178     while line:
179         ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", line)
180         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
181         if ip:
182             result = sock.connect_ex((ip.group(), 53))
183             if result == 0:
184                 nameservers.append(ip.group())
185         line = rconf.readline()
186     return nameservers
187
188
189 def get_ci_envvars():
190     """
191     Get the CI env variables
192     """
193     ci_env_var = {
194         "installer": os.environ.get('INSTALLER_TYPE'),
195         "scenario": os.environ.get('DEPLOY_SCENARIO')}
196     return ci_env_var
197
198
199 def execute_command(cmd, logger=None,
200                     exit_on_error=True,
201                     info=False,
202                     error_msg="",
203                     verbose=True):
204     if not error_msg:
205         error_msg = ("The command '%s' failed." % cmd)
206     msg_exec = ("Executing command: '%s'" % cmd)
207     if verbose:
208         if logger:
209             if info:
210                 logger.info(msg_exec)
211             else:
212                 logger.debug(msg_exec)
213         else:
214             print(msg_exec)
215     p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
216     while p.poll() is None:
217         line = p.stdout.readline().rstrip()
218         if verbose:
219             if logger:
220                 if info:
221                     logger.info(line)
222                 else:
223                     logger.debug(line)
224             else:
225                 print line
226     if p.returncode != 0:
227         if verbose:
228             if logger:
229                 logger.error(error_msg)
230             else:
231                 print(error_msg)
232         if exit_on_error:
233             sys.exit(1)
234
235     return p.returncode