Wait for floatingips to be released in clean_openstack script
[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', 'functest-net']
54 default_routers = ['router04']
55 default_users = ["heat", "heat-cfn", "cinder", "nova", "swift", "glance",
56                  "neutron", "admin", "fuel_stats_user", "quantum", "heat-cfn_heat",
57                  "ceilometer", "cinder_cinderv2"]
58 default_tenants = ["admin", "services","service"]
59 default_security_groups = ['default']
60
61 def separator():
62     logger.debug("-------------------------------------------")
63
64 def remove_instances(nova_client):
65     logger.info("Removing Nova instances...")
66     instances = functest_utils.get_instances(nova_client)
67     if instances is None or len(instances) == 0:
68         logger.debug("No instances found.")
69         return
70
71     for instance in instances:
72         instance_name = getattr(instance, 'name')
73         instance_id = getattr(instance, 'id')
74         logger.debug("Removing instance '%s', ID=%s ..." % (instance_name,instance_id))
75         if functest_utils.delete_instance(nova_client, instance_id):
76             logger.debug("  > Done!")
77         else:
78             logger.info("  > ERROR: There has been a problem removing the "
79                         "instance %s..." % instance_id)
80
81     timeout = 50
82     while timeout > 0:
83         instances = functest_utils.get_instances(nova_client)
84         if instances is None or len(instances) == 0:
85             break
86         else:
87             logger.debug("Waiting for instances to be terminated...")
88             timeout -= 1
89             time.sleep(1)
90
91
92 def remove_images(nova_client):
93     logger.info("Removing Glance images...")
94     images = functest_utils.get_images(nova_client)
95     if images is None or len(images) == 0:
96         logger.debug("No images found.")
97         return
98
99     for image in images:
100         image_name = getattr(image, 'name')
101         image_id = getattr(image, 'id')
102         logger.debug("'%s', ID=%s " %(image_name,image_id))
103         if image_name not in default_images:
104             logger.debug("Removing image '%s', ID=%s ..." % (image_name,image_id))
105             if functest_utils.delete_glance_image(nova_client, image_id):
106                 logger.debug("  > Done!")
107             else:
108                 logger.info("  > ERROR: There has been a problem removing the"
109                             "image %s..." % image_id)
110         else:
111             logger.debug("   > this is a default image and will NOT be deleted.")
112
113
114 def remove_volumes(cinder_client):
115     logger.info("Removing Cinder volumes...")
116     volumes = functest_utils.get_volumes(cinder_client)
117     if volumes is None or 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     timeout = 50
148     while timeout > 0:
149         floatingips = functest_utils.get_floating_ips(nova_client)
150         if floatingips is None or len(floatingips) == 0:
151             break
152         else:
153             logger.debug("Waiting for floating ips to be released...")
154             timeout -= 1
155             time.sleep(1)
156
157
158 def remove_networks(neutron_client):
159     logger.info("Removing Neutron objects")
160     network_ids = []
161     networks = functest_utils.get_network_list(neutron_client)
162     if networks == None:
163         logger.debug("There are no networks in the deployment. ")
164         return
165
166     logger.debug("Existing networks:")
167     for network in networks:
168         net_id = network['id']
169         net_name = network['name']
170         logger.debug(" '%s', ID=%s " %(net_name,net_id))
171         if net_name not in default_networks:
172             logger.debug("    > this is not a default network and will be deleted.")
173             network_ids.append(net_id)
174         else:
175             logger.debug("   > this is a default network and will NOT be deleted.")
176
177
178     #remove interfaces router and delete ports
179     ports = functest_utils.get_port_list(neutron_client)
180     if ports is None:
181         logger.debug("There are no ports in the deployment. ")
182         return
183
184     #debug information (to be removed when it works many times in a row)
185     print ports
186
187     for port in ports:
188         if port['network_id'] in network_ids:
189             port_id = port['id']
190             try:
191                 subnet_id = port['fixed_ips'][0]['subnet_id']
192             except:
193                 logger.info("  > WARNING: Port %s does not contain 'fixed_ips'" % port_id)
194                 print port
195
196             router_id = port['device_id']
197             if len(port['fixed_ips']) == 0 and router_id == '':
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
205             elif port['device_owner'] == 'network:router_interface':
206                 logger.debug("Detaching port %s (subnet %s) from router %s ..."
207                              % (port_id,subnet_id,router_id))
208                 if functest_utils.remove_interface_router(neutron_client,
209                                                           router_id, subnet_id):
210                     time.sleep(5) # leave 5 seconds to detach before doing anything else
211                     logger.debug("  > Done!")
212                 else:
213                     logger.info("  > ERROR: There has been a problem removing the "
214                                 "interface %s from router %s..." %(subnet_id,router_id))
215                     #print port
216             else:
217                 logger.debug("Removing port %s ..." % port_id)
218                 if functest_utils.delete_neutron_port(neutron_client, port_id):
219                     logger.debug("  > Done!")
220                 else:
221                     logger.info("  > ERROR: There has been a problem removing the "
222                                 "port %s ..." %port_id)
223                     #print port
224
225     #remove routers
226     routers = functest_utils.get_router_list(neutron_client)
227     if routers is None:
228         logger.debug("There are no routers in the deployment. ")
229         return
230     for router in routers:
231         router_id = router['id']
232         router_name = router['name']
233         if router_name not in default_routers:
234             logger.debug("Checking '%s' with ID=(%s) ..." % (router_name,router_id))
235             if router['external_gateway_info'] != None:
236                 logger.debug("Router has gateway to external network. Removing link...")
237                 if functest_utils.remove_gateway_router(neutron_client, router_id):
238                     logger.debug("  > Done!")
239                 else:
240                     logger.info("  > ERROR: There has been a problem removing "
241                                 "the gateway...")
242                     #print router
243
244             else:
245                 logger.debug("Router is not connected to anything. Ready to remove...")
246             logger.debug("Removing router %s(%s) ..." % (router_name,router_id))
247             if functest_utils.delete_neutron_router(neutron_client, router_id):
248                 logger.debug("  > Done!")
249             else:
250                 logger.info("  > ERROR: There has been a problem removing the "
251                             "router '%s'(%s)..." % (router_name,router_id))
252
253
254     #remove networks
255     for net_id in network_ids:
256         logger.debug("Removing network %s ..." % net_id)
257         if functest_utils.delete_neutron_net(neutron_client, net_id):
258             logger.debug("  > Done!")
259         else:
260             logger.info("  > ERROR: There has been a problem removing the "
261                         "network %s..." % net_id)
262
263
264 def remove_security_groups(neutron_client):
265     logger.info("Removing Security groups...")
266     secgroups = functest_utils.get_security_groups(neutron_client)
267     if secgroups is None or len(secgroups) == 0:
268         logger.debug("No security groups found.")
269         return
270
271     for secgroup in secgroups:
272         secgroup_name = secgroup['name']
273         secgroup_id = secgroup['id']
274         logger.debug("'%s', ID=%s " %(secgroup_name,secgroup_id))
275         if secgroup_name not in default_security_groups:
276             logger.debug(" Removing '%s'..." % secgroup_name)
277             if functest_utils.delete_security_group(neutron_client, secgroup_id):
278                 logger.debug("  > Done!")
279             else:
280                 logger.info("  > ERROR: There has been a problem removing the "
281                             "security group %s..." % secgroup_id)
282         else:
283             logger.debug("   > this is a default security group and will NOT "
284                          "be deleted.")
285
286
287 def remove_users(keystone_client):
288     logger.info("Removing Users...")
289     users = functest_utils.get_users(keystone_client)
290     if users == None:
291         logger.debug("There are no users in the deployment. ")
292         return
293
294     for user in users:
295         user_name = getattr(user, 'name')
296         user_id = getattr(user, 'id')
297         logger.debug("'%s', ID=%s " %(user_name,user_id))
298         if user_name not in default_users:
299             logger.debug(" Removing '%s'..." % user_name)
300             if functest_utils.delete_user(keystone_client,user_id):
301                 logger.debug("  > Done!")
302             else:
303                 logger.info("  > ERROR: There has been a problem removing the "
304                             "user '%s'(%s)..." % (user_name,user_id))
305         else:
306             logger.debug("   > this is a default user and will NOT be deleted.")
307
308
309 def remove_tenants(keystone_client):
310     logger.info("Removing Tenants...")
311     tenants = functest_utils.get_tenants(keystone_client)
312     if tenants == None:
313         logger.debug("There are no tenants in the deployment. ")
314         return
315
316     for tenant in tenants:
317         tenant_name=getattr(tenant, 'name')
318         tenant_id = getattr(tenant, 'id')
319         logger.debug("'%s', ID=%s " %(tenant_name,tenant_id))
320         if tenant_name not in default_tenants:
321             logger.debug(" Removing '%s'..." % tenant_name)
322             if functest_utils.delete_tenant(keystone_client,tenant_id):
323                 logger.debug("  > Done!")
324             else:
325                 logger.info("  > ERROR: There has been a problem removing the "
326                             "tenant '%s'(%s)..." % (tenant_name,tenant_id))
327         else:
328             logger.debug("   > this is a default tenant and will NOT be deleted.")
329
330
331
332 def main():
333     creds_nova = functest_utils.get_credentials("nova")
334     nova_client = novaclient.Client(**creds_nova)
335
336     creds_neutron = functest_utils.get_credentials("neutron")
337     neutron_client = neutronclient.Client(**creds_neutron)
338
339     creds_keystone = functest_utils.get_credentials("keystone")
340     keystone_client = keystoneclient.Client(**creds_keystone)
341
342     creds_cinder = functest_utils.get_credentials("cinder")
343     #cinder_client = cinderclient.Client(**creds_cinder)
344     cinder_client = cinderclient.Client('1',creds_cinder['username'],
345                                         creds_cinder['api_key'],
346                                         creds_cinder['project_id'],
347                                         creds_cinder['auth_url'],
348                                         service_type="volume")
349
350     if not functest_utils.check_credentials():
351         logger.error("Please source the openrc credentials and run the script again.")
352         exit(-1)
353
354
355     remove_instances(nova_client)
356     separator()
357     remove_images(nova_client)
358     separator()
359     remove_volumes(cinder_client)
360     separator()
361     remove_floatingips(nova_client)
362     separator()
363     remove_networks(neutron_client)
364     separator()
365     remove_security_groups(neutron_client)
366     separator()
367     remove_users(keystone_client)
368     separator()
369     remove_tenants(keystone_client)
370     separator()
371
372     exit(0)
373
374
375 if __name__ == '__main__':
376     main()