Merge "Create volume type before running Rally 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("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("/home/opnfv/functest/conf/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 VIMS_TEST_DIR = functest_yaml.get("general").get("directories").get("dir_repo_vims_test")
59 ODL_DIR = REPO_PATH + functest_yaml.get("general").get("directories").get("dir_odl")
60 DATA_DIR = functest_yaml.get("general").get("directories").get("dir_functest_data")
61
62 # Tempest/Rally configuration details
63 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
64 RALLY_COMMIT = functest_yaml.get("general").get("repositories").get("rally_commit")
65
66 #Image (cirros)
67 IMAGE_FILE_NAME = functest_yaml.get("general").get("openstack").get("image_file_name")
68 IMAGE_PATH = DATA_DIR + "/" + IMAGE_FILE_NAME
69
70 # NEUTRON Private Network parameters
71 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("general"). \
72     get("openstack").get("neutron_private_net_name")
73 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("general"). \
74     get("openstack").get("neutron_private_subnet_name")
75 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("general"). \
76     get("openstack").get("neutron_private_subnet_cidr")
77 NEUTRON_ROUTER_NAME = functest_yaml.get("general"). \
78     get("openstack").get("neutron_router_name")
79
80 creds_neutron = functest_utils.get_credentials("neutron")
81 neutron_client = neutronclient.Client(**creds_neutron)
82
83 def action_start():
84     """
85     Start the functest environment installation
86     """
87     if not functest_utils.check_internet_connectivity():
88         logger.error("There is no Internet connectivity. Please check the network configuration.")
89         exit(-1)
90
91     if action_check():
92         logger.info("Functest environment already installed. Nothing to do.")
93         exit(0)
94
95     else:
96         # Clean in case there are left overs
97         logger.debug("Cleaning possible functest environment leftovers.")
98         action_clean()
99         logger.info("Starting installation of functest environment")
100
101         private_net = functest_utils.get_private_net(neutron_client)
102         if private_net is None:
103             # If there is no private network in the deployment we create one
104             if not create_private_neutron_net(neutron_client):
105                 logger.error("There has been a problem while creating the functest network.")
106                 action_clean()
107                 exit(-1)
108         else:
109             logger.info("Private network '%s' already existing in the deployment."
110                  % private_net['name'])
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         # Install ruby libraries for vims test-case
119         script = 'source /etc/profile.d/rvm.sh; '
120         script += 'cd ' + VIMS_TEST_DIR + '; '
121         script += 'rvm use system;'
122         script += 'bundle install'
123
124         cmd = "/bin/bash -c '" + script + "'"
125         functest_utils.execute_command(cmd,logger)
126
127         # Create result folder under functest if necessary
128         if not os.path.exists(RALLY_RESULT_DIR):
129             os.makedirs(RALLY_RESULT_DIR)
130
131         exit(0)
132
133
134 def action_check():
135     """
136     Check if the functest environment is properly installed
137     """
138     errors_all = False
139     errors = False
140     logger.info("Checking current functest configuration...")
141
142     logger.debug("Checking script directories...")
143
144     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
145     for dir in dirs:
146         if not os.path.exists(dir):
147             logger.debug("The directory '%s' does NOT exist." % dir)
148             errors = True
149             errors_all = True
150         else:
151             logger.debug("   %s found" % dir)
152     if not errors:
153         logger.debug("...OK")
154     else:
155         logger.debug("...FAIL")
156
157
158     logger.debug("Checking Rally deployment...")
159     if not check_rally():
160         logger.debug("   Rally deployment NOT installed.")
161         errors_all = True
162         logger.debug("...FAIL")
163     else:
164         logger.debug("...OK")
165
166     logger.debug("Checking Image...")
167     errors = False
168     if not os.path.isfile(IMAGE_PATH):
169         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
170         errors = True
171         errors_all = True
172     else:
173         logger.debug("   Image file found in %s" % IMAGE_PATH)
174
175
176     if not errors:
177         logger.debug("...OK")
178     else:
179         logger.debug("...FAIL")
180
181     #TODO: check OLD environment setup
182     return not errors_all
183
184
185
186 def action_clean():
187     """
188     Clean the existing functest environment
189     """
190     logger.info("Removing current functest environment...")
191     if os.path.exists(RALLY_INSTALLATION_DIR):
192         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
193         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
194
195     if os.path.exists(RALLY_RESULT_DIR):
196         logger.debug("Removing Result directory")
197         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
198
199     logger.debug("Cleaning up the OpenStack deployment...")
200     cmd='python ' + REPO_PATH + \
201         '/testcases/VIM/OpenStack/CI/libraries/clean_openstack.py -d '
202     functest_utils.execute_command(cmd,logger)
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 check_rally():
238     """
239     Check if Rally is installed and properly configured
240     """
241     if os.path.exists(RALLY_INSTALLATION_DIR):
242         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
243         FNULL = open(os.devnull, 'w');
244         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
245         logger.debug('   Executing command : {}'.format(cmd))
246         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
247         #if the command does not exist or there is no deployment
248         line = p.stdout.readline()
249         if line == "":
250             logger.debug("   Rally deployment NOT found")
251             return False
252         logger.debug("   Rally deployment found")
253         return True
254     else:
255         return False
256
257
258 def create_private_neutron_net(neutron):
259     neutron.format = 'json'
260     logger.info('Creating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
261     network_id = functest_utils. \
262         create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
263
264     if not network_id:
265         return False
266     logger.debug("Network '%s' created successfully" % network_id)
267
268     logger.info('Updating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
269     if functest_utils.update_neutron_net(neutron, network_id, shared=True):
270         logger.debug("Network '%s' updated successfully" % network_id)
271     else:
272         logger.info('Updating neutron network %s failed' % network_id)
273
274     logger.debug('Creating Subnet....')
275     subnet_id = functest_utils. \
276         create_neutron_subnet(neutron,
277                               NEUTRON_PRIVATE_SUBNET_NAME,
278                               NEUTRON_PRIVATE_SUBNET_CIDR,
279                               network_id)
280     if not subnet_id:
281         return False
282     logger.debug("Subnet '%s' created successfully" % subnet_id)
283     logger.debug('Creating Router...')
284     router_id = functest_utils. \
285         create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
286
287     if not router_id:
288         return False
289
290     logger.debug("Router '%s' created successfully" % router_id)
291     logger.debug('Adding router to subnet...')
292
293     result = functest_utils.add_interface_router(neutron, router_id, subnet_id)
294
295     if not result:
296         return False
297
298     logger.debug("Interface added successfully.")
299     network_dic = {'net_id': network_id,
300                    'subnet_id': subnet_id,
301                    'router_id': router_id}
302     return True
303
304
305 def main():
306     if not (args.action in actions):
307         logger.error('argument not valid')
308         exit(-1)
309
310
311     if not functest_utils.check_credentials():
312         logger.error("Please source the openrc credentials and run the script again.")
313         #TODO: source the credentials in this script
314         exit(-1)
315
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