4f950b228e4cc7b50e2f871d3e8e058d481c4d1e
[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 import yaml
24
25 import novaclient.v2.client as novaclient
26 from neutronclient.v2_0 import client as neutronclient
27 from keystoneclient.v2_0 import client as keystoneclient
28 from cinderclient import client as cinderclient
29
30 parser = argparse.ArgumentParser()
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 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
46 ch.setFormatter(formatter)
47 logger.addHandler(ch)
48
49 REPO_PATH=os.environ['repos_dir']+'/functest/'
50 if not os.path.exists(REPO_PATH):
51     logger.error("Functest repository directory not found '%s'" % REPO_PATH)
52     exit(-1)
53 sys.path.append(REPO_PATH + "testcases/")
54 import functest_utils
55
56 with open(REPO_PATH+"testcases/VIM/OpenStack/CI/libraries/os_defaults.yaml") as f:
57     defaults_yaml = yaml.safe_load(f)
58 f.close()
59
60 installer = os.environ["INSTALLER_TYPE"]
61
62 default_images = defaults_yaml.get(installer).get("images")
63 default_networks = defaults_yaml.get(installer).get("networks") +\
64     defaults_yaml.get("common").get("networks")
65 default_routers = defaults_yaml.get(installer).get("routers") +\
66     defaults_yaml.get("common").get("routers")
67 default_security_groups = defaults_yaml.get(installer).get("security_groups")
68 default_users = defaults_yaml.get(installer).get("users")
69 default_tenants = defaults_yaml.get(installer).get("tenants")
70
71 def separator():
72     logger.debug("-------------------------------------------")
73
74 def remove_instances(nova_client):
75     logger.info("Removing Nova instances...")
76     instances = functest_utils.get_instances(nova_client)
77     if instances is None or len(instances) == 0:
78         logger.debug("No instances found.")
79         return
80
81     for instance in instances:
82         instance_name = getattr(instance, 'name')
83         instance_id = getattr(instance, 'id')
84         logger.debug("Removing instance '%s', ID=%s ..." % (instance_name,instance_id))
85         if functest_utils.delete_instance(nova_client, instance_id):
86             logger.debug("  > Done!")
87         else:
88             logger.info("  > ERROR: There has been a problem removing the "
89                         "instance %s..." % instance_id)
90
91     timeout = 50
92     while timeout > 0:
93         instances = functest_utils.get_instances(nova_client)
94         if instances is None or len(instances) == 0:
95             break
96         else:
97             logger.debug("Waiting for instances to be terminated...")
98             timeout -= 1
99             time.sleep(1)
100
101
102 def remove_images(nova_client):
103     logger.info("Removing Glance images...")
104     images = functest_utils.get_images(nova_client)
105     if images is None or len(images) == 0:
106         logger.debug("No images found.")
107         return
108
109     for image in images:
110         image_name = getattr(image, 'name')
111         image_id = getattr(image, 'id')
112         logger.debug("'%s', ID=%s " %(image_name,image_id))
113         if image_name not in default_images:
114             logger.debug("Removing image '%s', ID=%s ..." % (image_name,image_id))
115             if functest_utils.delete_glance_image(nova_client, image_id):
116                 logger.debug("  > Done!")
117             else:
118                 logger.info("  > ERROR: There has been a problem removing the"
119                             "image %s..." % image_id)
120         else:
121             logger.debug("   > this is a default image and will NOT be deleted.")
122
123
124 def remove_volumes(cinder_client):
125     logger.info("Removing Cinder volumes...")
126     volumes = functest_utils.get_volumes(cinder_client)
127     if volumes is None or len(volumes) == 0:
128         logger.debug("No volumes found.")
129         return
130
131     for volume in volumes:
132         volume_id = getattr(volume, 'id')
133         logger.debug("Removing cinder volume %s ..." % volume_id)
134         if functest_utils.delete_volume(cinder_client, volume_id):
135             logger.debug("  > Done!")
136         else:
137             logger.info("  > ERROR: There has been a problem removing the "
138                         "volume %s..." % volume_id)
139
140
141 def remove_floatingips(nova_client):
142     logger.info("Removing floating IPs...")
143     floatingips = functest_utils.get_floating_ips(nova_client)
144     if floatingips is None or len(floatingips) == 0:
145         logger.debug("No floating IPs found.")
146         return
147
148     for fip in floatingips:
149         fip_id = getattr(fip, 'id')
150         logger.debug("Removing floating IP %s ..." % fip_id)
151         if functest_utils.delete_floating_ip(nova_client, fip_id):
152             logger.debug("  > Done!")
153         else:
154             logger.info("  > ERROR: There has been a problem removing the "
155                         "floating IP %s..." % fip_id)
156
157     timeout = 50
158     while timeout > 0:
159         floatingips = functest_utils.get_floating_ips(nova_client)
160         if floatingips is None or len(floatingips) == 0:
161             break
162         else:
163             logger.debug("Waiting for floating ips to be released...")
164             timeout -= 1
165             time.sleep(1)
166
167
168 def remove_networks(neutron_client):
169     logger.info("Removing Neutron objects")
170     network_ids = []
171     networks = functest_utils.get_network_list(neutron_client)
172     if networks == None:
173         logger.debug("There are no networks in the deployment. ")
174     else:
175         logger.debug("Existing networks:")
176         for network in networks:
177             net_id = network['id']
178             net_name = network['name']
179             logger.debug(" '%s', ID=%s " %(net_name,net_id))
180             if net_name not in default_networks:
181                 logger.debug("    > this is not a default network and will be deleted.")
182                 network_ids.append(net_id)
183             else:
184                 logger.debug("   > this is a default network and will NOT be deleted.")
185
186     #delete ports
187     ports = functest_utils.get_port_list(neutron_client)
188     if ports is None:
189         logger.debug("There are no ports in the deployment. ")
190     else:
191         remove_ports(neutron_client, ports, network_ids)
192
193     #remove routers
194     routers = functest_utils.get_router_list(neutron_client)
195     if routers is None:
196         logger.debug("There are no routers in the deployment. ")
197     else:
198         remove_routers(neutron_client, routers)
199
200     #remove networks
201     if network_ids != None:
202         for net_id in network_ids:
203             logger.debug("Removing network %s ..." % net_id)
204             if functest_utils.delete_neutron_net(neutron_client, net_id):
205                 logger.debug("  > Done!")
206             else:
207                 logger.info("  > ERROR: There has been a problem removing the "
208                             "network %s..." % net_id)
209
210
211 def remove_ports(neutron_client, ports, network_ids):
212     for port in ports:
213         if port['network_id'] in network_ids:
214             port_id = port['id']
215             try:
216                 subnet_id = port['fixed_ips'][0]['subnet_id']
217             except:
218                 logger.info("  > WARNING: Port %s does not contain 'fixed_ips'" % port_id)
219                 print port
220             router_id = port['device_id']
221             if len(port['fixed_ips']) == 0 and router_id == '':
222                 logger.debug("Removing port %s ..." % port_id)
223                 if functest_utils.delete_neutron_port(neutron_client, port_id):
224                     logger.debug("  > Done!")
225                 else:
226                     logger.info("  > ERROR: There has been a problem removing the "
227                                 "port %s ..." %port_id)
228
229             elif port['device_owner'] == 'network:router_interface':
230                 logger.debug("Detaching port %s (subnet %s) from router %s ..."
231                              % (port_id,subnet_id,router_id))
232                 if functest_utils.remove_interface_router(neutron_client,
233                                                           router_id, subnet_id):
234                     time.sleep(5) # leave 5 seconds to detach before doing anything else
235                     logger.debug("  > Done!")
236                 else:
237                     logger.info("  > ERROR: There has been a problem removing the "
238                                 "interface %s from router %s..." %(subnet_id,router_id))
239             else:
240                 logger.debug("Clearing device_owner for port %s ..." % port_id)
241                 functest_utils.update_neutron_port(neutron_client,
242                                                    port_id,
243                                                    device_owner='clear')
244                 logger.debug("Removing port %s ..." % port_id)
245                 if functest_utils.delete_neutron_port(neutron_client, port_id):
246                     logger.debug("  > Done!")
247                 else:
248                     logger.debug("  > Port %s could not be removed directly" % port_id)
249
250
251 def remove_routers(neutron_client, routers):
252     for router in routers:
253         router_id = router['id']
254         router_name = router['name']
255         if router_name not in default_routers:
256             logger.debug("Checking '%s' with ID=(%s) ..." % (router_name,router_id))
257             if router['external_gateway_info'] != None:
258                 logger.debug("Router has gateway to external network. Removing link...")
259                 if functest_utils.remove_gateway_router(neutron_client, router_id):
260                     logger.debug("  > Done!")
261                 else:
262                     logger.info("  > ERROR: There has been a problem removing "
263                                 "the gateway...")
264             else:
265                 logger.debug("Router is not connected to anything. Ready to remove...")
266             logger.debug("Removing router %s(%s) ..." % (router_name, router_id))
267             if functest_utils.delete_neutron_router(neutron_client, router_id):
268                 logger.debug("  > Done!")
269             else:
270                 logger.info("  > ERROR: There has been a problem removing the "
271                             "router '%s'(%s)..." % (router_name, router_id))
272
273
274 def remove_security_groups(neutron_client):
275     logger.info("Removing Security groups...")
276     secgroups = functest_utils.get_security_groups(neutron_client)
277     if secgroups is None or len(secgroups) == 0:
278         logger.debug("No security groups found.")
279         return
280
281     for secgroup in secgroups:
282         secgroup_name = secgroup['name']
283         secgroup_id = secgroup['id']
284         logger.debug("'%s', ID=%s " %(secgroup_name,secgroup_id))
285         if secgroup_name not in default_security_groups:
286             logger.debug(" Removing '%s'..." % secgroup_name)
287             if functest_utils.delete_security_group(neutron_client, secgroup_id):
288                 logger.debug("  > Done!")
289             else:
290                 logger.info("  > ERROR: There has been a problem removing the "
291                             "security group %s..." % secgroup_id)
292         else:
293             logger.debug("   > this is a default security group and will NOT "
294                          "be deleted.")
295
296
297 def remove_users(keystone_client):
298     logger.info("Removing Users...")
299     users = functest_utils.get_users(keystone_client)
300     if users == None:
301         logger.debug("There are no users in the deployment. ")
302         return
303
304     for user in users:
305         user_name = getattr(user, 'name')
306         user_id = getattr(user, 'id')
307         logger.debug("'%s', ID=%s " %(user_name,user_id))
308         if user_name not in default_users:
309             logger.debug(" Removing '%s'..." % user_name)
310             if functest_utils.delete_user(keystone_client,user_id):
311                 logger.debug("  > Done!")
312             else:
313                 logger.info("  > ERROR: There has been a problem removing the "
314                             "user '%s'(%s)..." % (user_name,user_id))
315         else:
316             logger.debug("   > this is a default user and will NOT be deleted.")
317
318
319 def remove_tenants(keystone_client):
320     logger.info("Removing Tenants...")
321     tenants = functest_utils.get_tenants(keystone_client)
322     if tenants == None:
323         logger.debug("There are no tenants in the deployment. ")
324         return
325
326     for tenant in tenants:
327         tenant_name=getattr(tenant, 'name')
328         tenant_id = getattr(tenant, 'id')
329         logger.debug("'%s', ID=%s " %(tenant_name,tenant_id))
330         if tenant_name not in default_tenants:
331             logger.debug(" Removing '%s'..." % tenant_name)
332             if functest_utils.delete_tenant(keystone_client,tenant_id):
333                 logger.debug("  > Done!")
334             else:
335                 logger.info("  > ERROR: There has been a problem removing the "
336                             "tenant '%s'(%s)..." % (tenant_name,tenant_id))
337         else:
338             logger.debug("   > this is a default tenant and will NOT be deleted.")
339
340
341
342 def main():
343     creds_nova = functest_utils.get_credentials("nova")
344     nova_client = novaclient.Client(**creds_nova)
345
346     creds_neutron = functest_utils.get_credentials("neutron")
347     neutron_client = neutronclient.Client(**creds_neutron)
348
349     creds_keystone = functest_utils.get_credentials("keystone")
350     keystone_client = keystoneclient.Client(**creds_keystone)
351
352     creds_cinder = functest_utils.get_credentials("cinder")
353     #cinder_client = cinderclient.Client(**creds_cinder)
354     cinder_client = cinderclient.Client('1',creds_cinder['username'],
355                                         creds_cinder['api_key'],
356                                         creds_cinder['project_id'],
357                                         creds_cinder['auth_url'],
358                                         service_type="volume")
359
360     if not functest_utils.check_credentials():
361         logger.error("Please source the openrc credentials and run the script again.")
362         exit(-1)
363
364
365     remove_instances(nova_client)
366     separator()
367     remove_images(nova_client)
368     separator()
369     remove_volumes(cinder_client)
370     separator()
371     remove_floatingips(nova_client)
372     separator()
373     remove_networks(neutron_client)
374     separator()
375     remove_security_groups(neutron_client)
376     separator()
377     remove_users(keystone_client)
378     separator()
379     remove_tenants(keystone_client)
380     separator()
381
382     exit(0)
383
384
385 if __name__ == '__main__':
386     main()