diff --git a/gns3server/api/routes/controller/computes.py b/gns3server/api/routes/controller/computes.py index 9123d7eae..b7cb04920 100644 --- a/gns3server/api/routes/controller/computes.py +++ b/gns3server/api/routes/controller/computes.py @@ -26,7 +26,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Reques import gns3server.db.models as models from gns3server import schemas from gns3server.controller import Controller -from gns3server.controller.controller_error import ComputeConflictError, ControllerBadRequestError, ControllerError +from gns3server.controller.controller_error import ControllerBadRequestError, ControllerError from gns3server.db.repositories.computes import ComputesRepository from gns3server.db.repositories.rbac import RbacRepository from gns3server.db.repositories.templates import TemplatesRepository @@ -277,14 +277,14 @@ async def docker_delete_image( """ 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 naming the GNS3 nodes and projects using it, - unless force is set. + The deletion is refused while templates reference the image, unless force + is set. The compute also refuses an image used by a container (even a + stopped one) and answers a conflict naming the GNS3 nodes and projects + using it. - Templates referencing the image do not block the deletion but are named in - the conflict error, and a docker.image.deleted notification reporting them - is emitted on the controller notification stream after a successful - deletion. + After a successful deletion a docker.image.deleted notification is + emitted on the controller notification stream, with the templates that + referenced the image, so clients can refresh their image lists. Required privilege: Compute.Modify """ @@ -303,17 +303,21 @@ async def docker_delete_image( and canonical_docker_image_name(str(template.image)) == canonical_image ] + if referencing_templates and not force: + # refuse before touching the compute: the client can prompt the user + # and repeat with force once the user confirms + raise ControllerError( + f"Image '{image}' is referenced by template(s): {', '.join(referencing_templates)}. " + f"Delete the templates first or repeat with force=true.", + code="image_referenced_by_templates", + details={"referenced_by_templates": referencing_templates}, + ) + compute = Controller.instance().get_compute(str(compute_id)) - try: - await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()}) - except ComputeConflictError as e: - if referencing_templates: - response = e.response() - response["message"] += f" The image is also referenced by template(s): {', '.join(referencing_templates)}." - raise ComputeConflictError(e.url(), response) from e - raise - # tell the clients which templates pointed at the deleted image: their - # nodes can no longer start + await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()}) + # tell the clients the image changed on this compute: they can refresh + # their image lists, and the templates that referenced the image can no + # longer start their nodes Controller.instance().notification.controller_emit( "docker.image.deleted", { diff --git a/tests/api/routes/controller/test_computes.py b/tests/api/routes/controller/test_computes.py index 955367d9f..04359ed0b 100644 --- a/tests/api/routes/controller/test_computes.py +++ b/tests/api/routes/controller/test_computes.py @@ -24,7 +24,6 @@ from fastapi import FastAPI, status from httpx import AsyncClient from gns3server.controller import Controller -from gns3server.controller.controller_error import ComputeConflictError from gns3server.schemas.controller.computes import Compute pytestmark = pytest.mark.asyncio @@ -261,12 +260,12 @@ class TestComputeFeatures: compute.http_query.assert_not_called() assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT - async def test_compute_delete_docker_image_conflict_names_referencing_templates( + async def test_compute_delete_docker_image_refused_while_referenced_by_templates( self, app: FastAPI, client: AsyncClient, test_compute: Compute ) -> None: """ - Templates do not block the deletion but are named in the conflict - error, matched through their image reference spelling. + A deletion is refused while a template references the image, matched + through the image reference spelling, and the compute is not touched. """ new_template = { @@ -280,44 +279,69 @@ class TestComputeFeatures: assert response.status_code == status.HTTP_201_CREATED compute = MagicMock() - compute.http_query = AsyncioMagicMock( - side_effect=ComputeConflictError( - "http://localhost:3080/docker/images/alpine:3", - { - "message": "Cannot delete image 'alpine:3': it is still used by node 'alpine-1' " - "in project 'lab' (running). Delete the node or container first, or repeat with force=true." - }, - ) - ) + 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="alpine:3") ) assert response.status_code == status.HTTP_409_CONFLICT - message = response.json()["message"] - assert "node 'alpine-1' in project 'lab'" in message - assert "referenced by template(s): Alpine conflict test" in message + body = response.json() + assert body["code"] == "image_referenced_by_templates" + assert body["details"]["referenced_by_templates"] == ["Alpine conflict test"] + assert "referenced by template(s): Alpine conflict test" in body["message"] + compute.http_query.assert_not_called() - async def test_compute_delete_docker_image_notifies_referencing_templates( + async def test_compute_delete_docker_image_force_overrides_template_reference( self, app: FastAPI, client: AsyncClient, test_compute: Compute ) -> None: """ - A successful deletion emits a docker.image.deleted notification with - the templates referencing the deleted image. + force=true deletes an image referenced by templates and the deletion + notification reports them. """ new_template = { - "name": "Alpine delete test", + "name": "Alpine force test", "compute_id": "local", - # an image no other test in this class references: the assertion - # below is exact and the class shares one database - "image": "gns3/delete-event-test:1", + # an image no other test in this class references: the assertions + # below are exact and the class shares one database + "image": "gns3/force-delete-test:2", "template_type": "docker", } response = await client.post(app.url_path_for("create_template"), json=new_template) assert response.status_code == status.HTTP_201_CREATED + 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="gns3/force-delete-test:2" + ), + params={"force": True}, + ) + assert response.status_code == status.HTTP_204_NO_CONTENT + compute.http_query.assert_called_once_with( + "DELETE", "/docker/images/gns3/force-delete-test:2", params={"force": "true"} + ) + controller.return_value.notification.controller_emit.assert_called_once_with( + "docker.image.deleted", + { + "compute_id": str(test_compute.compute_id), + "image": "gns3/force-delete-test:2", + "referenced_by_templates": ["Alpine force test"], + }, + ) + + async def test_compute_delete_docker_image_notifies_without_templates( + self, app: FastAPI, client: AsyncClient, test_compute: Compute + ) -> None: + """ + A deletion nothing references still emits a docker.image.deleted + notification, so clients can refresh their image lists. + """ + compute = MagicMock() compute.http_query = AsyncioMagicMock(return_value={}) with patch("gns3server.api.routes.controller.computes.Controller.instance") as controller: @@ -333,7 +357,7 @@ class TestComputeFeatures: { "compute_id": str(test_compute.compute_id), "image": "gns3/delete-event-test:1", - "referenced_by_templates": ["Alpine delete test"], + "referenced_by_templates": [], }, )