Debian Codegraph @

httpd/docker/stap_image_cleanup.py

raw
1 # Note that this script was written to be executable by either version
2 # of python (checked by running pylint-2 and pylint-3 on it). Also
3 # note that the python version this script gets executed by is decided
4 # on by httpd/backends.cxx.
5
6 """Build a docker file and container image based on a JSON template."""
7
8 from __future__ import print_function
9 import subprocess
10 import sys
11 import json
12 import re
13 import datetime
14
15 def _eprint(*args, **kwargs):
16 """Print to stderr."""
17 print(*args, file=sys.stderr, **kwargs)
18
19 def main():
20 """Main function."""
21 try:
22 raw_json = subprocess.check_output(["buildah", "images", "--json"])
23 except subprocess.CalledProcessError as err:
24 _eprint('buildah images failed: %s' % err)
25 sys.exit(1)
26
27 try:
28 images_json = json.loads(raw_json)
29 except ValueError as err:
30 _eprint("Error: Invalid JSON input: %s" % err)
31 sys.exit(1)
32
33 _eprint(images_json)
34 name_regexp = re.compile(r'^sourceware.org/[a-f\d_]+/[a-f\d]+:(\d+)$')
35
36 # print the keys and values
37 for item in images_json:
38 #print("The item is ({})".format(item))
39 if not isinstance(item, dict):
40 _eprint("Expected a json dict, got a %s" % type(item))
41 continue
42
43 for key in item:
44 value = item[key]
45 if key != "names":
46 continue
47
48 # The value of 'names' should be a list of names for this
49 # image.
50 if not isinstance(value, list):
51 _eprint("Expected a json list, got a %s" % type(value))
52 continue
53
54 for name in value:
55 match = name_regexp.match(name)
56 if match:
57 date_str = match.group(1)
58 print("full name: %s, date: %s" % (name, date_str))
59
60 # Convert the date string into a numeric date/time.
61 dt_then = datetime.datetime.strptime(date_str, "%Y%m%d%H%M")
62 dt_now = datetime.datetime.utcnow()
63
64 # If for some reason the image date is in the
65 # future, skip it.
66 if dt_then >= dt_now:
67 continue
68
69 time_delta = dt_now - dt_then
70 two_days = datetime.timedelta(days=2)
71 if time_delta > two_days:
72 if subprocess.call(["buildah", "rmi", name]) == 0:
73 print("Remove %s" % name)
74 else:
75 _eprint("Error removing image %s" % name)
76 print("")
77 sys.exit(0)
78
79 if __name__ == '__main__':
80 main()