Add support for Promise test cases
[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         logger.info("Installing Ruby libraries for vIMS testcase...")
119         # Install ruby libraries for vims test-case
120         script = 'source /etc/profile.d/rvm.sh; '
121         script += 'cd ' + VIMS_TEST_DIR + '; '
122         script += 'rvm autolibs enable ;'
123         script += 'rvm install 1.9.3; '
124         script += 'rvm use 1.9.3;'
125         script += 'bundle install'
126
127         logger_debug = None
128         CI_DEBUG = os.environ.get("CI_DEBUG")
129         if CI_DEBUG == "true" or CI_DEBUG == "True":
130             logger_debug = logger
131
132         cmd = "/bin/bash -c '" + script + "'"
133         functest_utils.execute_command(cmd, logger = logger_debug, exit_on_error=False)
134
135
136         logger.info("Installing dependencies for Promise testcase...")
137         cmd = 'npm install -g yangforge'
138         functest_utils.execute_command(cmd,logger = logger_debug, exit_on_error=False)
139
140         cmd = 'npm install'
141         functest_utils.execute_command(cmd,logger = logger_debug, exit_on_error=False)
142
143         # Create result folder under functest if necessary
144         if not os.path.exists(RALLY_RESULT_DIR):
145             os.makedirs(RALLY_RESULT_DIR)
146
147         try:
148             logger.info("CI: Generate the list of executable tests.")
149             runnable_test = functest_utils.generateTestcaseList(functest_yaml)
150             logger.info("List of runnable tests generated: %s" % runnable_test)
151         except:
152             logger.error("Impossible to generate the list of runnable tests")
153
154         exit(0)
155
156
157 def action_check():
158     """
159     Check if the functest environment is properly installed
160     """
161     errors_all = False
162     errors = False
163     logger.info("Checking current functest configuration...")
164
165     logger.debug("Checking script directories...")
166
167     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
168     for dir in dirs:
169         if not os.path.exists(dir):
170             logger.debug("The directory '%s' does NOT exist." % dir)
171             errors = True
172             errors_all = True
173         else:
174             logger.debug("   %s found" % dir)
175     if not errors:
176         logger.debug("...OK")
177     else:
178         logger.debug("...FAIL")
179
180
181     logger.debug("Checking Rally deployment...")
182     if not check_rally():
183         logger.debug("   Rally deployment NOT installed.")
184         errors_all = True
185         logger.debug("...FAIL")
186     else:
187         logger.debug("...OK")
188
189     logger.debug("Checking Image...")
190     errors = False
191     if not os.path.isfile(IMAGE_PATH):
192         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
193         errors = True
194         errors_all = True
195     else:
196         logger.debug("   Image file found in %s" % IMAGE_PATH)
197
198
199     if not errors:
200         logger.debug("...OK")
201     else:
202         logger.debug("...FAIL")
203
204     #TODO: check OLD environment setup
205     return not errors_all
206
207
208
209 def action_clean():
210     """
211     Clean the existing functest environment
212     """
213     logger.info("Removing current functest environment...")
214     if os.path.exists(RALLY_INSTALLATION_DIR):
215         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
216         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
217
218     if os.path.exists(RALLY_RESULT_DIR):
219         logger.debug("Removing Result directory")
220         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
221
222     logger.debug("Cleaning up the OpenStack deployment...")
223     cmd='python ' + REPO_PATH + \
224         '/testcases/VIM/OpenStack/CI/libraries/clean_openstack.py --debug'
225     functest_utils.execute_command(cmd,logger)
226     logger.info("Functest environment clean!")
227
228
229
230 def install_rally():
231     if check_rally():
232         logger.info("Rally is already installed.")
233     else:
234         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
235         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
236         cmd = 'sudo ' + install_script
237         if os.environ.get("CI_DEBUG") == "false":
238             functest_utils.execute_command(cmd)
239         else:
240             functest_utils.execute_command(cmd,logger)
241
242         logger.debug("Creating Rally environment...")
243         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
244         functest_utils.execute_command(cmd,logger)
245
246         logger.debug("Installing tempest...")
247         cmd = "rally verify install"
248         functest_utils.execute_command(cmd,logger)
249
250         cmd = "rally deployment check"
251         functest_utils.execute_command(cmd,logger)
252         #TODO: check that everything is 'Available' and warn if not
253
254         cmd = "rally show images"
255         functest_utils.execute_command(cmd,logger)
256
257         cmd = "rally show flavors"
258         functest_utils.execute_command(cmd,logger)
259
260     return True
261
262
263 def check_rally():
264     """
265     Check if Rally is installed and properly configured
266     """
267     if os.path.exists(RALLY_INSTALLATION_DIR):
268         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
269         FNULL = open(os.devnull, 'w');
270         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
271         logger.debug('   Executing command : {}'.format(cmd))
272         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
273         #if the command does not exist or there is no deployment
274         line = p.stdout.readline()
275         if line == "":
276             logger.debug("   Rally deployment NOT found")
277             return False
278         logger.debug("   Rally deployment found")
279         return True
280     else:
281         return False
282
283
284 def create_private_neutron_net(neutron):
285     neutron.format = 'json'
286     logger.info('Creating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
287     network_id = functest_utils. \
288         create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
289
290     if not network_id:
291         return False
292     logger.debug("Network '%s' created successfully" % network_id)
293
294     logger.info('Updating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
295     if functest_utils.update_neutron_net(neutron, network_id, shared=True):
296         logger.debug("Network '%s' updated successfully" % network_id)
297     else:
298         logger.info('Updating neutron network %s failed' % network_id)
299
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