Remove all the repo handling in prepare_env
[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 import openstack_utils
14 from git import Repo
15 from os import stat
16 from pwd import getpwuid
17 from neutronclient.v2_0 import client as neutronclient
18
19 actions = ['start', 'check', 'clean']
20 parser = argparse.ArgumentParser()
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 REPOS_DIR=os.environ['repos_dir']
42 FUNCTEST_REPO=REPOS_DIR+'/functest/'
43 if not os.path.exists(FUNCTEST_REPO):
44     logger.error("Functest repository directory not found '%s'" % FUNCTEST_REPO)
45     exit(-1)
46 sys.path.append(FUNCTEST_REPO + "testcases/")
47
48 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
49     functest_yaml = yaml.safe_load(f)
50 f.close()
51
52
53 """ global variables """
54 # Directories
55 RALLY_DIR = FUNCTEST_REPO + 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 TEMPEST_REPO_DIR = functest_yaml.get("general").get("directories").get("dir_repo_tempest")
60 VPING_DIR = FUNCTEST_REPO + functest_yaml.get("general").get("directories").get("dir_vping")
61 ODL_DIR = FUNCTEST_REPO + functest_yaml.get("general").get("directories").get("dir_odl")
62 DATA_DIR = functest_yaml.get("general").get("directories").get("dir_functest_data")
63
64 # Tempest/Rally configuration details
65 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
66 RALLY_COMMIT = functest_yaml.get("general").get("repositories").get("rally_commit")
67
68 #Image (cirros)
69 IMAGE_FILE_NAME = functest_yaml.get("general").get("openstack").get("image_file_name")
70 IMAGE_PATH = DATA_DIR + "/" + IMAGE_FILE_NAME
71
72 # NEUTRON Private Network parameters
73 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("general"). \
74     get("openstack").get("neutron_private_net_name")
75 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("general"). \
76     get("openstack").get("neutron_private_subnet_name")
77 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("general"). \
78     get("openstack").get("neutron_private_subnet_cidr")
79 NEUTRON_ROUTER_NAME = functest_yaml.get("general"). \
80     get("openstack").get("neutron_router_name")
81
82 creds_neutron = openstack_utils.get_credentials("neutron")
83 neutron_client = neutronclient.Client(**creds_neutron)
84
85 def action_start():
86     """
87     Start the functest environment installation
88     """
89     if not functest_utils.check_internet_connectivity():
90         logger.info("No Internet connectivity. This may affect some test case suites.")
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 = openstack_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         # Create result folder under functest if necessary
120         if not os.path.exists(RALLY_RESULT_DIR):
121             os.makedirs(RALLY_RESULT_DIR)
122
123         try:
124             logger.info("CI: Generate the list of executable tests.")
125             runnable_test = functest_utils.generateTestcaseList(functest_yaml)
126             logger.info("List of runnable tests generated: %s" % runnable_test)
127         except:
128             logger.error("Impossible to generate the list of runnable tests")
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("   %s NOT found" % dir)
147             errors = True
148             errors_all = True
149         else:
150             logger.debug("   %s found" % dir)
151
152     logger.debug("Checking Rally deployment...")
153     if not check_rally():
154         logger.debug("   Rally deployment NOT installed.")
155         errors_all = True
156
157     logger.debug("Checking Image...")
158     errors = False
159     if not os.path.isfile(IMAGE_PATH):
160         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
161         errors = True
162         errors_all = True
163     else:
164         logger.debug("   Image file found in %s" % IMAGE_PATH)
165
166
167     #TODO: check OLD environment setup
168     return not errors_all
169
170
171
172 def action_clean():
173     """
174     Clean the existing functest environment
175     """
176     logger.info("Removing current functest environment...")
177     if os.path.exists(RALLY_INSTALLATION_DIR):
178         logger.debug("Removing Rally installation directory %s" % RALLY_INSTALLATION_DIR)
179         shutil.rmtree(RALLY_INSTALLATION_DIR,ignore_errors=True)
180
181     if os.path.exists(RALLY_RESULT_DIR):
182         logger.debug("Removing Result directory")
183         shutil.rmtree(RALLY_RESULT_DIR,ignore_errors=True)
184
185     logger.info("Functest environment clean!")
186
187
188
189 def install_rally():
190     if check_rally():
191         logger.info("Rally is already installed.")
192     else:
193         logger.debug("Creating Rally environment...")
194         cmd = "rally deployment create --fromenv --name="+DEPLOYMENT_MAME
195         functest_utils.execute_command(cmd,logger)
196
197         logger.debug("Installing tempest from existing repo...")
198         cmd = "rally verify install --source " + TEMPEST_REPO_DIR + " --system-wide"
199         functest_utils.execute_command(cmd,logger)
200
201         cmd = "rally deployment check"
202         functest_utils.execute_command(cmd,logger)
203         #TODO: check that everything is 'Available' and warn if not
204
205         cmd = "rally show images"
206         functest_utils.execute_command(cmd,logger)
207
208         cmd = "rally show flavors"
209         functest_utils.execute_command(cmd,logger)
210
211     return True
212
213 def check_rally():
214     """
215     Check if Rally is installed and properly configured
216     """
217     if os.path.exists(RALLY_INSTALLATION_DIR):
218         logger.debug("   Rally installation directory found in %s" % RALLY_INSTALLATION_DIR)
219         FNULL = open(os.devnull, 'w');
220         cmd="rally deployment list | grep "+DEPLOYMENT_MAME
221         logger.debug('   Executing command : {}'.format(cmd))
222         p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=FNULL);
223         #if the command does not exist or there is no deployment
224         line = p.stdout.readline()
225         if line == "":
226             logger.debug("   Rally deployment NOT found")
227             return False
228         logger.debug("   Rally deployment found")
229         return True
230     else:
231         return False
232
233
234 def create_private_neutron_net(neutron):
235     neutron.format = 'json'
236     logger.info("Creating network '%s'..." % NEUTRON_PRIVATE_NET_NAME)
237     network_id = openstack_utils. \
238         create_neutron_net(neutron, NEUTRON_PRIVATE_NET_NAME)
239
240     if not network_id:
241         return False
242     logger.debug("Network '%s' created successfully." % network_id)
243
244     logger.info("Updating network '%s' with shared=True..." % NEUTRON_PRIVATE_NET_NAME)
245     if openstack_utils.update_neutron_net(neutron, network_id, shared=True):
246         logger.debug("Network '%s' updated successfully." % network_id)
247     else:
248         logger.info("Updating neutron network '%s' failed" % network_id)
249
250     logger.info("Creating Subnet....")
251     subnet_id = openstack_utils. \
252         create_neutron_subnet(neutron,
253                               NEUTRON_PRIVATE_SUBNET_NAME,
254                               NEUTRON_PRIVATE_SUBNET_CIDR,
255                               network_id)
256     if not subnet_id:
257         return False
258     logger.debug("Subnet '%s' created successfully." % subnet_id)
259     logger.info("Creating Router...")
260     router_id = openstack_utils. \
261         create_neutron_router(neutron, NEUTRON_ROUTER_NAME)
262
263     if not router_id:
264         return False
265
266     logger.debug("Router '%s' created successfully." % router_id)
267     logger.info("Adding router to subnet...")
268
269     result = openstack_utils.add_interface_router(neutron, router_id, subnet_id)
270
271     if not result:
272         return False
273
274     logger.debug("Interface added successfully.")
275     network_dic = {'net_id': network_id,
276                    'subnet_id': subnet_id,
277                    'router_id': router_id}
278     return True
279
280
281 def main():
282     if not (args.action in actions):
283         logger.error('argument not valid')
284         exit(-1)
285
286
287     if not openstack_utils.check_credentials():
288         logger.error("Please source the openrc credentials and run the script again.")
289         #TODO: source the credentials in this script
290         exit(-1)
291
292
293     if args.action == "start":
294         action_start()
295
296     if args.action == "check":
297         if action_check():
298             logger.info("Functest environment correctly installed")
299         else:
300             logger.info("Functest environment not found or faulty")
301
302     if args.action == "clean":
303         if args.force :
304             action_clean()
305         else :
306             while True:
307                 print("Are you sure? [y|n]")
308                 answer = raw_input("")
309                 if answer == "y":
310                     action_clean()
311                     break
312                 elif answer == "n":
313                     break
314                 else:
315                     print("Invalid option.")
316     exit(0)
317
318
319 if __name__ == '__main__':
320     main()
321