blob: a8431d6d0b0a4b3a43deea8caf2e14e255a94a76 [file] [log] [blame]
Dmitriy Kruglovb811e642022-10-06 12:24:33 +02001import argparse
2import os
3import re
4import sys
5
6import openstack
7
8
9# Send logs to both, a log file and stdout
10openstack.enable_logging(debug=False, path='openstack.log', stream=sys.stdout)
11
12# Connect to cloud
13TEST_CLOUD = os.getenv('OS_TEST_CLOUD', 'os-cloud')
14cloud = openstack.connect(cloud=TEST_CLOUD)
15log = cloud.log
16
17# Get cloud config (clouds.yaml vars)
18config_obj = openstack.config.loader.OpenStackConfig()
19cloud_config = config_obj.get_one(cloud=TEST_CLOUD)
20
21compute = cloud.compute
22identity = cloud.identity
23image = cloud.image
24network = cloud.network
25orchestration = cloud.orchestration
26object_store = cloud.object_store
27volume = cloud.volume
Ievgeniia Zadorozhnaab334132023-08-01 23:20:13 +030028load_balancer = cloud.load_balancer
Dmitriy Kruglovb811e642022-10-06 12:24:33 +020029
30mask = "cvp|s_rally|rally_|tempest-|tempest_|spt|fio"
31full_mask = f"^(?!.*(manual|-static-)).*({mask}).*$"
32mask_pattern = re.compile(full_mask, re.IGNORECASE)
33stack_mask = "api-[0-9]+-[a-z]+"
34stack_pattern = re.compile(stack_mask, re.IGNORECASE)
35
36
37def get_resource_value(resource_key, default):
38 try:
39 return cloud_config.config['custom_vars'][resource_key]
40 except KeyError:
41 return default
42
43
44def _filter_test_resources(resources, attribute, pattern=mask_pattern):
45 filtered_resources = {}
46 for item in resources:
47 # If there is no attribute in object, use just empty string as value
48 value = getattr(item, attribute, '')
49 # If the attribute value is None, use empty string instead, to be
50 # able to run regex search
51 if value is None:
52 value = ''
53 found = pattern.match(value)
54 if found:
55 filtered_resources[item.id] = getattr(item, attribute)
56 return filtered_resources
57
58
59def _log_resources_count(count, resource, pattern=mask):
60 log.info(f"{count} {resource} containing '{pattern}' are found.")
61
62
63def _log_resource_delete(id_, name, type_):
64 log.info(f"... deleting {name} (id={id_}) {type_}")
65
66
Ievgeniia Zadorozhnaab334132023-08-01 23:20:13 +030067def _force_delete_load_balancer(id_):
68 log.info(f"... ... force deleting {id_} load balancer")
69 lb_ep = load_balancer.get_endpoint()
70 lb_uri = f"{lb_ep}/lbaas/loadbalancers/{id_}"
71 headers = {'X-Auth-Token': cloud.session.get_token(),
72 'Content-Type': 'application/json'}
73 params = {'cascade': 'true', 'force': 'true'}
74 cloud.session.request(url=lb_uri, method='DELETE',
75 headers=headers, params=params)
76
77
Dmitriy Kruglovb811e642022-10-06 12:24:33 +020078def cleanup_users():
79 users = identity.users()
80 users_to_delete = _filter_test_resources(users, 'name')
81 _log_resources_count(len(users_to_delete), 'user(s)')
82 if args.dry_run:
83 return
84 for id_ in users_to_delete:
85 _log_resource_delete(id_, users_to_delete[id_], 'user')
86 identity.delete_user(id_)
87
88
89def cleanup_roles():
90 roles = identity.roles()
91 roles_to_delete = _filter_test_resources(roles, 'name')
92 _log_resources_count(len(roles_to_delete), 'role(s)')
93 if args.dry_run:
94 return
95 for id_ in roles_to_delete:
96 _log_resource_delete(id_, roles_to_delete[id_], 'role')
97 identity.delete_role(id_)
98
99
100def cleanup_projects():
101 projects = identity.projects()
102 projects_to_delete = _filter_test_resources(projects, 'name')
103 _log_resources_count(len(projects_to_delete), 'project(s)')
104 if args.dry_run:
105 return
106 for id_ in projects_to_delete:
107 _log_resource_delete(id_, projects_to_delete[id_], 'project')
108 identity.delete_project(id_)
109
110
111def cleanup_regions():
112 regions = identity.regions()
113 regions_to_delete = _filter_test_resources(regions, 'id')
114 _log_resources_count(len(regions_to_delete), 'region(s)')
115 if args.dry_run:
116 return
117 for id_ in regions_to_delete:
118 _log_resource_delete(id_, id_, 'region')
119 identity.delete_region(id_)
120
121
122def cleanup_services():
123 services = identity.services()
124 services_to_delete = _filter_test_resources(services, 'name')
125 _log_resources_count(len(services_to_delete), 'service(s)')
126 if args.dry_run:
127 return
128 for id_ in services_to_delete:
129 _log_resource_delete(id_, services_to_delete[id_], 'service')
130 identity.delete_service(id_)
131
132
133def cleanup_stacks(stacks_alt=False):
134 stacks = orchestration.stacks()
135 stacks_to_delete = _filter_test_resources(stacks, 'name')
136 _log_resources_count(len(stacks_to_delete), 'stack(s)')
137
138 # Use additional pattern for searching/deleting test Heat resources,
139 # if enabled
140 if stacks_alt:
141 stacks_alt_to_delete = _filter_test_resources(
142 stacks, 'name', stack_pattern)
143 _log_resources_count(len(stacks_alt_to_delete), 'stack(s)', stack_mask)
144 stacks_to_delete.update(stacks_alt_to_delete)
145
146 if args.dry_run:
147 return
148
149 for id_ in stacks_to_delete:
150 _log_resource_delete(id_, stacks_to_delete[id_], 'stack')
151 orchestration.delete_stack(id_)
152 orchestration.wait_for_delete(id_)
153
154
155def cleanup_flavors():
156 flavors = compute.flavors()
157 flavors_to_delete = _filter_test_resources(flavors, 'name')
158 _log_resources_count(len(flavors_to_delete), 'flavor(s)')
159 if args.dry_run:
160 return
161 for id_ in flavors_to_delete:
162 _log_resource_delete(id_, flavors_to_delete[id_], 'flavor')
163 compute.delete_flavor(id_)
164
165
166def cleanup_images():
167 images = image.images()
168 images_to_delete = _filter_test_resources(images, 'name')
169 _log_resources_count(len(images_to_delete), 'image(s)')
170 if args.dry_run:
171 return
172 for id_ in images_to_delete:
173 _log_resource_delete(id_, images_to_delete[id_], 'image')
174 image.delete_image(id_)
175
176
177def cleanup_keypairs():
178 keypairs = compute.keypairs()
179 keypairs_to_delete = _filter_test_resources(keypairs, 'name')
180 _log_resources_count(len(keypairs_to_delete), 'keypair(s)')
181 if args.dry_run:
182 return
183 for id_ in keypairs_to_delete:
184 _log_resource_delete(id_, keypairs_to_delete[id_], 'keypair')
185 compute.delete_keypair(id_)
186
187
188def cleanup_servers():
189 servers = compute.servers(all_projects=True)
190 servers_to_delete = _filter_test_resources(servers, 'name')
191 _log_resources_count(len(servers_to_delete), 'server(s)')
192 if args.dry_run:
193 return
194 for id_ in servers_to_delete:
195 if args.servers_active:
196 log.info(
197 f"... resetting {servers_to_delete[id_]} (id={id_}) server "
198 "state to 'active'")
199 compute.reset_server_state(id_, 'active')
200 _log_resource_delete(id_, servers_to_delete[id_], 'server')
201 compute.delete_server(id_)
202 srv_obj = compute.get_server(id_)
203 compute.wait_for_delete(srv_obj)
204
205
206def cleanup_snapshots():
207 snapshots = volume.snapshots(all_projects=True)
208 snapshots_to_delete = _filter_test_resources(snapshots, 'name')
209 _log_resources_count(len(snapshots_to_delete), 'snapshot(s)')
210 if args.dry_run:
211 return
212 for id_ in snapshots_to_delete:
213 volume.reset_snapshot(id_, 'available')
214 _log_resource_delete(id_, snapshots_to_delete[id_], 'snapshot')
215 volume.delete_snapshot(id_)
216 volume.wait_for_delete(id_)
217
218
219def cleanup_volumes():
220 volumes = volume.volumes(all_projects=True)
221 volumes_to_delete = _filter_test_resources(volumes, 'name')
222 _log_resources_count(len(volumes_to_delete), 'volume(s)')
223 if args.dry_run:
224 return
225 for id_ in volumes_to_delete:
226 volume.reset_volume_status(id_, 'available', 'detached', 'None')
227 _log_resource_delete(id_, volumes_to_delete[id_], 'volume')
228 volume.delete_volume(id_)
229 vol_obj = volume.get_volume(id_)
230 volume.wait_for_delete(vol_obj)
231
232
233def cleanup_volume_groups():
234 groups = volume.groups()
235 groups_to_delete = _filter_test_resources(groups, 'name')
236 _log_resources_count(len(groups_to_delete), 'volume group(s)')
237 if args.dry_run:
238 return
239 for id_ in groups_to_delete:
240 _log_resource_delete(id_, groups_to_delete[id_], 'volume group')
241 volume.delete_group(id_)
242
243
244def cleanup_volume_group_types():
245 group_types = volume.group_types()
246 group_types_to_delete = _filter_test_resources(group_types, 'name')
247 _log_resources_count(len(group_types_to_delete), 'volume group type(s)')
248 if args.dry_run:
249 return
250 for id_ in group_types_to_delete:
251 _log_resource_delete(
252 id_, group_types_to_delete[id_], 'volume group type')
253 volume.delete_group_type(id_)
254
255
256def cleanup_volume_types():
257 volume_types = volume.types()
258 volume_types_to_delete = _filter_test_resources(volume_types, 'name')
259 _log_resources_count(len(volume_types_to_delete), 'volume type(s)')
260 if args.dry_run:
261 return
262 for id_ in volume_types_to_delete:
263 _log_resource_delete(id_, volume_types_to_delete[id_], 'volume type')
264 volume.delete_type(id_)
265
266
267def cleanup_sec_groups():
268 sec_groups = network.security_groups()
269 sec_groups_to_delete = _filter_test_resources(sec_groups, 'name')
270 _log_resources_count(len(sec_groups_to_delete), 'security group(s)')
271 if args.dry_run:
272 return
273 for id_ in sec_groups_to_delete:
274 _log_resource_delete(id_, sec_groups_to_delete[id_], 'security group')
275 network.delete_security_group(id_)
276
277
278def cleanup_containers():
279 containers = object_store.containers()
280 containers_to_delete = _filter_test_resources(containers, 'name')
281 _log_resources_count(len(containers_to_delete), 'container(s)')
282 if args.dry_run:
283 return
284 for id_ in containers_to_delete:
285 _log_resource_delete(id_, containers_to_delete[id_], 'container')
286 object_store.delete_container(id_)
287
288
289def cleanup_routers():
290 routers = network.routers()
291 routers_to_delete = _filter_test_resources(routers, 'name')
292 _log_resources_count(len(routers_to_delete), 'router(s)')
293 if args.dry_run:
294 return
295 for id_ in routers_to_delete:
296 _log_resource_delete(id_, routers_to_delete[id_], 'router')
297
298 # Unset external gateway and remove ports from router
299 log.info("... ... removing external gateway from the router")
300 network.update_router(id_, external_gateway_info={})
301 ports = network.ports(device_id=id_)
302 for p in ports:
303 if p.device_owner != 'network:router_ha_interface':
304 log.info(f"... ... removing port {p.id} from the router")
305 network.remove_interface_from_router(id_, port_id=p.id)
306
307 network.delete_router(id_)
308
309
310def cleanup_networks():
311 nets = network.networks()
312 nets_to_delete = _filter_test_resources(nets, 'name')
313 _log_resources_count(len(nets_to_delete), 'network(s)')
314 if args.dry_run:
315 return
316 for id_ in nets_to_delete:
317 _log_resource_delete(id_, nets_to_delete[id_], 'network')
318
319 ports = network.ports(network_id=id_)
320 for p in ports:
321 log.info(
322 f"... ... removing port {p.id} from the network")
323 network.delete_port(p.id)
324 subnets = network.subnets(network_id=id_)
325 for s in subnets:
326 log.info(
327 f"... ... removing subnet {s.id} from the network")
328 network.delete_subnet(s.id)
329
330 network.delete_network(id_)
331
332
Ievgeniia Zadorozhnaab334132023-08-01 23:20:13 +0300333def cleanup_load_balancers():
334 lbs = load_balancer.load_balancers()
335 lbs_to_delete = _filter_test_resources(lbs, 'name')
336 _log_resources_count(len(lbs_to_delete), 'load_balancer(s)')
337 if args.dry_run:
338 return
339 for id_ in lbs_to_delete:
340 _log_resource_delete(id_, lbs_to_delete[id_], 'load_balancer')
341 try:
342 load_balancer.delete_load_balancer(id_, cascade=True)
343 except openstack.exceptions.ConflictException:
344 # force delete the LB in case it is in some PENDING_* state
345 _force_delete_load_balancer(id_)
346 except Exception as e:
347 log.info(f"... ... could not delete {id_} load balancer: {e}")
348
349
Dmitriy Kruglovb811e642022-10-06 12:24:33 +0200350if __name__ == "__main__":
351 parser = argparse.ArgumentParser(
352 description='OpenStack test resources cleanup script')
353 parser.add_argument(
354 '-t', dest='dry_run', action='store_true',
355 help='Dry run mode, no cleanup is done')
356 parser.add_argument(
357 '-P', dest='projects', action='store_true',
358 help='Force cleanup of projects')
359 parser.add_argument(
360 '-S', dest='servers_active', action='store_true',
361 help='Set servers to ACTIVE before deletion (reqiured by bare metal)')
362 parser.add_argument(
363 '-f', dest='stacks_alt', action='store_true',
364 help='Use additional mask for stack cleanup')
365
366 args = parser.parse_args()
367
368 if args.dry_run:
369 log.info("Running in dry-run mode")
370 if args.servers_active:
371 log.info("Servers will be set to ACTIVE before cleanup")
372 if args.projects:
373 log.info("Project cleanup is enabled")
374 if args.stacks_alt:
375 log.info(
376 f"Stacks will be cleaned up using additional '{stack_mask}' mask")
377
378 cleanup_stacks(stacks_alt=args.stacks_alt)
379 cleanup_servers()
380 cleanup_flavors()
381 cleanup_snapshots()
382 cleanup_volumes()
383 cleanup_volume_groups()
384 cleanup_volume_group_types()
385 cleanup_volume_types()
386 cleanup_images()
387 cleanup_sec_groups()
388 cleanup_keypairs()
389 cleanup_users()
390 cleanup_roles()
391 cleanup_services()
392 cleanup_regions()
393 cleanup_routers()
394 cleanup_networks()
395 cleanup_containers()
Ievgeniia Zadorozhnaab334132023-08-01 23:20:13 +0300396 cleanup_load_balancers()
Dmitriy Kruglovb811e642022-10-06 12:24:33 +0200397
398 if args.projects:
399 cleanup_projects()
400
401 msg = "Cleanup is FINISHED"
402 log.info(f"\n{'=' * len(msg)}\n{msg}")