Clean the Docker Registry by removing untagged repositories https://github.com/ricardobranco777/clean_registry
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

clean_registry.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #!/usr/bin/env python3
  2. """
  3. This script purges untagged repositories and runs the garbage collector in Docker Registry >= 2.4.0.
  4. It works on the whole registry or the specified repositories.
  5. The optional -x flag may be used to completely remove the specified repositories or tagged images.
  6. NOTES:
  7. - This script stops the Registry container during cleanup to prevent corruption,
  8. making it temporarily unavailable to clients.
  9. - This script assumes local storage (the filesystem storage driver).
  10. - This script may run stand-alone (on local setups) or dockerized (which supports remote Docker setups).
  11. - This script is Python 3 only.
  12. v1.3 by Ricardo Branco
  13. MIT License
  14. """
  15. import os
  16. import re
  17. import sys
  18. import tarfile
  19. import subprocess
  20. from argparse import ArgumentParser
  21. from distutils.version import LooseVersion
  22. from glob import iglob
  23. from io import BytesIO
  24. from shutil import rmtree
  25. from requests import exceptions
  26. import docker
  27. from docker.errors import APIError, NotFound, TLSParameterError
  28. import yaml
  29. VERSION = "1.3"
  30. REGISTRY_DIR = "REGISTRY_STORAGE_FILESYSTEM_ROOTREGISTRY_DIR"
  31. def dockerized():
  32. '''Returns True if we're inside a Docker container, False otherwise.'''
  33. return os.path.isfile("/.dockerenv")
  34. def error(msg, bye=True):
  35. '''Prints an error message and optionally exit with a status code of 1'''
  36. print("ERROR: " + str(msg), file=sys.stderr)
  37. if bye:
  38. sys.exit(1)
  39. def remove(path):
  40. '''Run rmtree() in verbose mode'''
  41. rmtree(path)
  42. if not args.quiet:
  43. print("removed directory " + path)
  44. def clean_revisions(repo):
  45. '''Remove the revision manifests that are not present in the tags directory'''
  46. revisions = set(os.listdir(repo + "/_manifests/revisions/sha256/"))
  47. manifests = set(map(os.path.basename, iglob(repo + "/_manifests/tags/*/*/sha256/*")))
  48. revisions.difference_update(manifests)
  49. for revision in revisions:
  50. remove(repo + "/_manifests/revisions/sha256/" + revision)
  51. def clean_tag(repo, tag):
  52. '''Clean a specific repo:tag'''
  53. link = repo + "/_manifests/tags/" + tag + "/current/link"
  54. if not os.path.isfile(link):
  55. error("No such tag: %s in repository %s" % (tag, repo), bye=False)
  56. return False
  57. if args.remove:
  58. remove(repo + "/_manifests/tags/" + tag)
  59. else:
  60. with open(link) as infile:
  61. current = infile.read()[len("sha256:"):]
  62. path = repo + "/_manifests/tags/" + tag + "/index/sha256/"
  63. for index in os.listdir(path):
  64. if index == current:
  65. continue
  66. remove(path + index)
  67. clean_revisions(repo)
  68. return True
  69. def clean_repo(image):
  70. '''Clean all tags (or a specific one, if specified) from a specific repository'''
  71. repo, tag = image.split(":", 1) if ":" in image else (image, "")
  72. if not os.path.isdir(repo):
  73. error("No such repository: " + repo, bye=False)
  74. return False
  75. if args.remove:
  76. tags = os.listdir(repo + "/_manifests/tags/")
  77. if not tag or len(tags) == 1 and tag in tags:
  78. remove(repo)
  79. return True
  80. if tag:
  81. return clean_tag(repo, tag)
  82. currents = set()
  83. for link in iglob(repo + "/_manifests/tags/*/current/link"):
  84. with open(link) as infile:
  85. currents.add(infile.read()[len("sha256:"):])
  86. for index in iglob(repo + "/_manifests/tags/*/index/sha256/*"):
  87. if os.path.basename(index) not in currents:
  88. remove(index)
  89. clean_revisions(repo)
  90. return True
  91. def check_name(image):
  92. '''Checks the whole repository:tag name'''
  93. repo, tag = image.split(":", 1) if ":" in image else (image, "latest")
  94. # From https://github.com/moby/moby/blob/master/image/spec/v1.2.md
  95. # Tag values are limited to the set of characters [a-zA-Z0-9_.-], except they may not start with a . or - character.
  96. # Tags are limited to 128 characters.
  97. #
  98. # From https://github.com/docker/distribution/blob/master/docs/spec/api.md
  99. # 1. A repository name is broken up into path components. A component of a repository name must be at least
  100. # one lowercase, alpha-numeric characters, optionally separated by periods, dashes or underscores.
  101. # More strictly, it must match the regular expression [a-z0-9]+(?:[._-][a-z0-9]+)*
  102. # 2. If a repository name has two or more path components, they must be separated by a forward slash ("/").
  103. # 3. The total length of a repository name, including slashes, must be less than 256 characters.
  104. # Note: Internally, distribution permits multiple dashes and up to 2 underscores as separators.
  105. # See https://github.com/docker/distribution/blob/master/reference/regexp.go
  106. return len(image) < 256 and len(tag) < 129 and re.match('[a-zA-Z0-9_][a-zA-Z0-9_.-]*$', tag) and \
  107. all(re.match('[a-z0-9]+(?:(?:[._]|__|[-]*)[a-z0-9]+)*$', path) for path in repo.split("/"))
  108. class RegistryCleaner():
  109. '''Simple callable class for Docker Registry cleaning duties'''
  110. def __init__(self, container=None, volume=None):
  111. try:
  112. self.docker = docker.from_env()
  113. except TLSParameterError as err:
  114. error(err)
  115. if container is None:
  116. self.container = None
  117. try:
  118. self.volume = self.docker.volumes.get(volume)
  119. self.registry_dir = self.volume.attrs['Mountpoint']
  120. except (APIError, exceptions.ConnectionError) as err:
  121. error(err)
  122. if dockerized():
  123. try:
  124. self.registry_dir = os.environ[REGISTRY_DIR]
  125. except KeyError:
  126. self.registry_dir = "/var/lib/registry"
  127. return
  128. try:
  129. self.info = self.docker.api.inspect_container(container)
  130. self.container = self.info['Id']
  131. except (APIError, exceptions.ConnectionError) as err:
  132. error(err)
  133. if self.info['Config']['Image'] != "registry:2":
  134. error("The container %s is not running the registry:2 image" % (container))
  135. if LooseVersion(self.get_image_version()) < LooseVersion("v2.4.0"):
  136. error("You're not running Docker Registry 2.4.0+")
  137. self.registry_dir = self.get_registry_dir()
  138. if dockerized():
  139. os.environ[REGISTRY_DIR] = self.registry_dir
  140. def __call__(self):
  141. try:
  142. os.chdir(self.registry_dir + "/docker/registry/v2/repositories")
  143. except FileNotFoundError as err:
  144. error(err)
  145. if self.container is not None:
  146. self.docker.api.stop(self.container)
  147. images = args.images or map(os.path.dirname, iglob("**/_manifests", recursive=True))
  148. exit_status = 0
  149. for image in images:
  150. if not clean_repo(image):
  151. exit_status = 1
  152. if not self.garbage_collect():
  153. exit_status = 1
  154. if self.container is not None:
  155. self.docker.api.start(self.container)
  156. self.docker.close()
  157. return exit_status
  158. def get_file(self, path):
  159. '''Returns the contents of the specified file from the container'''
  160. try:
  161. with BytesIO(
  162. b"".join(_ for _ in self.docker.api.get_archive(self.container, path)[0])
  163. ) as buf, tarfile.open(fileobj=buf) as tar, tar.extractfile(os.path.basename(path)) as infile:
  164. data = infile.read()
  165. except NotFound as err:
  166. error(err)
  167. return data
  168. def get_registry_dir(self):
  169. '''Gets the Registry directory'''
  170. registry_dir = os.getenv(REGISTRY_DIR)
  171. if registry_dir:
  172. return registry_dir
  173. for env in self.info['Config']['Env']:
  174. var, value = env.split("=", 1)
  175. if var == REGISTRY_DIR:
  176. registry_dir = value
  177. break
  178. if not registry_dir:
  179. config_yml = self.info['Args'][0]
  180. data = yaml.load(self.get_file(config_yml))
  181. try:
  182. registry_dir = data['storage']['filesystem']['rootdirectory']
  183. except KeyError:
  184. driver = [k for k in 'azure gcs inmemory oss s3 swift'.split() if k in data['storage']][0]
  185. error("Unsupported storage driver: " + driver)
  186. if dockerized():
  187. return registry_dir
  188. for item in self.info['Mounts']:
  189. if item['Destination'] == registry_dir:
  190. return item['Source']
  191. def get_image_version(self):
  192. '''Gets the Docker distribution version running on the container'''
  193. if self.info['State']['Running']:
  194. data = self.docker.containers.get(self.container).exec_run("/bin/registry --version").output
  195. else:
  196. data = self.docker.containers.run(self.info["Image"], command="--version", remove=True)
  197. return data.decode('utf-8').split()[2]
  198. def garbage_collect(self):
  199. '''Runs garbage-collect'''
  200. command = "garbage-collect " + "/etc/docker/registry/config.yml"
  201. if dockerized():
  202. command = "/bin/registry " + command
  203. with subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc:
  204. if not args.quiet:
  205. print(proc.stdout.read().decode('utf-8'))
  206. status = proc.wait()
  207. else:
  208. cli = self.docker.containers.run("registry:2", command=command, detach=True, stderr=True,
  209. volumes={self.registry_dir: {'bind': "/var/lib/registry", 'mode': "rw"}})
  210. if not args.quiet:
  211. for line in cli.logs(stream=True):
  212. print(line.decode('utf-8'), end="")
  213. status = bool(cli.wait()['StatusCode'] == 0)
  214. cli.remove()
  215. return status
  216. def main():
  217. '''Main function'''
  218. progname = os.path.basename(sys.argv[0])
  219. usage = "\rUsage: " + progname + " [OPTIONS] VOLUME|CONTAINER [REPOSITORY[:TAG]]..." + """
  220. Options:
  221. -x, --remove Remove the specified images or repositories.
  222. -v, --volume Specify a volume instead of container.
  223. -q, --quiet Supress non-error messages.
  224. -V, --version Show version and exit."""
  225. parser = ArgumentParser(usage=usage, add_help=False)
  226. parser.add_argument('-h', '--help', action='store_true')
  227. parser.add_argument('-q', '--quiet', action='store_true')
  228. parser.add_argument('-x', '--remove', action='store_true')
  229. parser.add_argument('-v', '--volume', action='store_true')
  230. parser.add_argument('-V', '--version', action='store_true')
  231. parser.add_argument('container_or_volume', nargs='?')
  232. parser.add_argument('images', nargs='*')
  233. global args
  234. args = parser.parse_args()
  235. if args.help:
  236. print('usage: ' + usage)
  237. sys.exit(0)
  238. elif args.version:
  239. print(progname + " " + VERSION)
  240. sys.exit(0)
  241. elif not args.container_or_volume:
  242. print('usage: ' + usage)
  243. sys.exit(1)
  244. for image in args.images:
  245. if not check_name(image):
  246. error("Invalid Docker repository/tag: " + image)
  247. if args.remove and not args.images:
  248. error("The -x option requires that you specify at least one repository...")
  249. if args.volume:
  250. cleaner = RegistryCleaner(volume=args.container_or_volume)
  251. else:
  252. cleaner = RegistryCleaner(container=args.container_or_volume)
  253. sys.exit(cleaner())
  254. if __name__ == "__main__":
  255. try:
  256. main()
  257. except KeyboardInterrupt:
  258. sys.exit(1)