8523a77f4c6b823910cd37fe0884f72023904d4e
[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 REPO_PATH = args.repo_path
55 RALLY_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_rally")
56 RALLY_REPO_DIR = functest_yaml.get("general").get("directories").get("dir_repo_rally")
57 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get("dir_rally_inst")
58 RALLY_RESULT_DIR = 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 DATA_DIR = functest_yaml.get("general").get("directories").get("dir_functest_data")
62
63 # Tempest/Rally configuration details
64 DEPLOYMENT_MAME = "opnfv-rally"
65 RALLY_COMMIT = functest_yaml.get("general").get("openstack").get("rally_stable_commit")
66
67 #GLANCE image parameters
68 IMAGE_FILE_NAME = functest_yaml.get("general").get("openstack").get("image_file_name")
69 IMAGE_DISK_FORMAT = functest_yaml.get("general").get("openstack").get("image_disk_format")
70 IMAGE_NAME = functest_yaml.get("general").get("openstack").get("image_name")
71 IMAGE_PATH = DATA_DIR + "/" + IMAGE_FILE_NAME
72
73
74 def action_start():
75     """
76     Start the functest environment installation
77     """
78     if not functest_utils.check_internet_connectivity():
79         logger.error("There is no Internet connectivity. Please check the network configuration.")
80         exit(-1)
81
82     if action_check():
83         logger.info("Functest environment already installed. Nothing to do.")
84         exit(0)
85
86     else:
87         # Clean in case there are left overs
88         logger.debug("Cleaning possible functest environment leftovers.")
89         action_clean()
90
91         logger.info("Starting installation of functest environment")
92         logger.info("Installing Rally...")
93         if not install_rally():
94             logger.error("There has been a problem while installing Rally.")
95             action_clean()
96             exit(-1)
97
98         logger.info("Configuring Tempest...")
99         if not configure_tempest():
100             logger.error("There has been a problem while configuring Tempest.")
101             action_clean()
102             exit(-1)
103
104         # Create result folder under functest if necessary
105         if not os.path.exists(RALLY_RESULT_DIR):
106             os.makedirs(RALLY_RESULT_DIR)
107
108         logger.info("Creating Glance image: %s ..." %IMAGE_NAME)
109         if not create_glance_image(IMAGE_PATH,IMAGE_NAME,IMAGE_DISK_FORMAT):
110             logger.error("There has been a problem while creating the Glance image.")
111             action_clean()
112             exit(-1)
113
114         exit(0)
115
116
117 def action_check():
118     """
119     Check if the functest environment is properly installed
120     """
121     errors_all = False
122     errors = False
123     logger.info("Checking current functest configuration...")
124
125     logger.debug("Checking script directories...")
126
127     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
128     for dir in dirs:
129         if not os.path.exists(dir):
130             logger.debug("The directory '%s' does NOT exist." % dir)
131             errors = True
132             errors_all = True
133         else:
134             logger.debug("   %s found" % dir)
135     if not errors:
136         logger.debug("...OK")
137     else:
138         logger.debug("...FAIL")
139
140
141     logger.debug("Checking Rally deployment...")
142     if not check_rally():
143         logger.debug("   Rally deployment NOT installed.")
144         errors_all = True
145         logger.debug("...FAIL")
146     else:
147         logger.debug("...OK")
148
149     logger.debug("Checking Image...")
150     errors = False
151     if not os.path.isfile(IMAGE_PATH):
152         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
153         errors = True
154         errors_all = True
155     else:
156         logger.debug("   Image file found in %s" % IMAGE_PATH)
157
158     cmd="glance image-list | grep " + IMAGE_NAME
159     FNULL = open(os.devnull, 'w');
160     logger.debug('   Executing command : {}'.format(cmd))
161     p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
162     #if the command does not exist or there is no glance image
163     line = p.stdout.readline()
164     if line == "":
165         logger.debug("   Glance image NOT found.")
166         errors = True
167         errors_all = True
168     else:
169         logger.debug("   Glance image found.")
170
171     if not errors:
172         logger.debug("...OK")
173     else:
174         logger.debug("...FAIL")
175
176     #TODO: check OLD environment setup
177     return not errors_all
178
179
180
181 def action_clean():
182     """
183     Clean the existing functest environment
184     """
185     logger.info("Removing current functest environment...")
186     if os.path.exists(RALLY_INSTALLATION_DIR):
187         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
188         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
189
190     cmd = "glance image-list | grep "+IMAGE_NAME+" | cut -c3-38"
191     p = os.popen(cmd,"r")
192
193     #while image_id = p.readline()
194     for image_id in p.readlines():
195         cmd = "glance image-delete " + image_id
196         functest_utils.execute_command(cmd,logger)
197
198     if os.path.exists(RALLY_RESULT_DIR):
199         logger.debug("Removing Result directory")
200         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
201
202
203     logger.info("Functest environment clean!")
204
205
206
207 def install_rally():
208     if check_rally():
209         logger.info("Rally is already installed.")
210     else:
211         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
212         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
213         cmd = 'sudo ' + install_script
214         functest_utils.execute_command(cmd,logger)
215
216         logger.debug("Creating Rally environment...")
217         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
218         functest_utils.execute_command(cmd,logger)
219
220         logger.debug("Installing tempest...")
221         cmd = "rally verify install"
222         functest_utils.execute_command(cmd,logger)
223
224         cmd = "rally deployment check"
225         functest_utils.execute_command(cmd,logger)
226         #TODO: check that everything is 'Available' and warn if not
227
228         cmd = "rally show images"
229         functest_utils.execute_command(cmd,logger)
230
231         cmd = "rally show flavors"
232         functest_utils.execute_command(cmd,logger)
233
234     return True
235
236
237 def configure_tempest():
238     """
239     Add/update needed parameters into tempest.conf file generated by Rally
240     """
241
242     creds_neutron = functest_utils.get_credentials("neutron")
243     neutron_client = neutronclient.Client(**creds_neutron)
244
245     logger.debug("Generating tempest.conf file...")
246     cmd = "rally verify genconfig"
247     functest_utils.execute_command(cmd,logger)
248
249     logger.debug("Resolving deployment UUID...")
250     cmd = "rally deployment list | awk '/"+DEPLOYMENT_MAME+"/ {print $2}'"
251     p = subprocess.Popen(cmd, shell=True,
252                          stdout=subprocess.PIPE,
253                          stderr=subprocess.STDOUT);
254     deployment_uuid = p.stdout.readline().rstrip()
255     if deployment_uuid == "":
256         logger.debug("   Rally deployment NOT found")
257         return False
258
259     logger.debug("Finding tempest.conf file...")
260     tempest_conf_file = RALLY_INSTALLATION_DIR+"/tempest/for-deployment-" \
261                         +deployment_uuid+"/tempest.conf"
262
263     logger.debug("  Updating fixed_network_name...")
264     fixed_network = functest_utils.get_network_list(neutron_client)[0]['name']
265     if fixed_network != None:
266         cmd = "crudini --set "+tempest_conf_file+" compute fixed_network_name "+fixed_network
267         functest_utils.execute_command(cmd,logger)
268
269     return True
270
271
272 def check_rally():
273     """
274     Check if Rally is installed and properly configured
275     """
276     if os.path.exists(RALLY_INSTALLATION_DIR):
277         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
278         FNULL = open(os.devnull, 'w');
279         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
280         logger.debug('   Executing command : {}'.format(cmd))
281         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
282         #if the command does not exist or there is no deployment
283         line = p.stdout.readline()
284         if line == "":
285             logger.debug("   Rally deployment NOT found")
286             return False
287         logger.debug("   Rally deployment found")
288         return True
289     else:
290         return False
291
292
293
294 def create_glance_image(path,name,disk_format):
295     """
296     Create a glance image given the absolute path of the image, its name and the disk format
297     """
298     cmd = ("glance image-create --name "+name+"  --visibility public "
299     "--disk-format "+disk_format+" --container-format bare --file "+path)
300     functest_utils.execute_command(cmd,logger)
301     return True
302
303
304
305
306 def main():
307     if not (args.action in actions):
308         logger.error('argument not valid')
309         exit(-1)
310
311
312     if not functest_utils.check_credentials():
313         logger.error("Please source the openrc credentials and run the script again.")
314         #TODO: source the credentials in this script
315         exit(-1)
316
317     if args.action == "start":
318         action_start()
319
320     if args.action == "check":
321         if action_check():
322             logger.info("Functest environment correctly installed")
323         else:
324             logger.info("Functest environment not found or faulty")
325
326     if args.action == "clean":
327         if args.force :
328             action_clean()
329         else :
330             while True:
331                 print("Are you sure? [y|n]")
332                 answer = raw_input("")
333                 if answer == "y":
334                     action_clean()
335                     break
336                 elif answer == "n":
337                     break
338                 else:
339                     print("Invalid option.")
340     exit(0)
341
342
343 if __name__ == '__main__':
344     main()
345