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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 pauses 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.4 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.4"
  30. REGISTRY_DIR = "REGISTRY_STORAGE_FILESYSTEM_ROOTREGISTRY_DIR"
  31. args = None
  32. os.environ['LC_ALL'] = 'C.UTF-8'
  33. def dockerized():
  34. '''Returns True if we're inside a Docker container, False otherwise.'''
  35. return os.path.isfile("/.dockerenv")
  36. def error(msg, bye=True):
  37. '''Prints an error message and optionally exit with a status code of 1'''
  38. print("ERROR: " + str(msg), file=sys.stderr)
  39. if bye:
  40. sys.exit(1)
  41. def remove(path):
  42. '''Run rmtree() in verbose mode'''
  43. rmtree(path)
  44. if not args.quiet:
  45. print("removed directory " + path)
  46. def clean_revisions(repo):
  47. '''Remove the revision manifests that are not present in the tags directory'''
  48. revisions = set(
  49. os.listdir(repo + "/_manifests/revisions/sha256/")
  50. )
  51. manifests = set(
  52. map(os.path.basename, iglob(repo + "/_manifests/tags/*/*/sha256/*"))
  53. )
  54. revisions.difference_update(manifests)
  55. for revision in revisions:
  56. remove(repo + "/_manifests/revisions/sha256/" + revision)
  57. def clean_tag(repo, tag):
  58. '''Clean a specific repo:tag'''
  59. link = repo + "/_manifests/tags/" + tag + "/current/link"
  60. if not os.path.isfile(link):
  61. error("No such tag: %s in repository %s" % (tag, repo), bye=False)
  62. return False
  63. if args.remove:
  64. remove(repo + "/_manifests/tags/" + tag)
  65. else:
  66. with open(link) as infile:
  67. current = infile.read()[len("sha256:"):]
  68. path = repo + "/_manifests/tags/" + tag + "/index/sha256/"
  69. for index in os.listdir(path):
  70. if index == current:
  71. continue
  72. remove(path + index)
  73. clean_revisions(repo)
  74. return True
  75. def clean_repo(image):
  76. '''Clean all tags (or a specific one, if specified) from a specific repository'''
  77. repo, tag = image.split(":", 1) if ":" in image else (image, "")
  78. if not os.path.isdir(repo):
  79. error("No such repository: " + repo, bye=False)
  80. return False
  81. if args.remove:
  82. tags = set(os.listdir(repo + "/_manifests/tags/"))
  83. if not tag or len(tags) == 1 and tag in tags:
  84. remove(repo)
  85. return True
  86. if tag:
  87. return clean_tag(repo, tag)
  88. currents = set()
  89. for link in iglob(repo + "/_manifests/tags/*/current/link"):
  90. with open(link) as infile:
  91. currents.add(infile.read()[len("sha256:"):])
  92. for index in iglob(repo + "/_manifests/tags/*/index/sha256/*"):
  93. if os.path.basename(index) not in currents:
  94. remove(index)
  95. clean_revisions(repo)
  96. return True
  97. def check_name(image):
  98. '''Checks the whole repository:tag name'''
  99. repo, tag = image.split(":", 1) if ":" in image else (image, "latest")
  100. # From https://github.com/moby/moby/blob/master/image/spec/v1.2.md
  101. # Tag values are limited to the set of characters [a-zA-Z0-9_.-], except they may not start with a . or - character.
  102. # Tags are limited to 128 characters.
  103. #
  104. # From https://github.com/docker/distribution/blob/master/docs/spec/api.md
  105. # 1. A repository name is broken up into path components. A component of a repository name must be at least
  106. # one lowercase, alpha-numeric characters, optionally separated by periods, dashes or underscores.
  107. # More strictly, it must match the regular expression [a-z0-9]+(?:[._-][a-z0-9]+)*
  108. # 2. If a repository name has two or more path components, they must be separated by a forward slash ("/").
  109. # 3. The total length of a repository name, including slashes, must be less than 256 characters.
  110. # Note: Internally, distribution permits multiple dashes and up to 2 underscores as separators.
  111. # See https://github.com/docker/distribution/blob/master/reference/regexp.go
  112. return len(image) < 256 and len(tag) < 129 and \
  113. re.match('[a-zA-Z0-9_][a-zA-Z0-9_.-]*$', tag) and \
  114. all(
  115. re.match('[a-z0-9]+(?:(?:[._]|__|[-]*)[a-z0-9]+)*$', path)
  116. for path in repo.split("/")
  117. )
  118. class RegistryCleaner():
  119. '''Simple callable class for Docker Registry cleaning duties'''
  120. def __init__(self, container_or_service=None, volume=None):
  121. try:
  122. self.docker = docker.from_env()
  123. except TLSParameterError as err:
  124. error(err)
  125. if volume:
  126. self.containers = None
  127. try:
  128. self.volume = self.docker.volumes.get(volume)
  129. self.registry_dir = self.volume.attrs['Mountpoint']
  130. except (APIError, exceptions.ConnectionError) as err:
  131. error(err)
  132. if dockerized():
  133. try:
  134. self.registry_dir = os.environ[REGISTRY_DIR]
  135. except KeyError:
  136. self.registry_dir = "/var/lib/registry"
  137. return
  138. self._get_info(container_or_service)
  139. if LooseVersion(self.get_image_version()) < LooseVersion("v2.4.0"):
  140. error("You're not running Docker Registry 2.4.0+")
  141. self.registry_dir = self.get_registry_dir()
  142. if dockerized():
  143. os.environ[REGISTRY_DIR] = self.registry_dir
  144. def __call__(self):
  145. try:
  146. os.chdir(self.registry_dir + "/docker/registry/v2/repositories")
  147. except FileNotFoundError as err:
  148. error(err)
  149. # We could use stop() but the orchestrator would start another container
  150. if self.containers is not None:
  151. for container in self.containers:
  152. if self.info['State']['Running']:
  153. self.docker.api.pause(container)
  154. images = args.images or \
  155. map(os.path.dirname, iglob("**/_manifests", recursive=True))
  156. exit_status = 0
  157. for image in images:
  158. if not clean_repo(image):
  159. exit_status = 1
  160. if not self.garbage_collect():
  161. exit_status = 1
  162. if self.containers is not None:
  163. for container in self.containers:
  164. if self.info['State']['Running']:
  165. self.docker.api.unpause(container)
  166. self.docker.close()
  167. return exit_status
  168. def _get_info(self, container_or_service):
  169. self.containers = []
  170. # Is a service?
  171. try:
  172. service = self.docker.services.get(container_or_service)
  173. except:
  174. pass
  175. else:
  176. # Get list of containers to pause them all
  177. try:
  178. tasks = service.tasks(filters={'desired-state': "running"})
  179. except (APIError, NotFound, exceptions.ConnectionError) as err:
  180. error(err)
  181. self.containers = [
  182. item['Status']['ContainerStatus']['ContainerID']
  183. for _, item in enumerate(tasks)
  184. ]
  185. # Get information from the first container in list.
  186. # We can't get the source of /var/lib/registry from inspect_service()
  187. # if a bind mount was not specified.
  188. try:
  189. self.info = self.docker.api.inspect_container(
  190. self.containers[0] if self.containers else container_or_service
  191. )
  192. except (APIError, NotFound, exceptions.ConnectionError) as err:
  193. error(err)
  194. if not self.containers:
  195. self.containers = [self.info['Id']]
  196. def get_file(self, path):
  197. '''Returns the contents of the specified file from the container'''
  198. try:
  199. with BytesIO(b"".join(
  200. _ for _ in self.docker.api.get_archive(self.containers[0], path)[0]
  201. )) as buf, tarfile.open(fileobj=buf) \
  202. as tar, tar.extractfile(os.path.basename(path)) \
  203. as infile:
  204. data = infile.read()
  205. except NotFound as err:
  206. error(err)
  207. return data
  208. def get_registry_dir(self):
  209. '''Gets the Registry directory'''
  210. registry_dir = os.getenv(REGISTRY_DIR)
  211. if registry_dir:
  212. return registry_dir
  213. for env in self.info['Config']['Env']:
  214. var, value = env.split("=", 1)
  215. if var == REGISTRY_DIR:
  216. registry_dir = value
  217. break
  218. if not registry_dir:
  219. config_yml = self.info['Args'][0]
  220. data = yaml.load(self.get_file(config_yml))
  221. try:
  222. registry_dir = data['storage']['filesystem']['rootdirectory']
  223. except KeyError:
  224. driver = [
  225. _ for _ in 'azure gcs inmemory oss s3 swift'.split()
  226. if _ in data['storage']
  227. ][0]
  228. error("Unsupported storage driver: " + driver)
  229. if dockerized():
  230. return registry_dir
  231. for item in self.info['Mounts']:
  232. if item['Destination'] == registry_dir:
  233. return item['Source']
  234. return None
  235. def get_image_version(self):
  236. '''Gets the Docker distribution version running on the container'''
  237. if self.info['State']['Running']:
  238. data = self.docker.containers.get(
  239. self.containers[0]
  240. ).exec_run("/bin/registry --version").output
  241. else:
  242. data = self.docker.containers.run(
  243. self.info['Config']['Image'], command="--version", remove=True
  244. )
  245. return data.decode('utf-8').split()[2]
  246. def garbage_collect(self):
  247. '''Runs garbage-collect'''
  248. command = "garbage-collect " + "/etc/docker/registry/config.yml"
  249. if dockerized():
  250. command = "/bin/registry " + command
  251. with subprocess.Popen(
  252. command.split(),
  253. stdout=subprocess.PIPE,
  254. stderr=subprocess.STDOUT
  255. ) as proc:
  256. if not args.quiet:
  257. print(proc.stdout.read().decode('utf-8'))
  258. status = proc.wait()
  259. else:
  260. cli = self.docker.containers.run(
  261. "registry:2",
  262. command=command,
  263. detach=True,
  264. stderr=True,
  265. volumes={
  266. self.registry_dir: {
  267. 'bind': "/var/lib/registry",
  268. 'mode': "rw"
  269. }
  270. }
  271. )
  272. if not args.quiet:
  273. for line in cli.logs(stream=True):
  274. print(line.decode('utf-8'), end="")
  275. status = bool(cli.wait()['StatusCode'] == 0)
  276. cli.remove()
  277. return status
  278. def main():
  279. '''Main function'''
  280. progname = os.path.basename(sys.argv[0])
  281. usage = "\rUsage: " + progname + " [OPTIONS] SERVICE|CONTAINER|VOLUME [REPOSITORY[:TAG]]..." + """
  282. Options:
  283. -x, --remove Remove the specified images or repositories.
  284. -v, --volume Specify a volume instead of container.
  285. -q, --quiet Supress non-error messages.
  286. -V, --version Show version and exit."""
  287. parser = ArgumentParser(usage=usage, add_help=False)
  288. parser.add_argument('-h', '--help', action='store_true')
  289. parser.add_argument('-q', '--quiet', action='store_true')
  290. parser.add_argument('-x', '--remove', action='store_true')
  291. parser.add_argument('-v', '--volume', action='store_true')
  292. parser.add_argument('-V', '--version', action='store_true')
  293. parser.add_argument('foobar', nargs='?')
  294. parser.add_argument('images', nargs='*')
  295. global args
  296. args = parser.parse_args()
  297. if args.help:
  298. print('usage: ' + usage)
  299. sys.exit(0)
  300. elif args.version:
  301. print(progname + " " + VERSION)
  302. sys.exit(0)
  303. elif not args.foobar:
  304. print('usage: ' + usage)
  305. sys.exit(1)
  306. for image in args.images:
  307. if not check_name(image):
  308. error("Invalid Docker repository/tag: " + image)
  309. if args.remove and not args.images:
  310. error("The -x option requires that you specify at least one repository...")
  311. if args.volume:
  312. cleaner = RegistryCleaner(volume=args.foobar)
  313. else:
  314. cleaner = RegistryCleaner(container_or_service=args.foobar)
  315. sys.exit(cleaner())
  316. if __name__ == "__main__":
  317. try:
  318. main()
  319. except KeyboardInterrupt:
  320. sys.exit(1)