diff --git a/gns3server/api/routes/compute/images.py b/gns3server/api/routes/compute/images.py index 5e5f6410b..2d631b84b 100644 --- a/gns3server/api/routes/compute/images.py +++ b/gns3server/api/routes/compute/images.py @@ -73,6 +73,22 @@ async def load_docker_image( await docker_manager.load_image(request.stream(), image=image, digest=digest) +@router.delete("/docker/images/{image:path}", status_code=status.HTTP_204_NO_CONTENT) +async def delete_docker_image( + image: str, + force: bool = Query(False, description="Remove the image even if a container uses it"), +) -> None: + """ + Delete a Docker image from the Docker daemon. + + The daemon refuses to delete an image used by a container (even a stopped + one) and answers a conflict, unless force is set. + """ + + docker_manager = Docker.instance() + await docker_manager.delete_image(urllib.parse.unquote(image), force=force) + + @router.get("/dynamips/images") async def get_dynamips_images() -> List[dict]: """ diff --git a/gns3server/api/routes/controller/computes.py b/gns3server/api/routes/controller/computes.py index ab1830709..90bd51486 100644 --- a/gns3server/api/routes/controller/computes.py +++ b/gns3server/api/routes/controller/computes.py @@ -247,6 +247,29 @@ async def docker_load_image(compute_id: Union[str, UUID], request: Request) -> N await compute.http_query("POST", "/docker/images/load", data=request.stream(), timeout=None) +@router.delete( + "/{compute_id}/docker/images/{image:path}", + status_code=status.HTTP_204_NO_CONTENT, + dependencies=[Depends(has_privilege("Compute.Modify"))], +) +async def docker_delete_image( + compute_id: Union[str, UUID], + image: str, + force: bool = Query(False, description="Remove the image even if a container uses it"), +) -> None: + """ + Delete a Docker image on a compute. + + The compute refuses to delete an image used by a container (even a stopped + one) and answers a conflict, unless force is set. + + Required privilege: Compute.Modify + """ + + compute = Controller.instance().get_compute(str(compute_id)) + await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()}) + + @router.get("/{compute_id}/virtualbox/vms", response_model=List[schemas.ComputeVirtualBoxVM]) async def virtualbox_vms(compute_id: Union[str, UUID]) -> List[schemas.ComputeVirtualBoxVM]: """ diff --git a/gns3server/compute/docker/__init__.py b/gns3server/compute/docker/__init__.py index fdb3eaf51..588ce63fc 100644 --- a/gns3server/compute/docker/__init__.py +++ b/gns3server/compute/docker/__init__.py @@ -526,5 +526,25 @@ class Docker(BaseManager): if image["RepoTags"]: for tag in image["RepoTags"]: if tag != ":": - images.append({"image": tag}) + images.append( + { + "image": tag, + "id": image.get("Id"), + "size": image.get("Size"), + "created": image.get("Created"), + } + ) return sorted(images, key=lambda i: i["image"]) + + async def delete_image(self, image, force=False): + """ + Delete a Docker image from the Docker daemon. + + :param image: Image name or id + :param force: Remove the image even if a container uses it + """ + + await self.query("DELETE", f"images/{image}", params={"force": force}) + # the image id translation recorded when this image was synced from the + # controller no longer matches anything on this daemon + self._image_id_translations.pop(image, None) diff --git a/gns3server/schemas/controller/computes.py b/gns3server/schemas/controller/computes.py index 873228a70..e8df6658a 100644 --- a/gns3server/schemas/controller/computes.py +++ b/gns3server/schemas/controller/computes.py @@ -146,6 +146,9 @@ class ComputeDockerImage(BaseModel): """ image: str = Field(..., description="Docker image name") + id: Optional[str] = Field(None, description="Docker image id reported by the daemon") + size: Optional[int] = Field(None, description="Docker image size in bytes") + created: Optional[Union[int, str]] = Field(None, description="Docker image creation date (unix timestamp)") class AutoIdlePC(BaseModel): diff --git a/tests/api/routes/compute/test_images.py b/tests/api/routes/compute/test_images.py index 8d4e0c5d5..041a55702 100644 --- a/tests/api/routes/compute/test_images.py +++ b/tests/api/routes/compute/test_images.py @@ -55,6 +55,25 @@ class TestImagesRoutes: assert hasattr(stream, "__aiter__") assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_delete_docker_image(self, app: FastAPI, compute_client: AsyncClient) -> None: + + with asyncio_patch("gns3server.compute.docker.Docker.delete_image") as mock: + response = await compute_client.delete( + app.url_path_for("compute:delete_docker_image", image="ios-xr/xrd-control-plane:24.4.1") + ) + mock.assert_called_once_with("ios-xr/xrd-control-plane:24.4.1", force=False) + assert response.status_code == status.HTTP_204_NO_CONTENT + + async def test_delete_docker_image_force(self, app: FastAPI, compute_client: AsyncClient) -> None: + + with asyncio_patch("gns3server.compute.docker.Docker.delete_image") as mock: + response = await compute_client.delete( + app.url_path_for("compute:delete_docker_image", image="ubuntu:latest"), + params={"force": "true"}, + ) + mock.assert_called_once_with("ubuntu:latest", force=True) + assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_load_docker_image_with_image_and_digest(self, app: FastAPI, compute_client: AsyncClient) -> None: digest = "sha256:" + "a" * 64 diff --git a/tests/api/routes/controller/test_computes.py b/tests/api/routes/controller/test_computes.py index 4ae3b8c21..c32b245e8 100644 --- a/tests/api/routes/controller/test_computes.py +++ b/tests/api/routes/controller/test_computes.py @@ -182,7 +182,10 @@ class TestComputeFeatures: ) as mock: response = await client.get(app.url_path_for("docker_get_images", compute_id=compute_id)) mock.assert_called_with("GET", "docker", "images") - assert response.json() == [{"image": "docker1"}, {"image": "docker2"}] + assert response.json() == [ + {"image": "docker1", "id": None, "size": None, "created": None}, + {"image": "docker2", "id": None, "size": None, "created": None}, + ] async def test_compute_pull_docker_image(self, app: FastAPI, client: AsyncClient, test_compute: Compute) -> None: @@ -197,6 +200,27 @@ class TestComputeFeatures: compute.forward.assert_called_with("POST", "docker", "images/pull", data={"image": "nginx:latest"}) assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_compute_delete_docker_image(self, app: FastAPI, client: AsyncClient, test_compute: Compute) -> None: + + compute = MagicMock() + compute.http_query = AsyncioMagicMock(return_value={}) + with patch("gns3server.api.routes.controller.computes.Controller.instance") as controller: + controller.return_value.get_compute.return_value = compute + response = await client.delete( + app.url_path_for( + "docker_delete_image", + compute_id=test_compute.compute_id, + image="ios-xr/xrd-control-plane:24.4.1", + ), + params={"force": True}, + ) + compute.http_query.assert_called_once_with( + "DELETE", + "/docker/images/ios-xr/xrd-control-plane:24.4.1", + params={"force": "true"}, + ) + assert response.status_code == status.HTTP_204_NO_CONTENT + async def test_compute_load_docker_image(self, app: FastAPI, client: AsyncClient, test_compute: Compute) -> None: compute = MagicMock() diff --git a/tests/compute/docker/test_docker.py b/tests/compute/docker/test_docker.py index 7fe316f67..ef031ce6b 100644 --- a/tests/compute/docker/test_docker.py +++ b/tests/compute/docker/test_docker.py @@ -132,11 +132,14 @@ async def test_list_images(): images = await Docker.instance().list_images() mock.assert_called_with("GET", "images/json", params={"all": 0}) assert len(images) == 5 - assert {"image": "ubuntu:12.04"} in images - assert {"image": "ubuntu:precise"} in images - assert {"image": "ubuntu:latest"} in images - assert {"image": "ubuntu:12.10"} in images - assert {"image": "ubuntu:quantal"} in images + by_tag = {image["image"]: image for image in images} + assert by_tag["ubuntu:12.04"]["id"] == "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c" + assert by_tag["ubuntu:12.04"]["size"] == 131506275 + assert by_tag["ubuntu:12.04"]["created"] == 1365714795 + # tags of the same image share its id + assert by_tag["ubuntu:precise"]["id"] == by_tag["ubuntu:12.04"]["id"] + assert ":" not in by_tag + assert {"ubuntu:precise", "ubuntu:latest", "ubuntu:12.10", "ubuntu:quantal"} <= set(by_tag) @pytest.mark.asyncio @@ -330,6 +333,36 @@ async def test_load_image_error(): response.close.assert_called_once() +@pytest.mark.asyncio +async def test_delete_image(): + + docker = Docker.instance() + docker._image_id_translations["ubuntu:latest"] = ("sha256:" + "a" * 64, "sha256:" + "b" * 64) + + with asyncio_patch("gns3server.compute.docker.Docker.query") as mock: + await docker.delete_image("ubuntu:latest", force=True) + mock.assert_called_with("DELETE", "images/ubuntu:latest", params={"force": True}) + # deleting the image drops the id translation recorded for a previous sync + assert docker.image_id_translation("ubuntu:latest") is None + + +@pytest.mark.asyncio +async def test_delete_image_error_keeps_translation(): + """ + When the daemon refuses the deletion the image is still there, so the id + translation recorded for a previous sync stays valid. + """ + + docker = Docker.instance() + translation = ("sha256:" + "a" * 64, "sha256:" + "b" * 64) + docker._image_id_translations["ubuntu:latest"] = translation + + with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerError("conflict: image is in use")): + with pytest.raises(DockerError, match="image is in use"): + await docker.delete_image("ubuntu:latest") + assert docker.image_id_translation("ubuntu:latest") == translation + + @pytest.mark.asyncio async def test_docker_check_connection_docker_minimum_version(vm):