649d4f7ec3242f15e65065a0bb5bac32c13f7ee7
[functest.git] / 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 import argparse
11 import logging
12 import os
13 import shutil
14 import subprocess
15 import sys
16 import yaml
17
18 from neutronclient.v2_0 import client as neutronclient
19
20 import functest.utils.functest_utils as functest_utils
21 import functest.utils.openstack_utils as openstack_utils
22
23
24 actions = ['start', 'check', 'clean']
25 parser = argparse.ArgumentParser()
26 parser.add_argument("action", help="Possible actions are: "
27                     "'{d[0]}|{d[1]}|{d[2]}' ".format(d=actions))
28 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
29 parser.add_argument("-f", "--force", help="Force", action="store_true")
30 args = parser.parse_args()
31
32
33 """ logging configuration """
34 logger = logging.getLogger('config_functest')
35 logger.setLevel(logging.DEBUG)
36
37 ch = logging.StreamHandler()
38 if args.debug:
39     ch.setLevel(logging.DEBUG)
40 else:
41     ch.setLevel(logging.INFO)
42
43 formatter = logging.Formatter('%(asctime)s - %(name)s - '
44                               '%(levelname)s - %(message)s')
45 ch.setFormatter(formatter)
46 logger.addHandler(ch)
47
48 REPOS_DIR = os.environ['repos_dir']
49 FUNCTEST_REPO = REPOS_DIR + '/functest/'
50 if not os.path.exists(FUNCTEST_REPO):
51     logger.error("Functest repository directory not found '%s'"
52                  % FUNCTEST_REPO)
53     exit(-1)
54 sys.path.append(FUNCTEST_REPO + "testcases/")
55
56 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
57     functest_yaml = yaml.safe_load(f)
58 f.close()
59
60
61 """ global variables """
62 # Directories
63 RALLY_DIR = FUNCTEST_REPO + functest_yaml.get("general").get(
64     "directories").get("dir_rally")
65 RALLY_REPO_DIR = functest_yaml.get("general").get(
66     "directories").get("dir_repo_rally")
67 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get(
68     "directories").get("dir_rally_inst")
69 RALLY_RESULT_DIR = functest_yaml.get("general").get(
70     "directories").get("dir_rally_res")
71 TEMPEST_REPO_DIR = functest_yaml.get("general").get(
72     "directories").get("dir_repo_tempest")
73 VPING_DIR = FUNCTEST_REPO + functest_yaml.get("general").get(
74     "directories").get("dir_vping")
75 ODL_DIR = FUNCTEST_REPO + functest_yaml.get("general").get(
76     "directories").get("dir_odl")
77 DATA_DIR = functest_yaml.get("general").get(
78     "directories").get("dir_functest_data")
79
80 # Tempest/Rally configuration details
81 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
82
83 # Image (cirros)
84 IMAGE_FILE_NAME = functest_yaml.get("general").get("openstack").get(
85     "image_file_name")
86 IMAGE_PATH = DATA_DIR + "/" + IMAGE_FILE_NAME
87
88 # NEUTRON Private Network parameters
89 NEUTRON_PRIVATE_NET_NAME = functest_yaml.get("general").get(
90     "openstack").get("neutron_private_net_name")
91 NEUTRON_PRIVATE_SUBNET_NAME = functest_yaml.get("general").get(
92     "openstack").get("neutron_private_subnet_name")
93 NEUTRON_PRIVATE_SUBNET_CIDR = functest_yaml.get("general").get(
94     "openstack").get("neutron_private_subnet_cidr")
95 NEUTRON_ROUTER_NAME = functest_yaml.get("general").get(
96     "openstack").get("neutron_router_name")
97
98 creds_neutron = openstack_utils.get_credentials("neutron")
99 neutron_client = neutronclient.Client(**creds_neutron)
100
101
102 def action_start():
103     """
104     Start the functest environment installation
105     """
106     if not functest_utils.check_internet_connectivity():
107         logger.info("No Internet connectivity. "
108                     "This may affect some test case suites.")
109
110     if action_check():
111         logger.info("Functest environment already installed. Nothing to do.")
112         exit(0)
113
114     else:
115         # Clean in case there are left overs
116         logger.debug("Cleaning possible functest environment leftovers.")
117         action_clean()
118         logger.info("Starting installation of functest environment")
119
120         private_net = openstack_utils.get_private_net(neutron_client)
121         if private_net is None:
122             # If there is no private network in the deployment we create one
123             if not create_private_neutron_net(neutron_client):
124                 logger.error("There has been a problem while "
125                              "creating the functest network.")
126                 action_clean()
127                 exit(-1)
128         else:
129             logger.info("Private network '%s' already existing in "
130                         "the deployment." % private_net['name'])
131
132         logger.info("Installing Rally...")
133         if not install_rally():
134             logger.error("There has been a problem while installing Rally.")
135             action_clean()
136             exit(-1)
137
138         # Create result folder under functest if necessary
139         if not os.path.exists(RALLY_RESULT_DIR):
140             os.makedirs(RALLY_RESULT_DIR)
141
142         try:
143             logger.info("CI: Generate the list of executable tests.")
144             runnable_test = functest_utils.generateTestcaseList(functest_yaml)
145             logger.info("List of runnable tests generated: %s" % runnable_test)
146         except:
147             logger.error("Impossible to generate the list of runnable tests")
148
149         exit(0)
150
151
152 def action_check():
153     """
154     Check if the functest environment is properly installed
155     """
156     errors_all = False
157     logger.info("Checking current functest configuration...")
158
159     logger.debug("Checking script directories...")
160
161     dirs = [RALLY_DIR, RALLY_INSTALLATION_DIR, VPING_DIR, ODL_DIR]
162     for dir in dirs:
163         if not os.path.exists(dir):
164             logger.debug("   %s NOT found" % dir)
165             errors_all = True
166         else:
167             logger.debug("   %s found" % dir)
168
169     logger.debug("Checking Rally deployment...")
170     if not check_rally():
171         logger.debug("   Rally deployment NOT installed.")
172         errors_all = True
173
174     logger.debug("Checking Image...")
175     if not os.path.isfile(IMAGE_PATH):
176         logger.debug("   Image file '%s' NOT found." % IMAGE_PATH)
177         errors_all = True
178     else:
179         logger.debug("   Image file found in %s" % IMAGE_PATH)
180
181     # TODO: check OLD environment setup
182     return not errors_all
183
184
185 def action_clean():
186     """
187     Clean the existing functest environment
188     """
189     logger.info("Removing current functest environment...")
190     if os.path.exists(RALLY_INSTALLATION_DIR):
191         logger.debug("Removing Rally installation directory %s"
192                      % 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.info("Functest environment clean!")
200
201
202 def install_rally():
203     if check_rally():
204         logger.info("Rally is already installed.")
205     else:
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 from existing repo...")
211         cmd = ("rally verify install --source " + TEMPEST_REPO_DIR +
212                " --system-wide")
213         functest_utils.execute_command(cmd, logger)
214
215         cmd = "rally deployment check"
216         functest_utils.execute_command(cmd, logger)
217         # TODO: check that everything is 'Available' and warn if not
218
219         cmd = "rally show images"
220         functest_utils.execute_command(cmd, logger)
221
222         cmd = "rally show flavors"
223         functest_utils.execute_command(cmd, logger)
224
225     return True
226
227
228 def check_rally():
229     """
230     Check if Rally is installed and properly configured
231     """
232     if os.path.exists(RALLY_INSTALLATION_DIR):
233         logger.debug("   Rally installation directory found in %s"
234                      % RALLY_INSTALLATION_DIR)
235         FNULL = open(os.devnull, 'w')
236         cmd = "rally deployment list | grep " + DEPLOYMENT_MAME
237         logger.debug('   Executing command : {}'.format(cmd))
238         p = subprocess.Popen(cmd, shell=True,
239                              stdout=subprocess.PIPE, stderr=FNULL)
240         # if the command does not exist or there is no deployment
241         line = p.stdout.readline()
242         if line == "":
243             logger.debug("   Rally deployment NOT found")
244             return False
245         logger.debug("   Rally deployment found")
246         return True
247     else:
248         return False
249
250
251 def create_private_neutron_net(neutron):
252     neutron.format = 'json'
253     logger.info("Creating network '%s'..." % NEUTRON_PRIVATE_NET_NAME)
254     network_id = openstack_utils.create_neutron_net(
255         neutron, NEUTRON_PRIVATE_NET_NAME)
256
257     if not network_id:
258         return False
259     logger.debug("Network '%s' created successfully." % network_id)
260
261     logger.info("Updating network '%s' with shared=True..."
262                 % NEUTRON_PRIVATE_NET_NAME)
263     if openstack_utils.update_neutron_net(neutron, network_id, shared=True):
264         logger.debug("Network '%s' updated successfully." % network_id)
265     else:
266         logger.info("Updating neutron network '%s' failed" % network_id)
267
268     logger.info("Creating Subnet....")
269     subnet_id = openstack_utils.create_neutron_subnet(
270         neutron, NEUTRON_PRIVATE_SUBNET_NAME, NEUTRON_PRIVATE_SUBNET_CIDR,
271         network_id)
272     if not subnet_id:
273         return False
274     logger.debug("Subnet '%s' created successfully." % subnet_id)
275     logger.info("Creating Router...")
276     router_id = openstack_utils.create_neutron_router(neutron,
277                                                       NEUTRON_ROUTER_NAME)
278
279     if not router_id:
280         return False
281
282     logger.debug("Router '%s' created successfully." % router_id)
283     logger.info("Adding router to subnet...")
284
285     result = openstack_utils.add_interface_router(neutron,
286                                                   router_id,
287                                                   subnet_id)
288
289     if not result:
290         return False
291
292     logger.debug("Interface added successfully.")
293     return True
294
295
296 def main():
297     if not (args.action in actions):
298         logger.error('argument not valid')
299         exit(-1)
300
301     if not openstack_utils.check_credentials():
302         logger.error("Please source the openrc credentials and "
303                      "run the script again.")
304         # TODO: source the credentials in this script
305         exit(-1)
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()