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