Created
December 30, 2015 14:54
-
-
Save d-tux/fe6b749584802aaa6ce1 to your computer and use it in GitHub Desktop.
Searches and removes dangling docker volumes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Largely based on https://github.com/docker/docker/issues/6354#issuecomment-60817733 | |
| All credit goes to https://github.com/adamhadani | |
| """ | |
| import logging | |
| import os | |
| import os.path | |
| import sys | |
| import argparse | |
| from shutil import rmtree | |
| import docker | |
| def get_immediate_subdirectories(a_dir): | |
| return [os.path.join(a_dir, name) for name in os.listdir(a_dir) | |
| if os.path.isdir(os.path.join(a_dir, name))] | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Identify and remove dangling Docker volumes.') | |
| parser.add_argument('-k', '--clean', dest='clean', action='store_true') | |
| options = parser.parse_args() | |
| logging.basicConfig(level=logging.INFO, format="%(message)s") | |
| client = docker.Client() | |
| DOCKER_VOLUMES_DIR = os.path.join(client.info()['DockerRootDir'], 'volumes') | |
| valid_dirs = [] | |
| for container in client.containers(all=True): | |
| volumes = client.inspect_container(container['Id'])['Volumes'] | |
| if not volumes: | |
| continue | |
| for _, real_path in volumes.iteritems(): | |
| if real_path.startswith(DOCKER_VOLUMES_DIR): | |
| valid_dirs.append(real_path) | |
| all_dirs = get_immediate_subdirectories(DOCKER_VOLUMES_DIR) | |
| invalid_dirs = set(all_dirs).difference(valid_dirs) | |
| logging.info("%s dangling Docker volumes out of %s total volumes found.", len(invalid_dirs), len(all_dirs)) | |
| for invalid_dir in invalid_dirs: | |
| if options.clean: | |
| logging.info("Purging directory: %s", invalid_dir) | |
| rmtree(invalid_dir) | |
| else: | |
| logging.info("Dangling volume: %s", invalid_dir) | |
| logging.info("All done.") | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment