1836.3.2
by Aaron Bentley
Add clean_lxc.py |
1 |
#!/usr/bin/env python
|
2 |
from __future__ import print_function |
|
3 |
||
4 |
from argparse import ArgumentParser |
|
5 |
from datetime import ( |
|
6 |
datetime, |
|
7 |
timedelta, |
|
8 |
)
|
|
9 |
import json |
|
10 |
import os |
|
11 |
import subprocess |
|
12 |
import sys |
|
13 |
||
1841.1.1
by Aaron Bentley
Use dateutil to calculate age of container. |
14 |
from dateutil import ( |
15 |
parser as date_parser, |
|
16 |
tz, |
|
17 |
)
|
|
18 |
||
1836.3.5
by Aaron Bentley
Fix lint. |
19 |
|
1836.3.2
by Aaron Bentley
Add clean_lxc.py |
20 |
def list_old_juju_containers(hours): |
21 |
env = dict(os.environ) |
|
22 |
containers = json.loads(subprocess.check_output([ |
|
23 |
'lxc', 'list', '--format', 'json'], env=env)) |
|
1841.1.1
by Aaron Bentley
Use dateutil to calculate age of container. |
24 |
now = datetime.now(tz.gettz('UTC')) |
1836.3.2
by Aaron Bentley
Add clean_lxc.py |
25 |
for container in containers: |
26 |
name = container['name'] |
|
27 |
if not name.startswith('juju-'): |
|
28 |
continue
|
|
1841.1.1
by Aaron Bentley
Use dateutil to calculate age of container. |
29 |
created_at = date_parser.parse(container['created_at']) |
1836.3.2
by Aaron Bentley
Add clean_lxc.py |
30 |
age = now - created_at |
31 |
if age <= timedelta(hours=hours): |
|
32 |
continue
|
|
33 |
yield name, age |
|
34 |
||
35 |
||
36 |
def main(): |
|
37 |
parser = ArgumentParser('Delete old juju containers') |
|
38 |
parser.add_argument('--dry-run', action='store_true', |
|
39 |
help='Do not actually delete.') |
|
40 |
parser.add_argument('--hours', type=int, default=1, |
|
41 |
help='Number of hours a juju container may exist.') |
|
42 |
args = parser.parse_args() |
|
43 |
for container, age in list_old_juju_containers(args.hours): |
|
1836.3.5
by Aaron Bentley
Fix lint. |
44 |
print('deleting {} ({} old)'.format(container, age)) |
1836.3.2
by Aaron Bentley
Add clean_lxc.py |
45 |
if args.dry_run: |
46 |
continue
|
|
47 |
subprocess.check_call(('lxc', 'delete', '--verbose', '--force', |
|
48 |
container)) |
|
49 |
||
50 |
||
51 |
if __name__ == '__main__': |
|
52 |
sys.exit(main()) |