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.

98 lines
3.1 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. for ip in conn.network.ips():
  50. fn_if_old(conn.network.delete_ip, ip)
  51. # After removing unnecessary subnet from router, retry to delete ports
  52. map_if_old(conn.network.delete_port,
  53. conn.network.ports())
  54. print('Subnets...')
  55. map_if_old(conn.network.delete_subnet,
  56. conn.network.subnets())
  57. print('Networks...')
  58. for n in conn.network.networks():
  59. if not n.is_router_external:
  60. fn_if_old(conn.network.delete_network, n)
  61. # runs the given fn to all elements of the that are older than allowed
  62. def map_if_old(fn, items):
  63. for item in items:
  64. fn_if_old(fn, item)
  65. # run the given fn function only if the passed item is older than allowed
  66. def fn_if_old(fn, item):
  67. created_at = datetime.datetime.strptime(item.created_at, DATE_FORMAT)
  68. if item.name == "default": # skip default security group
  69. return
  70. if created_at < oldest_allowed:
  71. print('Will delete %(name)s (%(id)s)' % item)
  72. if not args.dry_run:
  73. fn(item)
  74. if __name__ == '__main__':
  75. # execute only if run as a script
  76. main()