Added configure_tempest() function
[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 HOME = os.environ['HOME']+"/"
55 REPO_PATH = args.repo_path
56 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
57 RALLY_REPO_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_repo")
58 RALLY_INSTALLATION_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_inst")
59 RALLY_RESULT_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_res")
60 VPING_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_vping")
61 ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
62
63 # Tempest/Rally configuration details
64 DEPLOYMENT_MAME = "opnfv-rally"
65
66 #GLANCE image parameters
67 IMAGE_URL = functest_yaml.get("general").get("openstack").get("image_url")
68 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
69 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
70 IMAGE_FILE_NAME = IMAGE_URL.rsplit('/')[-1]
71 IMAGE_DIR = HOME + functest_yaml.get("general").get("openstack").get("image_download_path")
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 check_permissions():
80         logger.error("Bad Python cache directory ownership.")
81         exit(-1)
82
83     if not functest_utils.check_internet_connectivity():
84         logger.error("There is no Internet connectivity. Please check the network configuration.")
85         exit(-1)
86
87     if action_check():
88         logger.info("Functest environment already installed. Nothing to do.")
89         exit(0)
90
91     else:
92         # Clean in case there are left overs
93         logger.debug("Cleaning possible functest environment leftovers.")
94         action_clean()
95
96         logger.info("Installing needed libraries on the host")
97         cmd = "sudo yum -y install gcc libffi-devel python-devel openssl-devel gmp-devel libxml2-devel libxslt-devel postgresql-devel git wget crudini"
98         if not functest_utils.execute_command(cmd, logger):
99             logger.error("There has been a problem while installing software packages.")
100             exit(-1)
101
102         logger.info("Installing ODL environment...")
103         if not install_odl():
104             logger.error("There has been a problem while installing Robot.")
105             action_clean()
106             exit(-1)
107
108         logger.info("Starting installation of functest environment")
109         logger.info("Installing Rally...")
110         if not install_rally():
111             logger.error("There has been a problem while installing Rally.")
112             action_clean()
113             exit(-1)
114
115         logger.info("Configuring Tempest...")
116         if not configure_tempest():
117             logger.error("There has been a problem while configuring Tempest.")
118             action_clean()
119             exit(-1)
120
121         # Create result folder under functest if necessary
122         if not os.path.exists(RALLY_RESULT_DIR):
123             os.makedirs(RALLY_RESULT_DIR)
124
125         logger.info("Downloading image...")
126         if not functest_utils.download_url(IMAGE_URL, IMAGE_DIR):
127             logger.error("There has been a problem downloading the image '%s'." %IMAGE_URL)
128             action_clean()
129             exit(-1)
130
131         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
132         if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
133             logger.error("There has been a problem while creating the Glance image.")
134             action_clean()
135             exit(-1)
136
137         exit(0)
138
139
140 def action_check():
141     """
142     Check if the functest environment is properly installed
143     """
144     errors_all = False
145
146     logger.info("Checking current functest configuration...")
147
148     logger.debug("Checking script directories...")
149     errors = False
150     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
151     for dir in dirs:
152         if not os.path.exists(dir):
153             logger.debug("The directory '%s' does NOT exist." % dir)
154             errors = True
155             errors_all = True
156         else:
157             logger.debug("   %s found" % dir)
158     if not errors:
159         logger.debug("...OK")
160     else:
161         logger.debug("...FAIL")
162
163
164     logger.debug("Checking Rally deployment...")
165     if not check_rally():
166         logger.debug("   Rally deployment NOT installed.")
167         errors_all = True
168         logger.debug("...FAIL")
169     else:
170         logger.debug("...OK")
171
172     logger.debug("Checking Image...")
173     errors = False
174     if not os.path.isfile(IMAGE_PATH):
175         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
176         errors = True
177         errors_all = True
178     else:
179         logger.debug("   Image file found in %s" % IMAGE_PATH)
180
181     cmd="glance image-list | grep " + IMAGE_NAME
182     FNULL = open(os.devnull, 'w');
183     logger.debug('   Executing command : {}'.format(cmd))
184     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
185     #if the command does not exist or there is no glance image
186     line = p.stdout.readline()
187     if line == "":
188         logger.debug("   Glance image NOT found.")
189         errors = True
190         errors_all = True
191     else:
192         logger.debug("   Glance image found.")
193
194     if not errors:
195         logger.debug("...OK")
196     else:
197         logger.debug("...FAIL")
198
199     #TODO: check OLD environment setup
200     if errors_all:
201         return False
202     else:
203         return True
204
205
206
207
208 def action_clean():
209     """
210     Clean the existing functest environment
211     """
212     logger.info("Removing current functest environment...")
213     if os.path.exists(RALLY_INSTALLATION_DIR):
214         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
215         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
216
217     if os.path.exists(RALLY_REPO_DIR):
218         logger.debug("Removing Rally repository %s" % RALLY_REPO_DIR)
219         cmd = "sudo rm -rf " + RALLY_REPO_DIR #need to be sudo, not possible with rmtree
220         functest_utils.execute_command(cmd,logger)
221
222     if os.path.exists(IMAGE_PATH):
223         logger.debug("Deleting image")
224         os.remove(IMAGE_PATH)
225
226     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
227     p = os.popen(cmd,"r")
228
229     #while image_id = p.readline()
230     for image_id in p.readlines():
231         cmd = "glance image-delete " + image_id
232         functest_utils.execute_command(cmd,logger)
233
234     if os.path.exists(RALLY_RESULT_DIR):
235         logger.debug("Removing Result directory")
236         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
237
238
239     logger.info("Functest environment clean!")
240
241
242
243 def check_permissions():
244     current_user = getpass.getuser()
245     cache_dir = HOME+".cache/pip"
246     logger.info("Checking permissions of '%s'..." %cache_dir)
247     logger.debug("Current user is '%s'" %current_user)
248     cache_user = getpwuid(stat(cache_dir).st_uid).pw_name
249     logger.debug("Cache directory owner is '%s'" %cache_user)
250     if cache_user != current_user:
251         logger.info("The owner of '%s' is '%s'. Please run 'sudo chown -R %s %s'." %(cache_dir, cache_user, current_user, cache_dir))
252         return False
253
254     return True
255
256
257 def install_rally():
258     if check_rally():
259         logger.info("Rally is already installed.")
260     else:
261         logger.debug("Cloning repository...")
262         url = "https://git.openstack.org/openstack/rally"
263         Repo.clone_from(url, RALLY_REPO_DIR)
264
265         logger.debug("Executing %s./install_rally.sh..." %RALLY_REPO_DIR)
266         install_script = RALLY_REPO_DIR + "install_rally.sh --yes"
267         cmd = 'sudo ' + install_script
268         functest_utils.execute_command(cmd,logger)
269
270         logger.debug("Creating Rally environment...")
271         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
272         functest_utils.execute_command(cmd,logger)
273
274         logger.debug("Installing tempest...")
275         cmd = "rally verify install"
276         functest_utils.execute_command(cmd,logger)
277
278         cmd = "rally deployment check"
279         functest_utils.execute_command(cmd,logger)
280         #TODO: check that everything is 'Available' and warn if not
281
282         cmd = "rally show images"
283         functest_utils.execute_command(cmd,logger)
284
285         cmd = "rally show flavors"
286         functest_utils.execute_command(cmd,logger)
287
288     return True
289
290
291 def configure_tempest():
292     """
293     Add/update needed parameters into tempest.conf file generated by Rally
294     """
295
296     creds_neutron = functest_utils.get_credentials("neutron")
297     neutron_client = neutronclient.Client(**creds_neutron)
298
299     logger.debug("Generating tempest.conf file...")
300     cmd = "rally verify genconfig"
301     functest_utils.execute_command(cmd,logger)
302
303     logger.debug("Resolving deployment UUID...")
304     cmd = "rally deployment list | awk '/"+DEPLOYMENT_MAME+"/ {print $2}'"
305     p = subprocess.Popen(cmd, shell=True,
306                          stdout=subprocess.PIPE,
307                          stderr=subprocess.STDOUT);
308     deployment_uuid = p.stdout.readline().rstrip()
309     if deployment_uuid == "":
310         logger.debug("   Rally deployment NOT found")
311         return False
312
313     logger.debug("Finding tempest.conf file...")
314     tempest_conf_file = RALLY_INSTALLATION_DIR+"tempest/for-deployment-" \
315                         +deployment_uuid+"/tempest.conf"
316
317     logger.debug("  Updating fixed_network_name...")
318     fixed_network = functest_utils.get_network_list(neutron_client)[0]['name']
319     if fixed_network != None:
320         cmd = "crudini --set "+tempest_conf_file+" compute fixed_network_name "+fixed_network
321         functest_utils.execute_command(cmd,logger)
322
323     return True
324
325
326 def check_rally():
327     """
328     Check if Rally is installed and properly configured
329     """
330     if os.path.exists(RALLY_INSTALLATION_DIR):
331         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
332         FNULL = open(os.devnull, 'w');
333         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
334         logger.debug('   Executing command : {}'.format(cmd))
335         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
336         #if the command does not exist or there is no deployment
337         line = p.stdout.readline()
338         if line == "":
339             logger.debug("   Rally deployment NOT found")
340             return False
341         logger.debug("   Rally deployment found")
342         return True
343     else:
344         return False
345
346
347 def install_odl():
348     cmd = "chmod +x " + ODL_DIR + "start_tests.sh"
349     functest_utils.execute_command(cmd,logger)
350     cmd = "chmod +x " + ODL_DIR + "create_venv.sh"
351     functest_utils.execute_command(cmd,logger)
352     cmd = ODL_DIR + "create_venv.sh"
353     functest_utils.execute_command(cmd,logger)
354     return True
355
356
357
358 def create_glance_image(path,name,disk_format):
359     """
360     Create a glance image given the absolute path of the image, its name and the disk format
361     """
362     cmd = "glance image-create --name "+name+" --is-public true --disk-format "+disk_format+" --container-format bare --file "+path
363     functest_utils.execute_command(cmd,logger)
364     return True
365
366
367
368
369 def main():
370     if not (args.action in actions):
371         logger.error('argument not valid')
372         exit(-1)
373
374
375     if not functest_utils.check_credentials():
376         logger.error("Please source the openrc credentials and run the script again.")
377         #TODO: source the credentials in this script
378         exit(-1)
379
380     if args.action == "start":
381         action_start()
382
383     if args.action == "check":
384         if action_check():
385             logger.info("Functest environment correctly installed")
386         else:
387             logger.info("Functest environment not found or faulty")
388
389     if args.action == "clean":
390         if args.force :
391             action_clean()
392         else :
393             while True:
394                 print("Are you sure? [y|n]")
395                 answer = raw_input("")
396                 if answer == "y":
397                     action_clean()
398                     break
399                 elif answer == "n":
400                     break
401                 else:
402                     print("Invalid option.")
403     exit(0)
404
405
406 if __name__ == '__main__':
407     main()
408