config_functest.py: Rally installed with sudo
[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
12 import functest_utils
13 from git import Repo
14
15 actions = ['start', 'check', 'clean']
16 parser = argparse.ArgumentParser()
17 parser.add_argument("repo_path", help="Path to the repository")
18 parser.add_argument("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
19 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
20 parser.add_argument("-f", "--force", help="Force",  action="store_true")
21 args = parser.parse_args()
22
23
24 """ logging configuration """
25 logger = logging.getLogger('config_functest')
26 logger.setLevel(logging.DEBUG)
27
28 ch = logging.StreamHandler()
29 if args.debug:
30     ch.setLevel(logging.DEBUG)
31 else:
32     ch.setLevel(logging.INFO)
33
34 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
35 ch.setFormatter(formatter)
36 logger.addHandler(ch)
37
38 if not os.path.exists(args.repo_path):
39     logger.error("Repo directory not found '%s'" % args.repo_path)
40     exit(-1)
41
42 with open(args.repo_path+"testcases/config_functest.yaml") as f:
43     functest_yaml = yaml.safe_load(f)
44 f.close()
45
46
47
48
49 """ global variables """
50 # Directories
51 HOME = os.environ['HOME']+"/"
52 REPO_PATH = args.repo_path
53 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
54 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
55 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
56 RALLY_RESULT_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_res")
57 VPING_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_vping")
58 ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
59
60
61 #GLANCE image parameters
62 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
63 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
64 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
65 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
66 IMAGE_DIR = HOME + functest_yaml.get("general").get("openstack").get("image_download_path")
67 IMAGE_PATH = IMAGE_DIR + IMAGE_FILE_NAME
68
69
70 def action_start():
71     """
72     Start the functest environment installation
73     """
74     if not functest_utils.check_internet_connectivity():
75         logger.error("There is no Internet connectivity. Please check the network configuration.")
76         exit(-1)
77
78     if action_check():
79         logger.info("Functest environment already installed. Nothing to do.")
80         exit(0)
81
82     else:
83         # Clean in case there are left overs
84         logger.debug("Cleaning possible functest environment leftovers.")
85         action_clean()
86
87         logger.info("Starting installation of functest environment")
88         logger.info("Installing Rally...")
89         if not install_rally():
90             logger.error("There has been a problem while installing Rally.")
91             action_clean()
92             exit(-1)
93
94         logger.info("Installing ODL environment...")
95         if not install_odl():
96             logger.error("There has been a problem while installing Robot.")
97             action_clean()
98             exit(-1)
99
100         # Create result folder under functest if necessary
101         if not os.path.exists(RALLY_RESULT_DIR):
102             os.makedirs(RALLY_RESULT_DIR)
103
104         logger.info("Downloading image...")
105         if not functest_utils.download_url(IMAGE_URL, IMAGE_DIR):
106             logger.error("There has been a problem downloading the image '%s'." %IMAGE_URL)
107             action_clean()
108             exit(-1)
109
110         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
111         if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
112             logger.error("There has been a problem while creating the Glance image.")
113             action_clean()
114             exit(-1)
115
116         exit(0)
117
118
119 def action_check():
120     """
121     Check if the functest environment is properly installed
122     """
123     errors_all = False
124
125     logger.info("Checking current functest configuration...")
126
127     logger.debug("Checking script directories...")
128     errors = False
129     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
130     for dir in dirs:
131         if not os.path.exists(dir):
132             logger.debug("The directory '%s' does NOT exist." % dir)
133             errors = True
134             errors_all = True
135         else:
136             logger.debug("   %s found" % dir)
137     if not errors:
138         logger.debug("...OK")
139     else:
140         logger.debug("...FAIL")
141
142
143     logger.debug("Checking Rally deployment...")
144     if not check_rally():
145         logger.debug("   Rally deployment NOT installed.")
146         errors_all = True
147         logger.debug("...FAIL")
148     else:
149         logger.debug("...OK")
150
151     logger.debug("Checking Image...")
152     errors = False
153     if not os.path.isfile(IMAGE_PATH):
154         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
155         errors = True
156         errors_all = True
157     else:
158         logger.debug("   Image file found in %s" % IMAGE_PATH)
159
160     cmd="glance image-list | grep " + IMAGE_NAME
161     FNULL = open(os.devnull, 'w');
162     logger.debug('   Executing command : {}'.format(cmd))
163     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
164     #if the command does not exist or there is no glance image
165     line = p.stdout.readline()
166     if line == "":
167         logger.debug("   Glance image NOT found.")
168         errors = True
169         errors_all = True
170     else:
171         logger.debug("   Glance image found.")
172
173     if not errors:
174         logger.debug("...OK")
175     else:
176         logger.debug("...FAIL")
177
178     #TODO: check OLD environment setup
179     if errors_all:
180         return False
181     else:
182         return True
183
184
185
186
187 def action_clean():
188     """
189     Clean the existing functest environment
190     """
191     logger.info("Removing current functest environment...")
192     if os.path.exists(RALLY_INSTALLATION_DIR):
193         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
194         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
195
196     if os.path.exists(RALLY_REPO_DIR):
197         logger.debug("Removing Rally repository %s" % RALLY_REPO_DIR)
198         cmd = "sudo rm -rf " + RALLY_REPO_DIR #need to be sudo, not possible with rmtree
199         functest_utils.execute_command(cmd,logger)
200
201     if os.path.exists(IMAGE_PATH):
202         logger.debug("Deleting image")
203         os.remove(IMAGE_PATH)
204
205     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
206     p = os.popen(cmd,"r")
207
208     #while image_id = p.readline()
209     for image_id in p.readlines():
210         cmd = "glance image-delete " + image_id
211         functest_utils.execute_command(cmd,logger)
212
213     if os.path.exists(RALLY_RESULT_DIR):
214         logger.debug("Removing Result directory")
215         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
216
217
218     logger.info("Functest environment clean!")
219
220
221
222
223
224 def install_rally():
225     if check_rally():
226         logger.info("Rally is already installed.")
227     else:
228         logger.debug("Cloning repository...")
229         url = "https://git.openstack.org/openstack/rally"
230         Repo.clone_from(url, RALLY_REPO_DIR)
231
232         logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
233         install_script = RALLY_REPO_DIR + "install_rally.sh"
234         cmd = 'sudo ' + install_script
235         functest_utils.execute_command(cmd,logger)
236
237         logger.debug("Creating Rally environment...")
238         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
239         functest_utils.execute_command(cmd,logger)
240
241         logger.debug("Installing tempest...")
242         cmd = "rally-manage tempest install"
243         functest_utils.execute_command(cmd,logger)
244
245         cmd = "rally deployment check"
246         functest_utils.execute_command(cmd,logger)
247         #TODO: check that everything is 'Available' and warn if not
248
249         cmd = "rally show images"
250         functest_utils.execute_command(cmd,logger)
251
252         cmd = "rally show flavors"
253         functest_utils.execute_command(cmd,logger)
254
255     return True
256
257
258
259 def check_rally():
260     """
261     Check if Rally is installed and properly configured
262     """
263     if os.path.exists(RALLY_INSTALLATION_DIR):
264         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
265         FNULL = open(os.devnull, 'w');
266         cmd="rally deployment list | grep opnfv";
267         logger.debug('   Executing command : {}'.format(cmd))
268         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
269         #if the command does not exist or there is no deployment
270         line = p.stdout.readline()
271         if line == "":
272             logger.debug("   Rally deployment NOT found")
273             return False
274         logger.debug("   Rally deployment found")
275         return True
276     else:
277         return False
278
279
280 def install_odl():
281     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
282     functest_utils.execute_command(cmd,logger)
283     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
284     functest_utils.execute_command(cmd,logger)
285     cmd = ODL_DIR + "create_venv.sh"
286     functest_utils.execute_command(cmd,logger)
287     return True
288
289
290
291 def create_glance_image(path,name,disk_format):
292     """
293     Create a glance image given the absolute path of the image, its name and the disk format
294     """
295     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
296     functest_utils.execute_command(cmd,logger)
297     return True
298
299
300
301
302 def main():
303     if not (args.action in actions):
304         logger.error('argument not valid')
305         exit(-1)
306
307
308     if not functest_utils.check_credentials():
309         logger.error("Please source the openrc credentials and run the script again.")
310         #TODO: source the credentials in this script
311         exit(-1)
312
313     if args.action == "start":
314         action_start()
315
316     if args.action == "check":
317         if action_check():
318             logger.info("Functest environment correctly installed")
319         else:
320             logger.info("Functest environment not found or faulty")
321
322     if args.action == "clean":
323         if args.force :
324             action_clean()
325         else :
326             while True:
327                 print("Are you sure? [y|n]")
328                 answer = raw_input("")
329                 if answer == "y":
330                     action_clean()
331                     break
332                 elif answer == "n":
333                     break
334                 else:
335                     print("Invalid option.")
336     exit(0)
337
338
339 if __name__ == '__main__':
340     main()
341