Fix bug clean_openstack if the function return a None
[functest.git] / testcases / VIM / OpenStack / CI / libraries / clean_openstack.py
1 #!/usr/bin/env python
2 #
3 # Description:
4 #   Cleans possible leftovers after running functest tests:
5 #       - Nova instances
6 #       - Glance images
7 #       - Cinder volumes
8 #       - Floating IPs
9 #       - Neutron networks, subnets and ports
10 #       - Routers
11 #       - Users and tenants
12 #
13 # Author:
14 #    jose.lausuch@ericsson.com
15 #
16
17 import argparse
18 import logging
19 import os
20 import re
21 import sys
22 import time
23
24 import novaclient.v2.client as novaclient
25 from neutronclient.v2_0 import client as neutronclient
26 from keystoneclient.v2_0 import client as keystoneclient
27 from cinderclient import client as cinderclient
28
29 parser = argparse.ArgumentParser()
30 parser.add_argument("repo_path", help="Path to the repository")
31 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
32 args = parser.parse_args()
33
34
35 """ logging configuration """
36 logger = logging.getLogger('clean_openstack')
37 logger.setLevel(logging.DEBUG)
38
39 ch = logging.StreamHandler()
40 if args.debug:
41     ch.setLevel(logging.DEBUG)
42 else:
43     ch.setLevel(logging.INFO)
44
45 sys.path.append(args.repo_path + "testcases/")
46 import functest_utils
47
48 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
49 ch.setFormatter(formatter)
50 logger.addHandler(ch)
51
52 default_images = ['TestVM']
53 default_networks = ['net04', 'net04_ext']
54 default_routers = ['router04']
55 default_users = ["heat", "heat-cfn", "cinder", "nova", "swift", "glance",
56                  "neutron", "admin", "fuel_stats_user"]
57 default_tenants = ["admin", "services","service"]
58 default_security_groups = ['default']
59
60 def separator():
61     logger.debug("-------------------------------------------")
62
63 def remove_instances(nova_client):
64     logger.info("Removing Nova instances...")
65     instances = functest_utils.get_instances(nova_client)
66     if instances is None or len(instances) == 0:
67         logger.debug("No instances found.")
68         return
69
70     for instance in instances:
71         instance_name = getattr(instance, 'name')
72         instance_id = getattr(instance, 'id')
73         logger.debug("Removing instance '%s', ID=%s ..." % (instance_name,instance_id))
74         if functest_utils.delete_instance(nova_client, instance_id):
75             logger.debug("  > Done!")
76         else:
77             logger.info("  > ERROR: There has been a problem removing the "
78                         "instance %s..." % instance_id)
79
80
81 def remove_images(nova_client):
82     logger.info("Removing Glance images...")
83     images = functest_utils.get_images(nova_client)
84     if images is None or len(images) == 0:
85         logger.debug("No images found.")
86         return
87
88     for image in images:
89         image_name = getattr(image, 'name')
90         image_id = getattr(image, 'id')
91         logger.debug("'%s', ID=%s " %(image_name,image_id))
92         if image_name not in default_images:
93             logger.debug("Removing image '%s', ID=%s ..." % (image_name,image_id))
94             if functest_utils.delete_glance_image(nova_client, image_id):
95                 logger.debug("  > Done!")
96             else:
97                 logger.info("  > ERROR: There has been a problem removing the"
98                             "image %s..." % image_id)
99         else:
100             logger.debug("   > this is a default image and will NOT be deleted.")
101
102
103 def remove_volumes(cinder_client, nova_client):
104     logger.info("Removing Cinder volumes...")
105
106     timeout = 50
107     while timeout > 0:
108         instances = functest_utils.get_instances(nova_client)
109         if instances is None or len(instances) == 0:
110             break
111         else:
112             logger.debug("Waiting for instances to be terminated...")
113             timeout -= 1
114             time.sleep(1)
115
116     volumes = functest_utils.get_volumes(cinder_client)
117     if len(volumes) == 0:
118         logger.debug("No volumes found.")
119         return
120
121     for volume in volumes:
122         volume_id = getattr(volume, 'id')
123         logger.debug("Removing cinder volume %s ..." % volume_id)
124         if functest_utils.delete_volume(cinder_client, volume_id):
125             logger.debug("  > Done!")
126         else:
127             logger.info("  > ERROR: There has been a problem removing the "
128                         "volume %s..." % volume_id)
129
130
131 def remove_floatingips(nova_client):
132     logger.info("Removing floating IPs...")
133     floatingips = functest_utils.get_floating_ips(nova_client)
134     if floatingips is None or len(floatingips) == 0:
135         logger.debug("No floating IPs found.")
136         return
137
138     for fip in floatingips:
139         fip_id = getattr(fip, 'id')
140         logger.debug("Removing floating IP %s ..." % fip_id)
141         if functest_utils.delete_floating_ip(nova_client, fip_id):
142             logger.debug("  > Done!")
143         else:
144             logger.info("  > ERROR: There has been a problem removing the "
145                         "floating IP %s..." % fip_id)
146
147
148 def remove_networks(neutron_client):
149     logger.info("Removing Neutron objects")
150     network_ids = []
151     networks = functest_utils.get_network_list(neutron_client)
152     if networks == None:
153         logger.debug("There are no networks in the deployment. ")
154         return
155
156     logger.debug("Existing networks:")
157     for network in networks:
158         net_id = network['id']
159         net_name = network['name']
160         logger.debug(" '%s', ID=%s " %(net_name,net_id))
161         if net_name not in default_networks:
162             logger.debug("    > this is not a default network and will be deleted.")
163             network_ids.append(net_id)
164         else:
165             logger.debug("   > this is a default network and will NOT be deleted.")
166
167
168     #remove interfaces router and delete ports
169     ports = functest_utils.get_port_list(neutron_client)
170     if ports is None:
171         logger.debug("There are no ports in the deployment. ")
172         return
173
174     for port in ports:
175         if port['network_id'] in network_ids:
176             port_id = port['id']
177             try:
178                 subnet_id = port['fixed_ips'][0]['subnet_id']
179             except:
180                 logger.info("  > ERROR: Error removing port %s." % port_id)
181                 print port
182                 print ports
183                 continue
184
185             router_id = port['device_id']
186             if port['device_owner'] == 'network:router_interface':
187                 logger.debug("Detaching port %s (subnet %s) from router %s ..."
188                              % (port_id,subnet_id,router_id))
189                 if functest_utils.remove_interface_router(neutron_client,
190                                                           router_id, subnet_id):
191                     time.sleep(5) # leave 5 seconds to detach before doing anything else
192                     logger.debug("  > Done!")
193                 else:
194                     logger.info("  > ERROR: There has been a problem removing the "
195                                 "interface %s from router %s..." %(subnet_id,router_id))
196                     #print port
197             else:
198                 logger.debug("Removing port %s ..." % port_id)
199                 if functest_utils.delete_neutron_port(neutron_client, port_id):
200                     logger.debug("  > Done!")
201                 else:
202                     logger.info("  > ERROR: There has been a problem removing the "
203                                 "port %s ..." %port_id)
204                     #print port
205
206     #remove routers
207     routers = functest_utils.get_router_list(neutron_client)
208     if routers is None:
209         logger.debug("There are no routers in the deployment. ")
210         return
211     for router in routers:
212         router_id = router['id']
213         router_name = router['name']
214         if router_name not in default_routers:
215             logger.debug("Checking '%s' with ID=(%s) ..." % (router_name,router_id))
216             if router['external_gateway_info'] != None:
217                 logger.debug("Router has gateway to external network. Removing link...")
218                 if functest_utils.remove_gateway_router(neutron_client, router_id):
219                     logger.debug("  > Done!")
220                 else:
221                     logger.info("  > ERROR: There has been a problem removing "
222                                 "the gateway...")
223                     #print router
224
225             else:
226                 logger.debug("Router is not connected to anything. Ready to remove...")
227             logger.debug("Removing router %s(%s) ..." % (router_name,router_id))
228             if functest_utils.delete_neutron_router(neutron_client, router_id):
229                 logger.debug("  > Done!")
230             else:
231                 logger.info("  > ERROR: There has been a problem removing the "
232                             "router '%s'(%s)..." % (router_name,router_id))
233
234
235     #remove networks
236     for net_id in network_ids:
237         logger.debug("Removing network %s ..." % net_id)
238         if functest_utils.delete_neutron_net(neutron_client, net_id):
239             logger.debug("  > Done!")
240         else:
241             logger.info("  > ERROR: There has been a problem removing the "
242                         "network %s..." % net_id)
243
244
245 def remove_security_groups(neutron_client):
246     logger.info("Removing Security groups...")
247     secgroups = functest_utils.get_security_groups(neutron_client)
248     if secgroups is None or len(secgroups) == 0:
249         logger.debug("No security groups found.")
250         return
251
252     for secgroup in secgroups:
253         secgroup_name = secgroup['name']
254         secgroup_id = secgroup['id']
255         logger.debug("'%s', ID=%s " %(secgroup_name,secgroup_id))
256         if secgroup_name not in default_security_groups:
257             logger.debug(" Removing '%s'..." % secgroup_name)
258             if functest_utils.delete_security_group(neutron_client, secgroup_id):
259                 logger.debug("  > Done!")
260             else:
261                 logger.info("  > ERROR: There has been a problem removing the "
262                             "security group %s..." % secgroup_id)
263         else:
264             logger.debug("   > this is a default security group and will NOT "
265                          "be deleted.")
266
267
268 def remove_users(keystone_client):
269     logger.info("Removing Users...")
270     users = functest_utils.get_users(keystone_client)
271     if users == None:
272         logger.debug("There are no users in the deployment. ")
273         return
274
275     for user in users:
276         user_name = getattr(user, 'name')
277         user_id = getattr(user, 'id')
278         logger.debug("'%s', ID=%s " %(user_name,user_id))
279         if user_name not in default_users:
280             logger.debug(" Removing '%s'..." % user_name)
281             if functest_utils.delete_user(keystone_client,user_id):
282                 logger.debug("  > Done!")
283             else:
284                 logger.info("  > ERROR: There has been a problem removing the "
285                             "user '%s'(%s)..." % (user_name,user_id))
286         else:
287             logger.debug("   > this is a default user and will NOT be deleted.")
288
289
290 def remove_tenants(keystone_client):
291     logger.info("Removing Tenants...")
292     tenants = functest_utils.get_tenants(keystone_client)
293     if tenants == None:
294         logger.debug("There are no tenants in the deployment. ")
295         return
296
297     for tenant in tenants:
298         tenant_name=getattr(tenant, 'name')
299         tenant_id = getattr(tenant, 'id')
300         logger.debug("'%s', ID=%s " %(tenant_name,tenant_id))
301         if tenant_name not in default_tenants:
302             logger.debug(" Removing '%s'..." % tenant_name)
303             if functest_utils.delete_tenant(keystone_client,tenant_id):
304                 logger.debug("  > Done!")
305             else:
306                 logger.info("  > ERROR: There has been a problem removing the "
307                             "tenant '%s'(%s)..." % (tenant_name,tenant_id))
308         else:
309             logger.debug("   > this is a default tenant and will NOT be deleted.")
310
311
312
313 def main():
314     creds_nova = functest_utils.get_credentials("nova")
315     nova_client = novaclient.Client(**creds_nova)
316
317     creds_neutron = functest_utils.get_credentials("neutron")
318     neutron_client = neutronclient.Client(**creds_neutron)
319
320     creds_keystone = functest_utils.get_credentials("keystone")
321     keystone_client = keystoneclient.Client(**creds_keystone)
322
323     creds_cinder = functest_utils.get_credentials("cinder")
324     #cinder_client = cinderclient.Client(**creds_cinder)
325     cinder_client = cinderclient.Client('1',creds_cinder['username'],
326                                         creds_cinder['api_key'],
327                                         creds_cinder['project_id'],
328                                         creds_cinder['auth_url'],
329                                         service_type="volume")
330
331     if not functest_utils.check_credentials():
332         logger.error("Please source the openrc credentials and run the script again.")
333         exit(-1)
334
335
336     remove_instances(nova_client)
337     separator()
338     remove_images(nova_client)
339     separator()
340     remove_volumes(cinder_client, nova_client)
341     separator()
342     remove_floatingips(nova_client)
343     separator()
344     remove_networks(neutron_client)
345     separator()
346     remove_security_groups(neutron_client)
347     separator()
348     remove_users(keystone_client)
349     separator()
350     remove_tenants(keystone_client)
351     separator()
352
353     exit(0)
354
355
356 if __name__ == '__main__':
357     main()