feat: name nodes and templates in Docker image delete conflicts

The compute translates the container ids in a daemon delete conflict
into the GNS3 node and project behind each container. Leftover
containers from closed projects and containers created outside GNS3
are named as such.

The controller lists the templates referencing the image in the
conflict error, matched through the canonical image name. After a
successful deletion it emits a docker.image.deleted notification with
those templates: their nodes can no longer start.
This commit is contained in:
YueGuobin committed 2026-11-06 22:05:52 +08:00
1 parent 04a8ba06a8
commit de986e890e
6 files changed
+341 -7

No files matched your search

+42 -4
View File
@@ -26,11 +26,16 @@ 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 ControllerBadRequestError, ControllerError
from gns3server.controller.controller_error import ComputeConflictError, ControllerBadRequestError, ControllerError
from gns3server.db.repositories.computes import ComputesRepository
from gns3server.db.repositories.rbac import RbacRepository
from gns3server.db.repositories.templates import TemplatesRepository
from gns3server.services.computes import ComputesService
from gns3server.utils.images import DOCKER_IMAGE_NAME_PATTERN, validate_docker_image_name
from gns3server.utils.images import (
DOCKER_IMAGE_NAME_PATTERN,
canonical_docker_image_name,
validate_docker_image_name,
)
from .dependencies.database import get_repository
from .dependencies.rbac import has_privilege
@@ -267,12 +272,19 @@ async def docker_delete_image(
compute_id: Union[str, UUID],
image: str = Path(..., pattern=DOCKER_IMAGE_NAME_PATTERN),
force: bool = Query(False, description="Remove the image even if a container uses it"),
templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository)),
) -> 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.
one) and answers a conflict naming the GNS3 nodes and projects using it,
unless force is set.
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.
Required privilege: Compute.Modify
"""
@@ -282,8 +294,34 @@ async def docker_delete_image(
except ValueError as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e
canonical_image = canonical_docker_image_name(image)
referencing_templates = [
str(template.name)
for template in await templates_repo.get_templates()
if isinstance(template, models.DockerTemplate)
and template.image
and canonical_docker_image_name(str(template.image)) == canonical_image
]
compute = Controller.instance().get_compute(str(compute_id))
await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()})
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
Controller.instance().notification.controller_emit(
"docker.image.deleted",
{
"compute_id": str(compute_id),
"image": image,
"referenced_by_templates": referencing_templates,
},
)
@router.get("/{compute_id}/virtualbox/vms", response_model=List[schemas.ComputeVirtualBoxVM])
+64 -1
View File
@@ -22,6 +22,7 @@ import asyncio
import json
import logging
import os
import re
import shutil
import sys
@@ -29,6 +30,7 @@ import aiohttp
import platformdirs
from gns3server.compute.base_manager import BaseManager
from gns3server.compute.compute_error import ComputeError
from gns3server.compute.docker.docker_error import (
DockerError,
DockerHttp304Error,
@@ -38,6 +40,7 @@ from gns3server.compute.docker.docker_error import (
from gns3server.compute.docker.docker_vm import DockerVM
from gns3server.compute.docker.iol_docker_vm import IOLDockerVM
from gns3server.compute.docker.vendor_docker_vm import VendorDockerVM
from gns3server.compute.project_manager import ProjectManager
from gns3server.config import Config
from gns3server.utils import parse_version
from gns3server.utils.asyncio import locking
@@ -56,6 +59,16 @@ CHUNK_SIZE = 1024 * 8 # 8KB
# otherwise hang forever. This is an idle timeout, not a total time limit.
PULL_IDLE_TIMEOUT = 60
# Docker names GNS3 node containers "GNS3.{node name}.{project_id}", so a
# container name can be translated back into the node and project that block
# an image deletion. The node name may itself contain dots.
GNS3_CONTAINER_NAME_RE = re.compile(
r"^GNS3\.(?P<node>.+)\.(?P<project_id>[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$"
)
# The containers blocking an image deletion, as named by the daemon, e.g.
# 'container 6d59f00236ff is using its referenced image d529dd0c6e55'
CONFLICTING_CONTAINER_RE = re.compile(r"container ([0-9a-f]{12,64})\b")
class Docker(BaseManager):
_NODE_CLASS = DockerVM
@@ -582,11 +595,61 @@ class Docker(BaseManager):
"""
Delete a Docker image from the Docker daemon.
When the daemon refuses because containers use the image, the error
names the GNS3 nodes and projects behind them instead of raw
container ids.
: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": str(force).lower()})
try:
await self.query("DELETE", f"images/{image}", params={"force": str(force).lower()})
except DockerHttp409Error as e:
blockers = await self._describe_containers_using_image(str(e))
if blockers:
raise DockerHttp409Error(
f"Cannot delete image '{image}': it is still used by {blockers}. "
f"Delete the node or container first, or repeat with force=true."
) from e
raise
# 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)
async def _describe_containers_using_image(self, daemon_error: str) -> str:
"""
Translate the container ids named in a daemon image deletion conflict
into node, project or container descriptions.
:param daemon_error: the raw daemon conflict message
:returns: a comma separated description, empty when the message names
no container
"""
descriptions = []
for container_id in CONFLICTING_CONTAINER_RE.findall(daemon_error):
try:
info = await self.query("GET", f"containers/{container_id}/json")
except DockerError:
info = None
if not info:
# the container cannot be inspected (or already vanished)
descriptions.append(f"container '{container_id}'")
continue
name = info.get("Name", container_id).lstrip("/")
state = "running" if info.get("State", {}).get("Running") else "stopped"
match = GNS3_CONTAINER_NAME_RE.match(name)
if match:
node = match.group("node")
try:
project = ProjectManager.instance().get_project(match.group("project_id"))
except ComputeError:
# the project is closed on this compute: a leftover container
descriptions.append(f"leftover container of node '{node}' ({state}, its project is closed)")
else:
descriptions.append(f"node '{node}' in project '{project.name}' ({state})")
else:
# a container created outside GNS3
descriptions.append(f"container '{name}' ({state})")
return ", ".join(descriptions)
+38
View File
@@ -72,6 +72,44 @@ def validate_docker_image_name(image: str) -> None:
raise ValueError(f"Invalid Docker image name: {image}")
def canonical_docker_image_name(image: str) -> str:
"""
Normalize a Docker image reference for name comparisons.
Registry hosts are dropped, Docker Hub's implicit "library/" namespace and
the implicit ":latest" tag are made explicit, so "alpine",
"library/alpine:latest" and "docker.io/library/alpine" all normalize to
the same string. A reference pinned by digest keeps its digest and loses
its tag.
"""
reference = image.strip()
if "/" in reference:
registry, _, remainder = reference.partition("/")
if registry == "localhost" or "." in registry or ":" in registry:
# the first path element is a registry host, not a namespace
reference = remainder
if "@" in reference:
repository, _, digest = reference.rpartition("@")
if not repository:
return reference # a bare digest, nothing to normalize
# with a digest pinned the tag does not take part in the identity
repository = repository.partition(":")[0]
return f"{_canonical_docker_repository(repository)}@{digest}"
repository, separator, tag = reference.rpartition(":")
if not separator or not repository:
repository, tag = reference, "latest"
return f"{_canonical_docker_repository(repository)}:{tag or 'latest'}"
def _canonical_docker_repository(repository: str) -> str:
if "/" not in repository:
# images without a namespace live in Docker Hub's "library/" namespace
return f"library/{repository}"
return repository
async def list_images(image_type):
"""
Scan directories for available image for a given type.