Merge "Doc: Fixed weird chars for the tree directory structure JIRA: FUNCTEST-9"
[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         functest_utils.execute_command(install_script,logger)
235
236         logger.debug("Creating Rally environment...")
237         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
238         functest_utils.execute_command(cmd,logger)
239
240         logger.debug("Installing tempest...")
241         cmd = "rally-manage tempest install"
242         functest_utils.execute_command(cmd,logger)
243
244         cmd = "rally deployment check"
245         functest_utils.execute_command(cmd,logger)
246         #TODO: check that everything is 'Available' and warn if not
247
248         cmd = "rally show images"
249         functest_utils.execute_command(cmd,logger)
250
251         cmd = "rally show flavors"
252         functest_utils.execute_command(cmd,logger)
253
254     return True
255
256
257
258 def check_rally():
259     """
260     Check if Rally is installed and properly configured
261     """
262     if os.path.exists(RALLY_INSTALLATION_DIR):
263         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
264         FNULL = open(os.devnull, 'w');
265         cmd="rally deployment list | grep opnfv";
266         logger.debug('   Executing command : {}'.format(cmd))
267         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
268         #if the command does not exist or there is no deployment
269         line = p.stdout.readline()
270         if line == "":
271             logger.debug("   Rally deployment NOT found")
272             return False
273         logger.debug("   Rally deployment found")
274         return True
275     else:
276         return False
277
278
279 def install_odl():
280     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
281     functest_utils.execute_command(cmd,logger)
282     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
283     functest_utils.execute_command(cmd,logger)
284     cmd = ODL_DIR + "create_venv.sh"
285     functest_utils.execute_command(cmd,logger)
286     return True
287
288
289
290 def create_glance_image(path,name,disk_format):
291     """
292     Create a glance image given the absolute path of the image, its name and the disk format
293     """
294     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
295     functest_utils.execute_command(cmd,logger)
296     return True
297
298
299
300
301 def main():
302     if not (args.action in actions):
303         logger.error('argument not valid')
304         exit(-1)
305
306
307     if not functest_utils.check_credentials():
308         logger.error("Please source the openrc credentials and run the script again.")
309         #TODO: source the credentials in this script
310         exit(-1)
311
312     if args.action == "start":
313         action_start()
314
315     if args.action == "check":
316         if action_check():
317             logger.info("Functest environment correctly installed")
318         else:
319             logger.info("Functest environment not found or faulty")
320
321     if args.action == "clean":
322         if args.force :
323             action_clean()
324         else :
325             while True:
326                 print("Are you sure? [y|n]")
327                 answer = raw_input("")
328                 if answer == "y":
329                     action_clean()
330                     break
331                 elif answer == "n":
332                     break
333                 else:
334                     print("Invalid option.")
335     exit(0)
336
337
338 if __name__ == '__main__':
339     main()
340