You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.0 KiB

  1. #!/usr/bin/env python
  2. import argparse
  3. import openstack
  4. import logging
  5. import datetime
  6. import time
  7. DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  8. PAUSE_SECONDS = 5
  9. log = logging.getLogger('openstack-cleanup')
  10. parser = argparse.ArgumentParser(description='Cleanup OpenStack resources')
  11. parser.add_argument('-v', '--verbose', action='store_true',
  12. help='Increase verbosity')
  13. parser.add_argument('--hours', type=int, default=4,
  14. help='Age (in hours) of VMs to cleanup (default: 4h)')
  15. parser.add_argument('--dry-run', action='store_true',
  16. help='Do not delete anything')
  17. args = parser.parse_args()
  18. oldest_allowed = datetime.datetime.now() - datetime.timedelta(hours=args.hours)
  19. def main():
  20. if args.dry_run:
  21. print('Running in dry-run mode')
  22. else:
  23. print('This will delete resources... (ctrl+c to cancel)')
  24. time.sleep(PAUSE_SECONDS)
  25. conn = openstack.connect()
  26. print('Servers...')
  27. map_if_old(conn.compute.delete_server,
  28. conn.compute.servers())
  29. print('Security groups...')
  30. map_if_old(conn.network.delete_security_group,
  31. conn.network.security_groups())
  32. print('Ports...')
  33. try:
  34. map_if_old(conn.network.delete_port,
  35. conn.network.ports())
  36. except openstack.exceptions.ConflictException as ex:
  37. # Need to find subnet-id which should be removed from a router
  38. for sn in conn.network.subnets():
  39. try:
  40. fn_if_old(conn.network.delete_subnet, sn)
  41. except openstack.exceptions.ConflictException:
  42. for r in conn.network.routers():
  43. print("Deleting subnet %s from router %s", sn, r)
  44. try:
  45. conn.network.remove_interface_from_router(
  46. r, subnet_id=sn.id)
  47. except Exception as ex:
  48. print("Failed to delete subnet from router as %s", ex)
  49. # After removing unnecessary subnet from router, retry to delete ports
  50. map_if_old(conn.network.delete_port,
  51. conn.network.ports())
  52. print('Subnets...')
  53. map_if_old(conn.network.delete_subnet,
  54. conn.network.subnets())
  55. print('Networks...')
  56. for n in conn.network.networks():
  57. if not n.is_router_external:
  58. fn_if_old(conn.network.delete_network, n)
  59. # runs the given fn to all elements of the that are older than allowed
  60. def map_if_old(fn, items):
  61. for item in items:
  62. fn_if_old(fn, item)
  63. # run the given fn function only if the passed item is older than allowed
  64. def fn_if_old(fn, item):
  65. created_at = datetime.datetime.strptime(item.created_at, DATE_FORMAT)
  66. if item.name == "default": # skip default security group
  67. return
  68. if created_at < oldest_allowed:
  69. print('Will delete %(name)s (%(id)s)' % item)
  70. if not args.dry_run:
  71. fn(item)
  72. if __name__ == '__main__':
  73. # execute only if run as a script
  74. main()