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