Adapt installation of Tempest from rally with new command line
[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
17 actions = ['start', 'check', 'clean']
18 parser = argparse.ArgumentParser()
19 parser.add_argument("repo_path", help="Path to the repository")
20 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
21 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
22 parser.add_argument("-f", "--force", help="Force",  action="store_true")
23 args = parser.parse_args()
24
25
26 """ logging configuration """
27 logger = logging.getLogger('config_functest')
28 logger.setLevel(logging.DEBUG)
29
30 ch = logging.StreamHandler()
31 if args.debug:
32     ch.setLevel(logging.DEBUG)
33 else:
34     ch.setLevel(logging.INFO)
35
36 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
37 ch.setFormatter(formatter)
38 logger.addHandler(ch)
39
40 if not os.path.exists(args.repo_path):
41     logger.error("Repo directory not found '%s'" % args.repo_path)
42     exit(-1)
43
44 with open(args.repo_path+"testcases/config_functest.yaml") as f:
45     functest_yaml = yaml.safe_load(f)
46 f.close()
47
48
49
50
51 """ global variables """
52 # Directories
53 HOME = os.environ['HOME']+"/"
54 REPO_PATH = args.repo_path
55 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
56 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
57 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
58 RALLY_RESULT_DIR = HOME + 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
62
63 #GLANCE image parameters
64 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
65 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
66 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
67 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
68 IMAGE_DIR = HOME + functest_yaml.get("general").get("openstack").get("image_download_path")
69 IMAGE_PATH = IMAGE_DIR + IMAGE_FILE_NAME
70
71
72 def action_start():
73     """
74     Start the functest environment installation
75     """
76     if not check_permissions():
77         logger.error("Bad Python cache directory ownership.")
78         exit(-1)
79
80     if not functest_utils.check_internet_connectivity():
81         logger.error("There is no Internet connectivity. Please check the network configuration.")
82         exit(-1)
83
84     if action_check():
85         logger.info("Functest environment already installed. Nothing to do.")
86         exit(0)
87
88     else:
89         # Clean in case there are left overs
90         logger.debug("Cleaning possible functest environment leftovers.")
91         action_clean()
92
93         logger.info("Installing needed libraries on the host")
94         cmd = "sudo yum -y install gcc libffi-devel python-devel openssl-devel gmp-devel libxml2-devel libxslt-devel postgresql-devel git wget"
95         if not functest_utils.execute_command(cmd, logger):
96             logger.error("There has been a problem while installing software packages.")
97             exit(-1)
98
99         logger.info("Installing ODL environment...")
100         if not install_odl():
101             logger.error("There has been a problem while installing Robot.")
102             action_clean()
103             exit(-1)
104
105         logger.info("Starting installation of functest environment")
106         logger.info("Installing Rally...")
107         if not install_rally():
108             logger.error("There has been a problem while installing Rally.")
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
137     logger.info("Checking current functest configuration...")
138
139     logger.debug("Checking script directories...")
140     errors = False
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     if errors_all:
192         return False
193     else:
194         return True
195
196
197
198
199 def action_clean():
200     """
201     Clean the existing functest environment
202     """
203     logger.info("Removing current functest environment...")
204     if os.path.exists(RALLY_INSTALLATION_DIR):
205         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
206         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
207
208     if os.path.exists(RALLY_REPO_DIR):
209         logger.debug("Removing Rally repository %s" % RALLY_REPO_DIR)
210         cmd = "sudo rm -rf " + RALLY_REPO_DIR #need to be sudo, not possible with rmtree
211         functest_utils.execute_command(cmd,logger)
212
213     if os.path.exists(IMAGE_PATH):
214         logger.debug("Deleting image")
215         os.remove(IMAGE_PATH)
216
217     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
218     p = os.popen(cmd,"r")
219
220     #while image_id = p.readline()
221     for image_id in p.readlines():
222         cmd = "glance image-delete " + image_id
223         functest_utils.execute_command(cmd,logger)
224
225     if os.path.exists(RALLY_RESULT_DIR):
226         logger.debug("Removing Result directory")
227         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
228
229
230     logger.info("Functest environment clean!")
231
232
233
234 def check_permissions():
235     current_user = getpass.getuser()
236     cache_dir = HOME+".cache/pip"
237     logger.info("Checking permissions of '%s'..." %cache_dir)
238     logger.debug("Current user is '%s'" %current_user)
239     cache_user = getpwuid(stat(cache_dir).st_uid).pw_name
240     logger.debug("Cache directory owner is '%s'" %cache_user)
241     if cache_user != current_user:
242         logger.info("The owner of '%s' is '%s'. Please run 'sudo chown -R %s %s'." %(cache_dir, cache_user, current_user, cache_dir))
243         return False
244
245     return True
246
247
248 def install_rally():
249     if check_rally():
250         logger.info("Rally is already installed.")
251     else:
252         logger.debug("Cloning repository...")
253         url = "https://git.openstack.org/openstack/rally"
254         Repo.clone_from(url, RALLY_REPO_DIR)
255
256         logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
257         install_script = RALLY_REPO_DIR + "install_rally.sh --yes"
258         cmd = 'sudo ' + install_script
259         functest_utils.execute_command(cmd,logger)
260
261         logger.debug("Creating Rally environment...")
262         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
263         functest_utils.execute_command(cmd,logger)
264
265         logger.debug("Installing tempest...")
266         cmd = "rally verify install"
267         functest_utils.execute_command(cmd,logger)
268
269         cmd = "rally deployment check"
270         functest_utils.execute_command(cmd,logger)
271         #TODO: check that everything is 'Available' and warn if not
272
273         cmd = "rally show images"
274         functest_utils.execute_command(cmd,logger)
275
276         cmd = "rally show flavors"
277         functest_utils.execute_command(cmd,logger)
278
279     return True
280
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 opnfv";
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 def install_odl():
305     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
306     functest_utils.execute_command(cmd,logger)
307     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
308     functest_utils.execute_command(cmd,logger)
309     cmd = ODL_DIR + "create_venv.sh"
310     functest_utils.execute_command(cmd,logger)
311     return True
312
313
314
315 def create_glance_image(path,name,disk_format):
316     """
317     Create a glance image given the absolute path of the image, its name and the disk format
318     """
319     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
320     functest_utils.execute_command(cmd,logger)
321     return True
322
323
324
325
326 def main():
327     if not (args.action in actions):
328         logger.error('argument not valid')
329         exit(-1)
330
331
332     if not functest_utils.check_credentials():
333         logger.error("Please source the openrc credentials and run the script again.")
334         #TODO: source the credentials in this script
335         exit(-1)
336
337     if args.action == "start":
338         action_start()
339
340     if args.action == "check":
341         if action_check():
342             logger.info("Functest environment correctly installed")
343         else:
344             logger.info("Functest environment not found or faulty")
345
346     if args.action == "clean":
347         if args.force :
348             action_clean()
349         else :
350             while True:
351                 print("Are you sure? [y|n]")
352                 answer = raw_input("")
353                 if answer == "y":
354                     action_clean()
355                     break
356                 elif answer == "n":
357                     break
358                 else:
359                     print("Invalid option.")
360     exit(0)
361
362
363 if __name__ == '__main__':
364     main()
365