|
| 1 | +from datetime import datetime, timedelta |
| 2 | +from dateutil import parser |
| 3 | +from dateutil.tz import tzutc |
| 4 | +import re |
| 5 | + |
| 6 | +from docker.errors import APIError |
| 7 | + |
| 8 | +from dockerrotate.filter import include_image |
| 9 | + |
| 10 | + |
| 11 | +TIME_REGEX = re.compile(r'((?P<days>\d+?)d)?((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?') # noqa |
| 12 | + |
| 13 | + |
| 14 | +def parse_time(time_str): |
| 15 | + """ |
| 16 | + Parse a human readable time delta string. |
| 17 | + """ |
| 18 | + parts = TIME_REGEX.match(time_str) |
| 19 | + if not parts: |
| 20 | + raise Exception("Invalid time delta format '{}'".format(time_str)) |
| 21 | + parts = parts.groupdict() |
| 22 | + time_params = {} |
| 23 | + for (name, param) in parts.iteritems(): |
| 24 | + if param: |
| 25 | + time_params[name] = int(param) |
| 26 | + return timedelta(**time_params) |
| 27 | + |
| 28 | + |
| 29 | +def include_container(container, args): |
| 30 | + """ |
| 31 | + Return truthy if container should be removed. |
| 32 | + """ |
| 33 | + inspect_data = args.client.inspect_container(container["Id"]) |
| 34 | + status = inspect_data["State"]["Status"] |
| 35 | + |
| 36 | + if status == "exited": |
| 37 | + finished_at = parser.parse(inspect_data["State"]["FinishedAt"]) |
| 38 | + if (args.now - finished_at) < args.exited_ts: |
| 39 | + return False |
| 40 | + elif status == "created": |
| 41 | + created_at = parser.parse(inspect_data["Created"]) |
| 42 | + if (args.now - created_at) < args.created_ts: |
| 43 | + return False |
| 44 | + else: |
| 45 | + return False |
| 46 | + |
| 47 | + return include_image([container["Image"]], args) |
| 48 | + |
| 49 | + |
| 50 | +def clean_containers(args): |
| 51 | + """ |
| 52 | + Delete non-running containers. |
| 53 | +
|
| 54 | + Images cannot be deleted if in use. Deleting dead containers allows |
| 55 | + more images to be cleaned. |
| 56 | + """ |
| 57 | + args.exited_ts = parse_time(args.exited) |
| 58 | + args.created_ts = parse_time(args.created) |
| 59 | + args.now = datetime.now(tzutc()) |
| 60 | + |
| 61 | + containers = [ |
| 62 | + container for container in args.client.containers(all=True) |
| 63 | + if include_container(container, args) |
| 64 | + ] |
| 65 | + |
| 66 | + for container in containers: |
| 67 | + print "Removing container ID: {}, Name: {}, Image: {}".format( |
| 68 | + container["Id"], |
| 69 | + (container.get("Names") or ["N/A"])[0], |
| 70 | + container["Image"], |
| 71 | + ) |
| 72 | + |
| 73 | + if args.dry_run: |
| 74 | + continue |
| 75 | + |
| 76 | + try: |
| 77 | + args.client.remove_container(container["Id"]) |
| 78 | + except APIError as error: |
| 79 | + print "Unable to remove container: {}: {}".format( |
| 80 | + container["Id"], |
| 81 | + error, |
| 82 | + ) |
0 commit comments