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