Merge "Put ToC after heading"
[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 VPING_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_vping")
57 ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
58
59
60 #GLANCE image parameters
61 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
62 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
63 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
64 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
65 IMAGE_DIR = HOME + functest_yaml.get("general").get("openstack").get("image_download_path")
66 IMAGE_PATH = IMAGE_DIR + IMAGE_FILE_NAME
67
68
69 def action_start():
70     """
71     Start the functest environment installation
72     """
73     if not functest_utils.check_internet_connectivity():
74         logger.error("There is no Internet connectivity. Please check the network configuration.")
75         exit(-1)
76
77     if action_check():
78         logger.info("Functest environment already installed. Nothing to do.")
79         exit(0)
80
81     else:
82         # Clean in case there are left overs
83         logger.debug("Cleaning possible functest environment leftovers.")
84         action_clean()
85
86         logger.info("Starting installation of functest environment")
87         logger.info("Installing Rally...")
88         if not install_rally():
89             logger.error("There has been a problem while installing Rally.")
90             action_clean()
91             exit(-1)
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
100         logger.info("Downloading image...")
101         if not functest_utils.download_url(IMAGE_URL, IMAGE_DIR):
102             logger.error("There has been a problem downloading the image '%s'." %IMAGE_URL)
103             action_clean()
104             exit(-1)
105
106         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
107         if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
108             logger.error("There has been a problem while creating the Glance image.")
109             action_clean()
110             exit(-1)
111
112         exit(0)
113
114
115 def action_check():
116     """
117     Check if the functest environment is properly installed
118     """
119     errors_all = False
120
121     logger.info("Checking current functest configuration...")
122
123     logger.debug("Checking script directories...")
124     errors = False
125     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
126     for dir in dirs:
127         if not os.path.exists(dir):
128             logger.debug("The directory '%s' does NOT exist." % dir)
129             errors = True
130             errors_all = True
131         else:
132             logger.debug("   %s found" % dir)
133     if not errors:
134         logger.debug("...OK")
135     else:
136         logger.debug("...FAIL")
137
138
139     logger.debug("Checking Rally deployment...")
140     if not check_rally():
141         logger.debug("   Rally deployment NOT installed.")
142         errors_all = True
143         logger.debug("...FAIL")
144     else:
145         logger.debug("...OK")
146
147     logger.debug("Checking Image...")
148     errors = False
149     if not os.path.isfile(IMAGE_PATH):
150         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
151         errors = True
152         errors_all = True
153     else:
154         logger.debug("   Image file found in %s" % IMAGE_PATH)
155
156     cmd="glance image-list | grep " + IMAGE_NAME
157     FNULL = open(os.devnull, 'w');
158     logger.debug('   Executing command : {}'.format(cmd))
159     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
160     #if the command does not exist or there is no glance image
161     line = p.stdout.readline()
162     if line == "":
163         logger.debug("   Glance image NOT found.")
164         errors = True
165         errors_all = True
166     else:
167         logger.debug("   Glance image found.")
168
169     if not errors:
170         logger.debug("...OK")
171     else:
172         logger.debug("...FAIL")
173
174     #TODO: check OLD environment setup
175     if errors_all:
176         return False
177     else:
178         return True
179
180
181
182
183 def action_clean():
184     """
185     Clean the existing functest environment
186     """
187     logger.info("Removing current functest environment...")
188     if os.path.exists(RALLY_INSTALLATION_DIR):
189         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
190         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
191
192     if os.path.exists(RALLY_REPO_DIR):
193         logger.debug("Removing Rally repository %s" % RALLY_REPO_DIR)
194         cmd = "sudo rm -rf " + RALLY_REPO_DIR #need to be sudo, not possible with rmtree
195         functest_utils.execute_command(cmd,logger)
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     logger.info("Functest environment clean!")
210
211
212
213
214
215 def install_rally():
216     if check_rally():
217         logger.info("Rally is already installed.")
218     else:
219         logger.debug("Cloning repository...")
220         url = "https://git.openstack.org/openstack/rally"
221         Repo.clone_from(url, RALLY_REPO_DIR)
222
223         logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
224         install_script = RALLY_REPO_DIR + "install_rally.sh"
225         functest_utils.execute_command(install_script,logger)
226
227         logger.debug("Creating Rally environment...")
228         cmd = "rally deployment create --fromenv --name=opnfv-arno-rally"
229         functest_utils.execute_command(cmd,logger)
230
231         logger.debug("Installing tempest...")
232         cmd = "rally-manage tempest 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
249 def check_rally():
250     """
251     Check if Rally is installed and properly configured
252     """
253     if os.path.exists(RALLY_INSTALLATION_DIR):
254         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
255         FNULL = open(os.devnull, 'w');
256         cmd="rally deployment list | grep opnfv";
257         logger.debug('   Executing command : {}'.format(cmd))
258         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
259         #if the command does not exist or there is no deployment
260         line = p.stdout.readline()
261         if line == "":
262             logger.debug("   Rally deployment NOT found")
263             return False
264         logger.debug("   Rally deployment found")
265         return True
266     else:
267         return False
268
269
270 def install_odl():
271     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
272     functest_utils.execute_command(cmd,logger)
273     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
274     functest_utils.execute_command(cmd,logger)
275     cmd = ODL_DIR + "create_venv.sh"
276     functest_utils.execute_command(cmd,logger)
277     return True
278
279
280
281 def create_glance_image(path,name,disk_format):
282     """
283     Create a glance image given the absolute path of the image, its name and the disk format
284     """
285     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
286     functest_utils.execute_command(cmd,logger)
287     return True
288
289
290
291
292 def main():
293     if not (args.action in actions):
294         logger.error('argument not valid')
295         exit(-1)
296
297
298     if not functest_utils.check_credentials():
299         logger.error("Please source the openrc credentials and run the script again.")
300         #TODO: source the credentials in this script
301         exit(-1)
302
303     if args.action == "start":
304         action_start()
305
306     if args.action == "check":
307         if action_check():
308             logger.info("Functest environment correctly installed")
309         else:
310             logger.info("Functest environment not found or faulty")
311
312     if args.action == "clean":
313         if args.force :
314             action_clean()
315         else :
316             while True:
317                 print("Are you sure? [y|n]")
318                 answer = raw_input("")
319                 if answer == "y":
320                     action_clean()
321                     break
322                 elif answer == "n":
323                     break
324                 else:
325                     print("Invalid option.")
326     exit(0)
327
328
329 if __name__ == '__main__':
330     main()
331