Merge "update of the INFO file"
[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 IMAGE_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 #GLANCE image parameters
68 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
69 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
70 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
71 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
72 IMAGE_PATH = IMAGE_DIR + "/" + IMAGE_FILE_NAME
73
74
75 def action_start():
76     """
77     Start the functest environment installation
78     """
79     if not functest_utils.check_internet_connectivity():
80         logger.error("There is no Internet connectivity. Please check the network configuration.")
81         exit(-1)
82
83     if action_check():
84         logger.info("Functest environment already installed. Nothing to do.")
85         exit(0)
86
87     else:
88         # Clean in case there are left overs
89         logger.debug("Cleaning possible functest environment leftovers.")
90         action_clean()
91
92
93         logger.info("Installing ODL environment...")
94         if not install_odl():
95             logger.error("There has been a problem while installing Robot.")
96             action_clean()
97             exit(-1)
98
99         logger.info("Starting installation of functest environment")
100         logger.info("Installing Rally...")
101         if not install_rally():
102             logger.error("There has been a problem while installing Rally.")
103             action_clean()
104             exit(-1)
105
106         logger.info("Configuring Tempest...")
107         if not configure_tempest():
108             logger.error("There has been a problem while configuring Tempest.")
109             action_clean()
110             exit(-1)
111
112         # Create result folder under functest if necessary
113         if not os.path.exists(RALLY_RESULT_DIR):
114             os.makedirs(RALLY_RESULT_DIR)
115
116         logger.info("Downloading image...")
117         if not functest_utils.download_url(IMAGE_URL, IMAGE_DIR):
118             logger.error("There has been a problem downloading the image '%s'." %IMAGE_URL)
119             action_clean()
120             exit(-1)
121
122         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
123         if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
124             logger.error("There has been a problem while creating the Glance image.")
125             action_clean()
126             exit(-1)
127
128         exit(0)
129
130
131 def action_check():
132     """
133     Check if the functest environment is properly installed
134     """
135     errors_all = False
136     errors = False
137     logger.info("Checking current functest configuration...")
138
139     logger.debug("Checking script directories...")
140
141     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
142     for dir in dirs:
143         if not os.path.exists(dir):
144             logger.debug("The directory '%s' does NOT exist." % dir)
145             errors = True
146             errors_all = True
147         else:
148             logger.debug("   %s found" % dir)
149     if not errors:
150         logger.debug("...OK")
151     else:
152         logger.debug("...FAIL")
153
154
155     logger.debug("Checking Rally deployment...")
156     if not check_rally():
157         logger.debug("   Rally deployment NOT installed.")
158         errors_all = True
159         logger.debug("...FAIL")
160     else:
161         logger.debug("...OK")
162
163     logger.debug("Checking Image...")
164     errors = False
165     if not os.path.isfile(IMAGE_PATH):
166         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
167         errors = True
168         errors_all = True
169     else:
170         logger.debug("   Image file found in %s" % IMAGE_PATH)
171
172     cmd="glance image-list | grep " + IMAGE_NAME
173     FNULL = open(os.devnull, 'w');
174     logger.debug('   Executing command : {}'.format(cmd))
175     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
176     #if the command does not exist or there is no glance image
177     line = p.stdout.readline()
178     if line == "":
179         logger.debug("   Glance image NOT found.")
180         errors = True
181         errors_all = True
182     else:
183         logger.debug("   Glance image found.")
184
185     if not errors:
186         logger.debug("...OK")
187     else:
188         logger.debug("...FAIL")
189
190     #TODO: check OLD environment setup
191     return not errors_all
192
193
194
195 def action_clean():
196     """
197     Clean the existing functest environment
198     """
199     logger.info("Removing current functest environment...")
200     if os.path.exists(RALLY_INSTALLATION_DIR):
201         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
202         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
203
204     if os.path.exists(IMAGE_PATH):
205         logger.debug("Deleting image")
206         os.remove(IMAGE_PATH)
207
208     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
209     p = os.popen(cmd,"r")
210
211     #while image_id = p.readline()
212     for image_id in p.readlines():
213         cmd = "glance image-delete " + image_id
214         functest_utils.execute_command(cmd,logger)
215
216     if os.path.exists(RALLY_RESULT_DIR):
217         logger.debug("Removing Result directory")
218         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
219
220
221     logger.info("Functest environment clean!")
222
223
224
225 def install_rally():
226     if check_rally():
227         logger.info("Rally is already installed.")
228     else:
229         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
230         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
231         cmd = 'sudo ' + install_script
232         functest_utils.execute_command(cmd,logger)
233
234         logger.debug("Creating Rally environment...")
235         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
236         functest_utils.execute_command(cmd,logger)
237
238         logger.debug("Installing tempest...")
239         cmd = "rally verify install"
240         functest_utils.execute_command(cmd,logger)
241
242         cmd = "rally deployment check"
243         functest_utils.execute_command(cmd,logger)
244         #TODO: check that everything is 'Available' and warn if not
245
246         cmd = "rally show images"
247         functest_utils.execute_command(cmd,logger)
248
249         cmd = "rally show flavors"
250         functest_utils.execute_command(cmd,logger)
251
252     return True
253
254
255 def configure_tempest():
256     """
257     Add/update needed parameters into tempest.conf file generated by Rally
258     """
259
260     creds_neutron = functest_utils.get_credentials("neutron")
261     neutron_client = neutronclient.Client(**creds_neutron)
262
263     logger.debug("Generating tempest.conf file...")
264     cmd = "rally verify genconfig"
265     functest_utils.execute_command(cmd,logger)
266
267     logger.debug("Resolving deployment UUID...")
268     cmd = "rally deployment list | awk '/"+DEPLOYMENT_MAME+"/ {print $2}'"
269     p = subprocess.Popen(cmd, shell=True,
270                          stdout=subprocess.PIPE,
271                          stderr=subprocess.STDOUT);
272     deployment_uuid = p.stdout.readline().rstrip()
273     if deployment_uuid == "":
274         logger.debug("   Rally deployment NOT found")
275         return False
276
277     logger.debug("Finding tempest.conf file...")
278     tempest_conf_file = RALLY_INSTALLATION_DIR+"/tempest/for-deployment-" \
279                         +deployment_uuid+"/tempest.conf"
280
281     logger.debug("  Updating fixed_network_name...")
282     fixed_network = functest_utils.get_network_list(neutron_client)[0]['name']
283     if fixed_network != None:
284         cmd = "crudini --set "+tempest_conf_file+" compute fixed_network_name "+fixed_network
285         functest_utils.execute_command(cmd,logger)
286
287     return True
288
289
290 def check_rally():
291     """
292     Check if Rally is installed and properly configured
293     """
294     if os.path.exists(RALLY_INSTALLATION_DIR):
295         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
296         FNULL = open(os.devnull, 'w');
297         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
298         logger.debug('   Executing command : {}'.format(cmd))
299         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
300         #if the command does not exist or there is no deployment
301         line = p.stdout.readline()
302         if line == "":
303             logger.debug("   Rally deployment NOT found")
304             return False
305         logger.debug("   Rally deployment found")
306         return True
307     else:
308         return False
309
310
311 def install_odl():
312     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
313     functest_utils.execute_command(cmd,logger)
314     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
315     functest_utils.execute_command(cmd,logger)
316     cmd = ODL_DIR + "create_venv.sh"
317     functest_utils.execute_command(cmd,logger)
318     return True
319
320
321
322 def create_glance_image(path,name,disk_format):
323     """
324     Create a glance image given the absolute path of the image, its name and the disk format
325     """
326     cmd = ("glance image-create --name "+name+"  --visibility public "
327     "--disk-format "+disk_format+" --container-format bare --file "+path)
328     functest_utils.execute_command(cmd,logger)
329     return True
330
331
332
333
334 def main():
335     if not (args.action in actions):
336         logger.error('argument not valid')
337         exit(-1)
338
339
340     if not functest_utils.check_credentials():
341         logger.error("Please source the openrc credentials and run the script again.")
342         #TODO: source the credentials in this script
343         exit(-1)
344
345     if args.action == "start":
346         action_start()
347
348     if args.action == "check":
349         if action_check():
350             logger.info("Functest environment correctly installed")
351         else:
352             logger.info("Functest environment not found or faulty")
353
354     if args.action == "clean":
355         if args.force :
356             action_clean()
357         else :
358             while True:
359                 print("Are you sure? [y|n]")
360                 answer = raw_input("")
361                 if answer == "y":
362                     action_clean()
363                     break
364                 elif answer == "n":
365                     break
366                 else:
367                     print("Invalid option.")
368     exit(0)
369
370
371 if __name__ == '__main__':
372     main()
373