Using shared private network
[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("action", help="Possible actions are: '{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
21 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
22 parser.add_argument("-f", "--force", help="Force",  action="store_true")
23 args = parser.parse_args()
24
25
26 """ logging configuration """
27 logger = logging.getLogger('config_functest')
28 logger.setLevel(logging.DEBUG)
29
30 ch = logging.StreamHandler()
31 if args.debug:
32     ch.setLevel(logging.DEBUG)
33 else:
34     ch.setLevel(logging.INFO)
35
36 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
37 ch.setFormatter(formatter)
38 logger.addHandler(ch)
39
40 REPO_PATH=os.environ['repos_dir']+'/functest/'
41 if not os.path.exists(REPO_PATH):
42     logger.error("Functest repository directory not found '%s'" % REPO_PATH)
43     exit(-1)
44 sys.path.append(REPO_PATH + "testcases/")
45
46 with open(REPO_PATH+"testcases/config_functest.yaml") as f:
47     functest_yaml = yaml.safe_load(f)
48 f.close()
49
50
51 """ global variables """
52 # Directories
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 = functest_yaml.get("rally").get("deployment_name")
63 RALLY_COMMIT = functest_yaml.get("general").get("repositories").get("rally_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         logger.info("Installing Rally...")
112         if not install_rally():
113             logger.error("There has been a problem while installing Rally.")
114             action_clean()
115             exit(-1)
116
117         # Create result folder under functest if necessary
118         if not os.path.exists(RALLY_RESULT_DIR):
119             os.makedirs(RALLY_RESULT_DIR)
120
121         exit(0)
122
123
124 def action_check():
125     """
126     Check if the functest environment is properly installed
127     """
128     errors_all = False
129     errors = False
130     logger.info("Checking current functest configuration...")
131
132     logger.debug("Checking script directories...")
133
134     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
135     for dir in dirs:
136         if not os.path.exists(dir):
137             logger.debug("The directory '%s' does NOT exist." % dir)
138             errors = True
139             errors_all = True
140         else:
141             logger.debug("   %s found" % dir)
142     if not errors:
143         logger.debug("...OK")
144     else:
145         logger.debug("...FAIL")
146
147
148     logger.debug("Checking Rally deployment...")
149     if not check_rally():
150         logger.debug("   Rally deployment NOT installed.")
151         errors_all = True
152         logger.debug("...FAIL")
153     else:
154         logger.debug("...OK")
155
156     logger.debug("Checking Image...")
157     errors = False
158     if not os.path.isfile(IMAGE_PATH):
159         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
160         errors = True
161         errors_all = True
162     else:
163         logger.debug("   Image file found in %s" % IMAGE_PATH)
164
165
166     if not errors:
167         logger.debug("...OK")
168     else:
169         logger.debug("...FAIL")
170
171     #TODO: check OLD environment setup
172     return not errors_all
173
174
175
176 def action_clean():
177     """
178     Clean the existing functest environment
179     """
180     logger.info("Removing current functest environment...")
181     if os.path.exists(RALLY_INSTALLATION_DIR):
182         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
183         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
184
185     if os.path.exists(RALLY_RESULT_DIR):
186         logger.debug("Removing Result directory")
187         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
188
189     logger.debug("Cleaning up the OpenStack deployment...")
190     cmd='python ' + REPO_PATH + \
191         '/testcases/VIM/OpenStack/CI/libraries/clean_openstack.py -d '
192     functest_utils.execute_command(cmd,logger)
193     logger.info("Functest environment clean!")
194
195
196
197 def install_rally():
198     if check_rally():
199         logger.info("Rally is already installed.")
200     else:
201         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
202         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
203         cmd = 'sudo ' + install_script
204         functest_utils.execute_command(cmd,logger)
205
206         logger.debug("Creating Rally environment...")
207         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
208         functest_utils.execute_command(cmd,logger)
209
210         logger.debug("Installing tempest...")
211         cmd = "rally verify install"
212         functest_utils.execute_command(cmd,logger)
213
214         cmd = "rally deployment check"
215         functest_utils.execute_command(cmd,logger)
216         #TODO: check that everything is 'Available' and warn if not
217
218         cmd = "rally show images"
219         functest_utils.execute_command(cmd,logger)
220
221         cmd = "rally show flavors"
222         functest_utils.execute_command(cmd,logger)
223
224     return True
225
226
227 def check_rally():
228     """
229     Check if Rally is installed and properly configured
230     """
231     if os.path.exists(RALLY_INSTALLATION_DIR):
232         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
233         FNULL = open(os.devnull, 'w');
234         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
235         logger.debug('   Executing command : {}'.format(cmd))
236         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
237         #if the command does not exist or there is no deployment
238         line = p.stdout.readline()
239         if line == "":
240             logger.debug("   Rally deployment NOT found")
241             return False
242         logger.debug("   Rally deployment found")
243         return True
244     else:
245         return False
246
247
248 def create_private_neutron_net(neutron):
249     neutron.format = 'json'
250     logger.info('Creating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
251     network_id = functest_utils. \
252         create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
253
254     if not network_id:
255         return False
256     logger.debug("Network '%s' created successfully" % network_id)
257
258     logger.info('Updating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
259     if functest_utils.update_neutron_net(neutron, network_id, shared=True):
260         logger.debug("Network '%s' updated successfully" % network_id)
261     else:
262         logger.info('Updating neutron network %s failed' % network_id)
263
264     logger.debug('Creating Subnet....')
265     subnet_id = functest_utils. \
266         create_neutron_subnet(neutron,
267                               NEUTRON_PRIVATE_SUBNET_NAME,
268                               NEUTRON_PRIVATE_SUBNET_CIDR,
269                               network_id)
270     if not subnet_id:
271         return False
272     logger.debug("Subnet '%s' created successfully" % subnet_id)
273     logger.debug('Creating Router...')
274     router_id = functest_utils. \
275         create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
276
277     if not router_id:
278         return False
279
280     logger.debug("Router '%s' created successfully" % router_id)
281     logger.debug('Adding router to subnet...')
282
283     result = functest_utils.add_interface_router(neutron, router_id, subnet_id)
284
285     if not result:
286         return False
287
288     logger.debug("Interface added successfully.")
289     network_dic = {'net_id': network_id,
290                    'subnet_id': subnet_id,
291                    'router_id': router_id}
292     return True
293
294
295 def main():
296     if not (args.action in actions):
297         logger.error('argument not valid')
298         exit(-1)
299
300
301     if not functest_utils.check_credentials():
302         logger.error("Please source the openrc credentials and run the script again.")
303         #TODO: source the credentials in this script
304         exit(-1)
305
306
307     if args.action == "start":
308         action_start()
309
310     if args.action == "check":
311         if action_check():
312             logger.info("Functest environment correctly installed")
313         else:
314             logger.info("Functest environment not found or faulty")
315
316     if args.action == "clean":
317         if args.force :
318             action_clean()
319         else :
320             while True:
321                 print("Are you sure? [y|n]")
322                 answer = raw_input("")
323                 if answer == "y":
324                     action_clean()
325                     break
326                 elif answer == "n":
327                     break
328                 else:
329                     print("Invalid option.")
330     exit(0)
331
332
333 if __name__ == '__main__':
334     main()
335