Obtain build_tag by CONST instead of get function
[functest.git] / functest / utils / openstack_clean.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 #       - Tacker VNFDs and VNFs
13 #       - Tacker SFCs and SFC classifiers
14 #
15 # Author:
16 #    jose.lausuch@ericsson.com
17 #
18 #
19 # All rights reserved. This program and the accompanying materials
20 # are made available under the terms of the Apache License, Version 2.0
21 # which accompanies this distribution, and is available at
22 # http://www.apache.org/licenses/LICENSE-2.0
23 #
24
25 import logging
26 import time
27 import yaml
28
29 import functest.utils.openstack_utils as os_utils
30 from functest.utils.constants import CONST
31
32 logger = logging.getLogger(__name__)
33
34 OS_SNAPSHOT_FILE = CONST.openstack_snapshot_file
35
36
37 def separator():
38     logger.debug("-------------------------------------------")
39
40
41 def remove_instances(nova_client, default_instances):
42     logger.debug("Removing Nova instances...")
43     instances = os_utils.get_instances(nova_client)
44     if instances is None or len(instances) == 0:
45         logger.debug("No instances found.")
46         return
47
48     for instance in instances:
49         instance_name = getattr(instance, 'name')
50         instance_id = getattr(instance, 'id')
51         instance_status = getattr(instance, 'status')
52         instance_state = getattr(instance, 'OS-EXT-STS:task_state')
53
54         logger.debug("'%s', ID=%s " % (instance_name, instance_id))
55         if (instance_id not in default_instances and
56                 instance_name not in default_instances.values() and
57                 instance_status != 'DELETED' and
58                 (instance_status != 'BUILD' or instance_state != 'deleting')):
59             logger.debug("Removing instance '%s' ..." % instance_id)
60             if os_utils.delete_instance(nova_client, instance_id):
61                 logger.debug("  > Request sent.")
62             else:
63                 logger.error("There has been a problem removing the "
64                              "instance %s..." % instance_id)
65         else:
66             logger.debug("   > this is a default instance and will "
67                          "NOT be deleted.")
68
69     timeout = 50
70     while timeout > 0:
71         instances = os_utils.get_instances(nova_client)
72         for instance in instances:
73             instance_id = getattr(instance, 'id')
74             if instance_id not in default_instances:
75                 logger.debug("Waiting for instances to be terminated...")
76                 timeout -= 1
77                 time.sleep(1)
78                 continue
79         break
80
81
82 def remove_images(glance_client, default_images):
83     logger.debug("Removing Glance images...")
84     images = os_utils.get_images(glance_client)
85     if images is None:
86         return -1
87     images = {image.id: image.name for image in images}
88     if len(images) == 0:
89         logger.debug("No images found.")
90         return
91
92     for image in images:
93         image_id = image
94         image_name = images.get(image_id)
95         logger.debug("'%s', ID=%s " % (image_name, image_id))
96         if (image_id not in default_images and
97                 image_name not in default_images.values()):
98             logger.debug("Removing image '%s', ID=%s ..."
99                          % (image_name, image_id))
100             if os_utils.delete_glance_image(glance_client, image_id):
101                 logger.debug("  > Done!")
102             else:
103                 logger.error("There has been a problem removing the"
104                              "image %s..." % image_id)
105         else:
106             logger.debug("   > this is a default image and will "
107                          "NOT be deleted.")
108
109
110 def remove_volumes(cinder_client, default_volumes):
111     logger.debug("Removing Cinder volumes...")
112     volumes = os_utils.get_volumes(cinder_client)
113     if volumes is None or len(volumes) == 0:
114         logger.debug("No volumes found.")
115         return
116
117     for volume in volumes:
118         volume_id = getattr(volume, 'id')
119         volume_name = getattr(volume, 'name')
120         logger.debug("'%s', ID=%s " % (volume_name, volume_id))
121         if (volume_id not in default_volumes and
122                 volume_name not in default_volumes.values()):
123             logger.debug("Removing cinder volume %s ..." % volume_id)
124             if os_utils.delete_volume(cinder_client, volume_id):
125                 logger.debug("  > Done!")
126             else:
127                 logger.debug("Trying forced removal...")
128                 if os_utils.delete_volume(cinder_client,
129                                           volume_id,
130                                           forced=True):
131                     logger.debug("  > Done!")
132                 else:
133                     logger.error("There has been a problem removing the "
134                                  "volume %s..." % volume_id)
135         else:
136             logger.debug("   > this is a default volume and will "
137                          "NOT be deleted.")
138
139
140 def remove_floatingips(neutron_client, default_floatingips):
141     logger.debug("Removing floating IPs...")
142     floatingips = os_utils.get_floating_ips(neutron_client)
143     if floatingips is None or len(floatingips) == 0:
144         logger.debug("No floating IPs found.")
145         return
146
147     init_len = len(floatingips)
148     deleted = 0
149     for fip in floatingips:
150         fip_id = fip['id']
151         fip_ip = fip['floating_ip_address']
152         logger.debug("'%s', ID=%s " % (fip_ip, fip_id))
153         if (fip_id not in default_floatingips and
154                 fip_ip not in default_floatingips.values()):
155             logger.debug("Removing floating IP %s ..." % fip_id)
156             if os_utils.delete_floating_ip(neutron_client, fip_id):
157                 logger.debug("  > Done!")
158                 deleted += 1
159             else:
160                 logger.error("There has been a problem removing the "
161                              "floating IP %s..." % fip_id)
162         else:
163             logger.debug("   > this is a default floating IP and will "
164                          "NOT be deleted.")
165
166     timeout = 50
167     while timeout > 0:
168         floatingips = os_utils.get_floating_ips(neutron_client)
169         if floatingips is None or len(floatingips) == (init_len - deleted):
170             break
171         else:
172             logger.debug("Waiting for floating ips to be released...")
173             timeout -= 1
174             time.sleep(1)
175
176
177 def remove_networks(neutron_client, default_networks, default_routers):
178     logger.debug("Removing Neutron objects")
179     network_ids = []
180     networks = os_utils.get_network_list(neutron_client)
181     if networks is None:
182         logger.debug("There are no networks in the deployment. ")
183     else:
184         logger.debug("Existing networks:")
185         for network in networks:
186             net_id = network['id']
187             net_name = network['name']
188             logger.debug(" '%s', ID=%s " % (net_name, net_id))
189             if (net_id in default_networks and
190                     net_name in default_networks.values()):
191                 logger.debug("   > this is a default network and will "
192                              "NOT be deleted.")
193             elif network['router:external'] is True:
194                 logger.debug("   > this is an external network and will "
195                              "NOT be deleted.")
196             else:
197                 logger.debug("   > this network will be deleted.")
198                 network_ids.append(net_id)
199
200     # delete ports
201     ports = os_utils.get_port_list(neutron_client)
202     if ports is None:
203         logger.debug("There are no ports in the deployment. ")
204     else:
205         remove_ports(neutron_client, ports, network_ids)
206
207     # remove routers
208     routers = os_utils.get_router_list(neutron_client)
209     if routers is None:
210         logger.debug("There are no routers in the deployment. ")
211     else:
212         remove_routers(neutron_client, routers, default_routers)
213
214     # trozet: wait for Neutron to auto-cleanup HA networks when HA router is
215     #  deleted
216     time.sleep(5)
217
218     # remove networks
219     if network_ids is not None:
220         for net_id in network_ids:
221             networks = os_utils.get_network_list(neutron_client)
222             if networks is None:
223                 logger.debug("No networks left to remove")
224                 break
225             elif not any(network['id'] == net_id for network in networks):
226                 logger.debug("Network %s has already been removed" % net_id)
227                 continue
228             logger.debug("Removing network %s ..." % net_id)
229             if os_utils.delete_neutron_net(neutron_client, net_id):
230                 logger.debug("  > Done!")
231             else:
232                 logger.error("There has been a problem removing the "
233                              "network %s..." % net_id)
234
235
236 def remove_ports(neutron_client, ports, network_ids):
237     for port in ports:
238         if port['network_id'] in network_ids:
239             port_id = port['id']
240             try:
241                 subnet_id = port['fixed_ips'][0]['subnet_id']
242             except:
243                 logger.debug("  > WARNING: Port %s does not contain fixed_ips"
244                              % port_id)
245                 logger.info(port)
246             router_id = port['device_id']
247             if len(port['fixed_ips']) == 0 and router_id == '':
248                 logger.debug("Removing port %s ..." % port_id)
249                 if (os_utils.delete_neutron_port(neutron_client, port_id)):
250                     logger.debug("  > Done!")
251                 else:
252                     logger.error("There has been a problem removing the "
253                                  "port %s ..." % port_id)
254                     force_remove_port(neutron_client, port_id)
255
256             elif port['device_owner'] == 'network:router_interface':
257                 logger.debug("Detaching port %s (subnet %s) from router %s ..."
258                              % (port_id, subnet_id, router_id))
259                 if os_utils.remove_interface_router(
260                         neutron_client, router_id, subnet_id):
261                     time.sleep(5)  # leave 5 seconds to detach
262                     logger.debug("  > Done!")
263                 else:
264                     logger.error("There has been a problem removing the "
265                                  "interface %s from router %s..."
266                                  % (subnet_id, router_id))
267                     force_remove_port(neutron_client, port_id)
268             else:
269                 force_remove_port(neutron_client, port_id)
270
271
272 def force_remove_port(neutron_client, port_id):
273     logger.debug("Clearing device_owner for port %s ..." % port_id)
274     os_utils.update_neutron_port(neutron_client, port_id,
275                                  device_owner='clear')
276     logger.debug("Removing port %s ..." % port_id)
277     if os_utils.delete_neutron_port(neutron_client, port_id):
278         logger.debug("  > Done!")
279     else:
280         logger.error("There has been a problem removing the port %s..."
281                      % port_id)
282
283
284 def remove_routers(neutron_client, routers, default_routers):
285     for router in routers:
286         router_id = router['id']
287         router_name = router['name']
288         if (router_id not in default_routers and
289                 router_name not in default_routers.values()):
290             logger.debug("Checking '%s' with ID=(%s) ..." % (router_name,
291                                                              router_id))
292             if router['external_gateway_info'] is not None:
293                 logger.debug("Router has gateway to external network."
294                              "Removing link...")
295                 if os_utils.remove_gateway_router(neutron_client, router_id):
296                     logger.debug("  > Done!")
297                 else:
298                     logger.error("There has been a problem removing "
299                                  "the gateway...")
300             else:
301                 logger.debug("Router is not connected to anything."
302                              "Ready to remove...")
303             logger.debug("Removing router %s(%s) ..."
304                          % (router_name, router_id))
305             if os_utils.delete_neutron_router(neutron_client, router_id):
306                 logger.debug("  > Done!")
307             else:
308                 logger.error("There has been a problem removing the "
309                              "router '%s'(%s)..." % (router_name, router_id))
310
311
312 def remove_security_groups(neutron_client, default_security_groups):
313     logger.debug("Removing Security groups...")
314     secgroups = os_utils.get_security_groups(neutron_client)
315     if secgroups is None or len(secgroups) == 0:
316         logger.debug("No security groups found.")
317         return
318
319     for secgroup in secgroups:
320         secgroup_name = secgroup['name']
321         secgroup_id = secgroup['id']
322         logger.debug("'%s', ID=%s " % (secgroup_name, secgroup_id))
323         if secgroup_id not in default_security_groups:
324             logger.debug(" Removing '%s'..." % secgroup_name)
325             if os_utils.delete_security_group(neutron_client, secgroup_id):
326                 logger.debug("  > Done!")
327             else:
328                 logger.error("There has been a problem removing the "
329                              "security group %s..." % secgroup_id)
330         else:
331             logger.debug("   > this is a default security group and will NOT "
332                          "be deleted.")
333
334
335 def remove_users(keystone_client, default_users):
336     logger.debug("Removing Users...")
337     users = os_utils.get_users(keystone_client)
338     if users is None:
339         logger.debug("There are no users in the deployment. ")
340         return
341
342     for user in users:
343         user_name = getattr(user, 'name')
344         user_id = getattr(user, 'id')
345         logger.debug("'%s', ID=%s " % (user_name, user_id))
346         if (user_id not in default_users and
347                 user_name not in default_users.values()):
348             logger.debug(" Removing '%s'..." % user_name)
349             if os_utils.delete_user(keystone_client, user_id):
350                 logger.debug("  > Done!")
351             else:
352                 logger.error("There has been a problem removing the "
353                              "user '%s'(%s)..." % (user_name, user_id))
354         else:
355             logger.debug("   > this is a default user and will "
356                          "NOT be deleted.")
357
358
359 def remove_tenants(keystone_client, default_tenants):
360     logger.debug("Removing Tenants...")
361     tenants = os_utils.get_tenants(keystone_client)
362     if tenants is None:
363         logger.debug("There are no tenants in the deployment. ")
364         return
365
366     for tenant in tenants:
367         tenant_name = getattr(tenant, 'name')
368         tenant_id = getattr(tenant, 'id')
369         logger.debug("'%s', ID=%s " % (tenant_name, tenant_id))
370         if (tenant_id not in default_tenants and
371                 tenant_name not in default_tenants.values()):
372             logger.debug(" Removing '%s'..." % tenant_name)
373             if os_utils.delete_tenant(keystone_client, tenant_id):
374                 logger.debug("  > Done!")
375             else:
376                 logger.error("There has been a problem removing the "
377                              "tenant '%s'(%s)..." % (tenant_name, tenant_id))
378         else:
379             logger.debug("   > this is a default tenant and will "
380                          "NOT be deleted.")
381
382
383 def main():
384     logging.basicConfig()
385     logger.info("Cleaning OpenStack resources...")
386
387     nova_client = os_utils.get_nova_client()
388     neutron_client = os_utils.get_neutron_client()
389     keystone_client = os_utils.get_keystone_client()
390     cinder_client = os_utils.get_cinder_client()
391     glance_client = os_utils.get_glance_client()
392
393     try:
394         with open(OS_SNAPSHOT_FILE) as f:
395             snapshot_yaml = yaml.safe_load(f)
396     except Exception:
397         logger.info("The file %s does not exist. The OpenStack snapshot must"
398                     " be created first. Aborting cleanup." % OS_SNAPSHOT_FILE)
399         return 0
400
401     default_images = snapshot_yaml.get('images')
402     default_instances = snapshot_yaml.get('instances')
403     default_volumes = snapshot_yaml.get('volumes')
404     default_networks = snapshot_yaml.get('networks')
405     default_routers = snapshot_yaml.get('routers')
406     default_security_groups = snapshot_yaml.get('secgroups')
407     default_floatingips = snapshot_yaml.get('floatingips')
408     default_users = snapshot_yaml.get('users')
409     default_tenants = snapshot_yaml.get('tenants')
410
411     if not os_utils.check_credentials():
412         logger.error("Please source the openrc credentials and run "
413                      "the script again.")
414         return -1
415
416     remove_instances(nova_client, default_instances)
417     separator()
418     remove_images(glance_client, default_images)
419     separator()
420     remove_volumes(cinder_client, default_volumes)
421     separator()
422     remove_floatingips(neutron_client, default_floatingips)
423     separator()
424     remove_networks(neutron_client, default_networks, default_routers)
425     separator()
426     remove_security_groups(neutron_client, default_security_groups)
427     separator()
428     remove_users(keystone_client, default_users)
429     separator()
430     remove_tenants(keystone_client, default_tenants)
431     separator()
432     return 0