Change default order of tests
[functest.git] / testcases / config_functest.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2015 Ericsson
4 # jose.lausuch@ericsson.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 re, json, os, urllib2, argparse, logging, shutil, subprocess, yaml, sys, getpass
12 import functest_utils
13 from git import Repo
14 from os import stat
15 from pwd import getpwuid
16 from neutronclient.v2_0 import client as neutronclient
17
18 actions = ['start', 'check', 'clean']
19 parser = argparse.ArgumentParser()
20 parser.add_argument("repo_path", help="Path to the repository")
21 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
22 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
23 parser.add_argument("-f", "--force", help="Force",  action="store_true")
24 args = parser.parse_args()
25
26
27 """ logging configuration """
28 logger = logging.getLogger('config_functest')
29 logger.setLevel(logging.DEBUG)
30
31 ch = logging.StreamHandler()
32 if args.debug:
33     ch.setLevel(logging.DEBUG)
34 else:
35     ch.setLevel(logging.INFO)
36
37 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
38 ch.setFormatter(formatter)
39 logger.addHandler(ch)
40
41 if not os.path.exists(args.repo_path):
42     logger.error("Repo directory not found '%s'" % args.repo_path)
43     exit(-1)
44
45 with open(args.repo_path+"testcases/config_functest.yaml") as f:
46     functest_yaml = yaml.safe_load(f)
47 f.close()
48
49
50
51
52 """ global variables """
53 # Directories
54 REPO_PATH = args.repo_path
55 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
56 RALLY_REPO_DIR = functest_yaml.get("general").get("directories").get("dir_repo_rally")
57 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get("dir_rally_inst")
58 RALLY_RESULT_DIR = functest_yaml.get("general").get("directories").get("dir_rally_res")
59 VPING_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_vping")
60 ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
61 DATA_DIR = functest_yaml.get("general").get("directories").get("dir_functest_data")
62
63 # Tempest/Rally configuration details
64 DEPLOYMENT_MAME = "opnfv-rally"
65 RALLY_COMMIT = functest_yaml.get("general").get("openstack").get("rally_stable_commit")
66
67 #Image (cirros)
68 IMAGE_FILE_NAME = functest_yaml.get("general").get("openstack").get("image_file_name")
69 IMAGE_PATH = DATA_DIR + "/" + IMAGE_FILE_NAME
70
71
72 def action_start():
73     """
74     Start the functest environment installation
75     """
76     if not functest_utils.check_internet_connectivity():
77         logger.error("There is no Internet connectivity. Please check the network configuration.")
78         exit(-1)
79
80     if action_check():
81         logger.info("Functest environment already installed. Nothing to do.")
82         exit(0)
83
84     else:
85         # Clean in case there are left overs
86         logger.debug("Cleaning possible functest environment leftovers.")
87         action_clean()
88
89         logger.info("Starting installation of functest environment")
90         logger.info("Installing Rally...")
91         if not install_rally():
92             logger.error("There has been a problem while installing Rally.")
93             action_clean()
94             exit(-1)
95
96         logger.info("Configuring Tempest...")
97         if not configure_tempest():
98             logger.error("There has been a problem while configuring Tempest.")
99             action_clean()
100             exit(-1)
101
102         # Create result folder under functest if necessary
103         if not os.path.exists(RALLY_RESULT_DIR):
104             os.makedirs(RALLY_RESULT_DIR)
105
106         exit(0)
107
108
109 def action_check():
110     """
111     Check if the functest environment is properly installed
112     """
113     errors_all = False
114     errors = False
115     logger.info("Checking current functest configuration...")
116
117     logger.debug("Checking script directories...")
118
119     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
120     for dir in dirs:
121         if not os.path.exists(dir):
122             logger.debug("The directory '%s' does NOT exist." % dir)
123             errors = True
124             errors_all = True
125         else:
126             logger.debug("   %s found" % dir)
127     if not errors:
128         logger.debug("...OK")
129     else:
130         logger.debug("...FAIL")
131
132
133     logger.debug("Checking Rally deployment...")
134     if not check_rally():
135         logger.debug("   Rally deployment NOT installed.")
136         errors_all = True
137         logger.debug("...FAIL")
138     else:
139         logger.debug("...OK")
140
141     logger.debug("Checking Image...")
142     errors = False
143     if not os.path.isfile(IMAGE_PATH):
144         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
145         errors = True
146         errors_all = True
147     else:
148         logger.debug("   Image file found in %s" % IMAGE_PATH)
149
150
151     if not errors:
152         logger.debug("...OK")
153     else:
154         logger.debug("...FAIL")
155
156     #TODO: check OLD environment setup
157     return not errors_all
158
159
160
161 def action_clean():
162     """
163     Clean the existing functest environment
164     """
165     logger.info("Removing current functest environment...")
166     if os.path.exists(RALLY_INSTALLATION_DIR):
167         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
168         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
169
170     if os.path.exists(RALLY_RESULT_DIR):
171         logger.debug("Removing Result directory")
172         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
173
174
175     logger.info("Functest environment clean!")
176
177
178
179 def install_rally():
180     if check_rally():
181         logger.info("Rally is already installed.")
182     else:
183         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
184         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
185         cmd = 'sudo ' + install_script
186         functest_utils.execute_command(cmd,logger)
187
188         logger.debug("Creating Rally environment...")
189         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
190         functest_utils.execute_command(cmd,logger)
191
192         logger.debug("Installing tempest...")
193         cmd = "rally verify install"
194         functest_utils.execute_command(cmd,logger)
195
196         cmd = "rally deployment check"
197         functest_utils.execute_command(cmd,logger)
198         #TODO: check that everything is 'Available' and warn if not
199
200         cmd = "rally show images"
201         functest_utils.execute_command(cmd,logger)
202
203         cmd = "rally show flavors"
204         functest_utils.execute_command(cmd,logger)
205
206     return True
207
208
209 def configure_tempest():
210     """
211     Add/update needed parameters into tempest.conf file generated by Rally
212     """
213
214     creds_neutron = functest_utils.get_credentials("neutron")
215     neutron_client = neutronclient.Client(**creds_neutron)
216
217     logger.debug("Generating tempest.conf file...")
218     cmd = "rally verify genconfig"
219     functest_utils.execute_command(cmd,logger)
220
221     logger.debug("Resolving deployment UUID...")
222     cmd = "rally deployment list | awk '/"+DEPLOYMENT_MAME+"/ {print $2}'"
223     p = subprocess.Popen(cmd, shell=True,
224                          stdout=subprocess.PIPE,
225                          stderr=subprocess.STDOUT);
226     deployment_uuid = p.stdout.readline().rstrip()
227     if deployment_uuid == "":
228         logger.debug("   Rally deployment NOT found")
229         return False
230
231     logger.debug("Finding tempest.conf file...")
232     tempest_conf_file = RALLY_INSTALLATION_DIR+"/tempest/for-deployment-" \
233                         +deployment_uuid+"/tempest.conf"
234
235     logger.debug("  Updating fixed_network_name...")
236     fixed_network = functest_utils.get_network_list(neutron_client)[0]['name']
237     if fixed_network != None:
238         cmd = "crudini --set "+tempest_conf_file+" compute fixed_network_name "+fixed_network
239         functest_utils.execute_command(cmd,logger)
240
241     return True
242
243
244 def check_rally():
245     """
246     Check if Rally is installed and properly configured
247     """
248     if os.path.exists(RALLY_INSTALLATION_DIR):
249         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
250         FNULL = open(os.devnull, 'w');
251         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
252         logger.debug('   Executing command : {}'.format(cmd))
253         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
254         #if the command does not exist or there is no deployment
255         line = p.stdout.readline()
256         if line == "":
257             logger.debug("   Rally deployment NOT found")
258             return False
259         logger.debug("   Rally deployment found")
260         return True
261     else:
262         return False
263
264
265 def main():
266     if not (args.action in actions):
267         logger.error('argument not valid')
268         exit(-1)
269
270
271     if not functest_utils.check_credentials():
272         logger.error("Please source the openrc credentials and run the script again.")
273         #TODO: source the credentials in this script
274         exit(-1)
275
276     if args.action == "start":
277         action_start()
278
279     if args.action == "check":
280         if action_check():
281             logger.info("Functest environment correctly installed")
282         else:
283             logger.info("Functest environment not found or faulty")
284
285     if args.action == "clean":
286         if args.force :
287             action_clean()
288         else :
289             while True:
290                 print("Are you sure? [y|n]")
291                 answer = raw_input("")
292                 if answer == "y":
293                     action_clean()
294                     break
295                 elif answer == "n":
296                     break
297                 else:
298                     print("Invalid option.")
299     exit(0)
300
301
302 if __name__ == '__main__':
303     main()
304