Add copy of packages.json to the features path before running npm install
[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 REPOS_DIR=os.environ['repos_dir']
41 FUNCTEST_REPO=REPOS_DIR+'/functest/'
42 if not os.path.exists(FUNCTEST_REPO):
43     logger.error("Functest repository directory not found '%s'" % FUNCTEST_REPO)
44     exit(-1)
45 sys.path.append(FUNCTEST_REPO + "testcases/")
46
47 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
48     functest_yaml = yaml.safe_load(f)
49 f.close()
50
51
52 """ global variables """
53 # Directories
54 RALLY_DIR = FUNCTEST_REPO + functest_yaml.get("general").get("directories").get("dir_rally")
55 RALLY_REPO_DIR = functest_yaml.get("general").get("directories").get("dir_repo_rally")
56 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get("dir_rally_inst")
57 RALLY_RESULT_DIR = functest_yaml.get("general").get("directories").get("dir_rally_res")
58 VPING_DIR = FUNCTEST_REPO + functest_yaml.get("general").get("directories").get("dir_vping")
59 VIMS_TEST_DIR = functest_yaml.get("general").get("directories").get("dir_repo_vims_test")
60 ODL_DIR = FUNCTEST_REPO + 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 = functest_yaml.get("rally").get("deployment_name")
65 RALLY_COMMIT = functest_yaml.get("general").get("repositories").get("rally_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         logger.info("Installing Rally...")
114         if not install_rally():
115             logger.error("There has been a problem while installing Rally.")
116             action_clean()
117             exit(-1)
118
119         logger.info("Installing Ruby libraries for vIMS testcase...")
120         # Install ruby libraries for vims test-case
121         script = 'source /etc/profile.d/rvm.sh; '
122         script += 'cd ' + VIMS_TEST_DIR + '; '
123         script += 'rvm autolibs enable ;'
124         script += 'rvm install 1.9.3; '
125         script += 'rvm use 1.9.3;'
126         script += 'bundle install'
127
128         logger_debug = None
129         CI_DEBUG = os.environ.get("CI_DEBUG")
130         if CI_DEBUG == "true" or CI_DEBUG == "True":
131             logger_debug = logger
132
133         cmd = "/bin/bash -c '" + script + "'"
134         functest_utils.execute_command(cmd, logger = logger_debug, exit_on_error=False)
135
136
137         logger.info("Installing dependencies for Promise testcase...")
138         cmd = 'npm install -g yangforge'
139         functest_utils.execute_command(cmd,logger = logger_debug, exit_on_error=False)
140
141         shutil.copy2(REPOS_DIR+'/promise/package.json',FUNCTEST_REPO+'/testcases/features/package.json')
142         cmd = 'npm install'
143         functest_utils.execute_command(cmd,logger = logger_debug, exit_on_error=False)
144
145         # Create result folder under functest if necessary
146         if not os.path.exists(RALLY_RESULT_DIR):
147             os.makedirs(RALLY_RESULT_DIR)
148
149         try:
150             logger.info("CI: Generate the list of executable tests.")
151             runnable_test = functest_utils.generateTestcaseList(functest_yaml)
152             logger.info("List of runnable tests generated: %s" % runnable_test)
153         except:
154             logger.error("Impossible to generate the list of runnable tests")
155
156         exit(0)
157
158
159 def action_check():
160     """
161     Check if the functest environment is properly installed
162     """
163     errors_all = False
164     errors = False
165     logger.info("Checking current functest configuration...")
166
167     logger.debug("Checking script directories...")
168
169     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
170     for dir in dirs:
171         if not os.path.exists(dir):
172             logger.debug("The directory '%s' does NOT exist." % dir)
173             errors = True
174             errors_all = True
175         else:
176             logger.debug("   %s found" % dir)
177     if not errors:
178         logger.debug("...OK")
179     else:
180         logger.debug("...FAIL")
181
182
183     logger.debug("Checking Rally deployment...")
184     if not check_rally():
185         logger.debug("   Rally deployment NOT installed.")
186         errors_all = True
187         logger.debug("...FAIL")
188     else:
189         logger.debug("...OK")
190
191     logger.debug("Checking Image...")
192     errors = False
193     if not os.path.isfile(IMAGE_PATH):
194         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
195         errors = True
196         errors_all = True
197     else:
198         logger.debug("   Image file found in %s" % IMAGE_PATH)
199
200
201     if not errors:
202         logger.debug("...OK")
203     else:
204         logger.debug("...FAIL")
205
206     #TODO: check OLD environment setup
207     return not errors_all
208
209
210
211 def action_clean():
212     """
213     Clean the existing functest environment
214     """
215     logger.info("Removing current functest environment...")
216     if os.path.exists(RALLY_INSTALLATION_DIR):
217         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
218         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
219
220     if os.path.exists(RALLY_RESULT_DIR):
221         logger.debug("Removing Result directory")
222         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
223
224     logger.debug("Cleaning up the OpenStack deployment...")
225     cmd='python ' + FUNCTEST_REPO + \
226         '/testcases/VIM/OpenStack/CI/libraries/clean_openstack.py --debug'
227     functest_utils.execute_command(cmd,logger)
228     logger.info("Functest environment clean!")
229
230
231
232 def install_rally():
233     if check_rally():
234         logger.info("Rally is already installed.")
235     else:
236         logger.debug("Executing %s/install_rally.sh..." %RALLY_REPO_DIR)
237         install_script = RALLY_REPO_DIR + "/install_rally.sh --yes"
238         cmd = 'sudo ' + install_script
239         if os.environ.get("CI_DEBUG") == "false":
240             functest_utils.execute_command(cmd)
241         else:
242             functest_utils.execute_command(cmd,logger)
243
244         logger.debug("Creating Rally environment...")
245         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
246         functest_utils.execute_command(cmd,logger)
247
248         logger.debug("Installing tempest...")
249         cmd = "rally verify install"
250         functest_utils.execute_command(cmd,logger)
251
252         cmd = "rally deployment check"
253         functest_utils.execute_command(cmd,logger)
254         #TODO: check that everything is 'Available' and warn if not
255
256         cmd = "rally show images"
257         functest_utils.execute_command(cmd,logger)
258
259         cmd = "rally show flavors"
260         functest_utils.execute_command(cmd,logger)
261
262     return True
263
264
265 def check_rally():
266     """
267     Check if Rally is installed and properly configured
268     """
269     if os.path.exists(RALLY_INSTALLATION_DIR):
270         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
271         FNULL = open(os.devnull, 'w');
272         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
273         logger.debug('   Executing command : {}'.format(cmd))
274         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
275         #if the command does not exist or there is no deployment
276         line = p.stdout.readline()
277         if line == "":
278             logger.debug("   Rally deployment NOT found")
279             return False
280         logger.debug("   Rally deployment found")
281         return True
282     else:
283         return False
284
285
286 def create_private_neutron_net(neutron):
287     neutron.format = 'json'
288     logger.info('Creating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
289     network_id = functest_utils. \
290         create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
291
292     if not network_id:
293         return False
294     logger.debug("Network '%s' created successfully" % network_id)
295
296     logger.info('Updating neutron network %s...' % NEUTRON_PRIVATE_NET_NAME)
297     if functest_utils.update_neutron_net(neutron, network_id, shared=True):
298         logger.debug("Network '%s' updated successfully" % network_id)
299     else:
300         logger.info('Updating neutron network %s failed' % network_id)
301
302     logger.debug('Creating Subnet....')
303     subnet_id = functest_utils. \
304         create_neutron_subnet(neutron,
305                               NEUTRON_PRIVATE_SUBNET_NAME,
306                               NEUTRON_PRIVATE_SUBNET_CIDR,
307                               network_id)
308     if not subnet_id:
309         return False
310     logger.debug("Subnet '%s' created successfully" % subnet_id)
311     logger.debug('Creating Router...')
312     router_id = functest_utils. \
313         create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
314
315     if not router_id:
316         return False
317
318     logger.debug("Router '%s' created successfully" % router_id)
319     logger.debug('Adding router to subnet...')
320
321     result = functest_utils.add_interface_router(neutron, router_id, subnet_id)
322
323     if not result:
324         return False
325
326     logger.debug("Interface added successfully.")
327     network_dic = {'net_id': network_id,
328                    'subnet_id': subnet_id,
329                    'router_id': router_id}
330     return True
331
332
333 def main():
334     if not (args.action in actions):
335         logger.error('argument not valid')
336         exit(-1)
337
338
339     if not functest_utils.check_credentials():
340         logger.error("Please source the openrc credentials and run the script again.")
341         #TODO: source the credentials in this script
342         exit(-1)
343
344
345     if args.action == "start":
346         action_start()
347
348     if args.action == "check":
349         if action_check():
350             logger.info("Functest environment correctly installed")
351         else:
352             logger.info("Functest environment not found or faulty")
353
354     if args.action == "clean":
355         if args.force :
356             action_clean()
357         else :
358             while True:
359                 print("Are you sure? [y|n]")
360                 answer = raw_input("")
361                 if answer == "y":
362                     action_clean()
363                     break
364                 elif answer == "n":
365                     break
366                 else:
367                     print("Invalid option.")
368     exit(0)
369
370
371 if __name__ == '__main__':
372     main()
373