This repository was archived by the owner on May 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·60 lines (50 loc) · 1.89 KB
/
run.py
File metadata and controls
executable file
·60 lines (50 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import os
import sys
if len(sys.argv) > 1 and sys.argv[1].startswith('/'):
os.execvp(sys.argv[1], sys.argv[1:])
import time
import docker
import argparse
from datetime import datetime as dt
from dateutil.parser import parse
from dateutil.tz import tzutc
parser = argparse.ArgumentParser()
parser.add_argument('--dry-run', '-n',
action='store_true',
help="perform a trial run with no changes made")
parser.add_argument('--loop-delay',
default=0,
type=int,
help="sleep a certain delay in seconds (0 to disable)")
parser.add_argument('--min-age',
default=0,
type=int,
help=("only clean containers stopped since a certain time "
"in seconds (0 to disable)"))
def is_container_to_delete(client, container):
info = client.inspect_container(container)
age = (dt.now(tzutc()) - parse(info['State']['FinishedAt'])).total_seconds()
return (not info['State']['Running'] and
age > args.min_age and
info['HostConfig']['RestartPolicy']['MaximumRetryCount'] == 0)
def clean_containers(client):
to_delete = [x for x in client.containers(all=True)
if is_container_to_delete(client, x)]
for container in to_delete:
try:
if not args.dry_run:
client.remove_container(container=container, v=True)
except docker.errors.APIError as exc:
print(exc.explanation)
else:
print("Deleted:", container['Id'])
args = parser.parse_args()
client = docker.Client(base_url="unix://tmp/docker.sock", version='auto')
if args.loop_delay:
while True:
time.sleep(args.loop_delay)
clean_containers(client)
else:
clean_containers(client)