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