diff --git a/README.md b/README.md index ec4c60e..8b3aeb4 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,12 @@ $ d2-docker start dhis2-sierra.tgz On the first run, the images will been created, but you can either run this command again or the standard `start DHIS2_DATA_IMAGE_NAME`. +### Delete image/containers linked to an instance + +``` +$ d2-docker rm eyeseetea/dhis2-data:2.30-sierra +``` + ### Copy Docker images to/from local directories You can use a Docker image or a data directory (db + apps) as source, that will create a new Docker image _eyeseetea/dhis2-data:2.30-sierra2_ and a `sierra-data/` directory: diff --git a/src/d2_docker/cli.py b/src/d2_docker/cli.py index a600918..571a647 100644 --- a/src/d2_docker/cli.py +++ b/src/d2_docker/cli.py @@ -7,6 +7,7 @@ start, logs, stop, + rm, commit, push, copy, @@ -17,7 +18,20 @@ create, ) -COMMAND_MODULES = [start, logs, stop, commit, push, copy, export, import_, list_, run_sql, create] +COMMAND_MODULES = [ + start, + logs, + stop, + rm, + commit, + push, + copy, + export, + import_, + list_, + run_sql, + create, +] def get_parser(): diff --git a/src/d2_docker/commands/rm.py b/src/d2_docker/commands/rm.py new file mode 100644 index 0000000..a645f52 --- /dev/null +++ b/src/d2_docker/commands/rm.py @@ -0,0 +1,24 @@ +from d2_docker import utils + +DESCRIPTION = "Remove dhis2-data docker images/containers" + + +def setup(parser): + parser.add_argument("images", metavar="IMAGE", nargs="+", help="Docker dhis2-data images") + + +def run(args): + for image in args.images: + remove_image(image) + + +def remove_image(image): + utils.logger.info("Delete image/containers: {}".format(image)) + utils.run_docker_compose(["stop"], image) + result = utils.run_docker_compose(["ps", "-q"], data_image=image, capture_output=True) + container_ids = result.stdout.decode("utf-8").splitlines() + utils.logger.debug("Container IDs: {}".format(container_ids)) + if container_ids: + utils.run_docker(["container", "rm", *container_ids]) + utils.run_docker(["image", "rm", image]) + utils.logger.info("Removed: {}".format(image)) diff --git a/src/d2_docker/utils.py b/src/d2_docker/utils.py index 8376e55..b5e9c3e 100644 --- a/src/d2_docker/utils.py +++ b/src/d2_docker/utils.py @@ -91,6 +91,13 @@ def get_running_image_name(): raise D2DockerError("Multiple d2-docker images running, specify one:\n{}".format(names)) +def run_docker(args): + """Run docker.""" + cmd = ["docker", *args] + result = run(cmd, capture_output=True) + return [s.strip() for s in result.stdout.decode("utf-8").splitlines()] + + def run_docker_ps(args): """Run docker ps filtered by app label and return output lines.""" cmd = ["docker", "ps", "--filter", "label=" + IMAGE_NAME_LABEL, *args]