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