Merge pull request #3062 from yueguobin/feat/docker-image-upload

Allow uploading, deleting and pulling Docker images on computes
This commit is contained in:
Jeremy Grossmann authored and GitHub committed 2026-11-07 16:49:26 +01:00
commit ce8d5591a1
16 files changed
+1312 -206

No files matched your search

+96 -5
View File
@@ -18,6 +18,7 @@ import pytest
from fastapi import FastAPI, status
from httpx import AsyncClient
from gns3server.compute.docker.docker_error import DockerError
from tests.utils import asyncio_patch
pytestmark = pytest.mark.asyncio
@@ -26,12 +27,75 @@ pytestmark = pytest.mark.asyncio
class TestImagesRoutes:
async def test_pull_docker_image(self, app: FastAPI, compute_client: AsyncClient) -> None:
with asyncio_patch("gns3server.compute.docker.Docker.pull_image") as mock:
response = await compute_client.post(
app.url_path_for("compute:pull_docker_image"), json={"image": "nginx:latest"}
async def fake_pull(image, progress_callback=None, force=False):
progress_callback(
{"layers_total": 0, "layers_done": 0, "message": "Pulling 'nginx:latest'", "state": "started"}
)
mock.assert_called_once_with("nginx:latest", force=True)
assert response.status_code == status.HTTP_204_NO_CONTENT
with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull) as mock:
with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock:
response = await compute_client.post(
app.url_path_for("compute:pull_docker_image"), json={"image": "nginx:latest"}
)
assert mock.call_args[0] == ("nginx:latest",)
assert mock.call_args[1]["force"] is True
assert callable(mock.call_args[1]["progress_callback"])
# started and completed events are emitted to the notification stream
assert [(c.args[0], c.args[1]["state"]) for c in emit_mock.call_args_list] == [
("docker.image.pull", "started"),
("docker.image.pull", "completed"),
]
assert response.status_code == status.HTTP_204_NO_CONTENT
async def test_pull_docker_image_progress_id(self, app: FastAPI, compute_client: AsyncClient) -> None:
async def fake_pull(image, progress_callback=None, force=False):
progress_callback({"layers_total": 1, "layers_done": 0, "message": "Pulling", "state": "started"})
progress_callback({"layers_total": 1, "layers_done": 0, "message": "[==> ] 10/100"})
with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull):
with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock:
response = await compute_client.post(
app.url_path_for("compute:pull_docker_image"),
json={"image": "nginx:latest"},
params={"progress_id": "abc123"},
)
assert response.status_code == status.HTTP_204_NO_CONTENT
assert all(c.args[1]["progress_id"] == "abc123" for c in emit_mock.call_args_list)
async def test_pull_docker_image_reports_downloading(self, app: FastAPI, compute_client: AsyncClient) -> None:
async def fake_pull(image, progress_callback=None, force=False):
progress_callback({"layers_total": 2, "layers_done": 0, "message": "Pulling", "state": "started"})
progress_callback({"layers_total": 2, "layers_done": 1, "message": "[==> ] 40/100"})
with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull):
with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock:
response = await compute_client.post(
app.url_path_for("compute:pull_docker_image"), json={"image": "nginx:latest"}
)
assert response.status_code == status.HTTP_204_NO_CONTENT
states = [c.args[1]["state"] for c in emit_mock.call_args_list]
assert states == ["started", "downloading", "completed"]
downloading = emit_mock.call_args_list[1].args[1]
assert downloading["layers_total"] == 2
assert downloading["layers_done"] == 1
assert downloading["message"] == "[==> ] 40/100"
async def test_pull_docker_image_emits_failed(self, app: FastAPI, compute_client: AsyncClient) -> None:
async def fake_pull(image, progress_callback=None, force=False):
raise DockerError("no data received for 60 seconds")
with asyncio_patch("gns3server.compute.docker.Docker.pull_image", side_effect=fake_pull):
with asyncio_patch("gns3server.compute.notification_manager.NotificationManager.emit") as emit_mock:
response = await compute_client.post(
app.url_path_for("compute:pull_docker_image"), json={"image": "nginx:latest"}
)
assert response.status_code == status.HTTP_409_CONFLICT
failed = emit_mock.call_args_list[-1].args[1]
assert failed["state"] == "failed"
assert "no data received" in failed["message"]
@pytest.mark.parametrize("image", ["", " ", "nginx latest"])
async def test_pull_docker_image_rejects_invalid_name(
@@ -55,6 +119,33 @@ 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_rejects_path_traversal(self, app: FastAPI, compute_client: AsyncClient) -> None:
# percent encoded so the client does not normalize the ".." segments
# away before the request reaches the server
with asyncio_patch("gns3server.compute.docker.Docker.delete_image") as mock:
response = await compute_client.delete("/v3/compute/docker/images/a%2F..%2F..%2Fversion")
mock.assert_not_called()
assert response.status_code == status.HTTP_422_UNPROCESSABLE_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
+186 -2
View File
@@ -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:
@@ -194,7 +197,188 @@ class TestComputeFeatures:
app.url_path_for("docker_pull_image", compute_id=test_compute.compute_id),
json={"image": "nginx:latest"},
)
compute.forward.assert_called_with("POST", "docker", "images/pull", data={"image": "nginx:latest"})
compute.forward.assert_called_with(
"POST", "docker", "images/pull", data={"image": "nginx:latest"}, params=None
)
assert response.status_code == status.HTTP_204_NO_CONTENT
async def test_compute_pull_docker_image_progress_id(
self, app: FastAPI, client: AsyncClient, test_compute: Compute
) -> None:
compute = MagicMock()
compute.forward = 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.post(
app.url_path_for("docker_pull_image", compute_id=test_compute.compute_id),
json={"image": "nginx:latest"},
params={"progress_id": "abc123"},
)
compute.forward.assert_called_with(
"POST",
"docker",
"images/pull",
data={"image": "nginx:latest"},
params={"progress_id": "abc123"},
)
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_delete_docker_image_rejects_path_traversal(
self, app: FastAPI, client: AsyncClient, test_compute: Compute
) -> None:
# percent encoded so the client does not normalize the ".." segments
# away before the request reaches the server
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(
f"/v3/computes/{test_compute.compute_id}/docker/images/a%2F..%2F..%2Fversion"
)
compute.http_query.assert_not_called()
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
async def test_compute_delete_docker_image_refused_while_referenced_by_templates(
self, app: FastAPI, client: AsyncClient, test_compute: Compute
) -> None:
"""
A deletion is refused while a template references the image, matched
through the image reference spelling, and the compute is not touched.
"""
new_template = {
"name": "Alpine conflict test",
"compute_id": "local",
# a different spelling of the deleted 'alpine:3'
"image": "docker.io/library/alpine:3",
"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="alpine:3")
)
assert response.status_code == status.HTTP_409_CONFLICT
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_force_overrides_template_reference(
self, app: FastAPI, client: AsyncClient, test_compute: Compute
) -> None:
"""
force=true deletes an image referenced by templates and the deletion
notification reports them.
"""
new_template = {
"name": "Alpine force test",
"compute_id": "local",
# 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:
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/delete-event-test:1"
)
)
assert response.status_code == status.HTTP_204_NO_CONTENT
controller.return_value.notification.controller_emit.assert_called_once_with(
"docker.image.deleted",
{
"compute_id": str(test_compute.compute_id),
"image": "gns3/delete-event-test:1",
"referenced_by_templates": [],
},
)
async def test_compute_load_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.post(
app.url_path_for("docker_load_image", compute_id=test_compute.compute_id),
content=b"docker save tar data",
headers={"Content-Type": "application/octet-stream"},
)
compute.http_query.assert_called_once()
args, kwargs = compute.http_query.call_args
assert args[0] == "POST"
assert args[1] == "/docker/images/load"
assert kwargs["timeout"] is None
# the request body must be streamed, not buffered
assert hasattr(kwargs["data"], "__aiter__")
assert response.status_code == status.HTTP_204_NO_CONTENT
async def test_compute_list_virtualbox_vms(self, app: FastAPI, client: AsyncClient) -> None:
+282 -9
View File
@@ -16,13 +16,20 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import uuid
from unittest.mock import MagicMock, patch
import pytest
import pytest_asyncio
from gns3server.compute.docker import DOCKER_MINIMUM_API_VERSION, DOCKER_PREFERRED_API_VERSION, Docker
from gns3server.compute.docker.docker_error import DockerError, DockerHttp404Error
from gns3server.compute.docker import (
DOCKER_MINIMUM_API_VERSION,
DOCKER_PREFERRED_API_VERSION,
Docker,
)
from gns3server.compute.docker.docker_error import DockerError, DockerHttp404Error, DockerHttp409Error
from gns3server.compute.docker.docker_images import PULL_IDLE_TIMEOUT
from gns3server.compute.project_manager import ProjectManager
from tests.utils import AsyncioMagicMock, asyncio_patch
@@ -132,11 +139,64 @@ 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 "<none>:<none>" not in by_tag
assert {"ubuntu:precise", "ubuntu:latest", "ubuntu:12.10", "ubuntu:quantal"} <= set(by_tag)
@pytest.mark.asyncio
async def test_list_images_created_fallback_to_oci_label():
"""
Images built without a created timestamp (e.g. reproducible Ubuntu images)
report 0 from the daemon: the build time comes from the OCI created label.
"""
response = [
{
# zero timestamp, the label is used (Z suffix, nanosecond precision)
"RepoTags": ["ubuntu:latest"],
"Id": "febc1a2eec1f",
"Created": 0,
"Size": 78101592,
"Labels": {"org.opencontainers.image.created": "2026-10-25T10:26:07.538865123Z"},
},
{
# zero timestamp without a label stays at zero
"RepoTags": ["no-label:latest"],
"Id": "aaaaaa",
"Created": 0,
"Size": 1,
},
{
# the daemon timestamp wins over the label when it is set
"RepoTags": ["normal:latest"],
"Id": "bbbbbb",
"Created": 1365714795,
"Size": 1,
"Labels": {"org.opencontainers.image.created": "2000-01-01T00:00:00Z"},
},
{
# a broken label is ignored, the timestamp stays at zero
"RepoTags": ["broken-label:latest"],
"Id": "cccccc",
"Created": 0,
"Size": 1,
"Labels": {"org.opencontainers.image.created": "not a date"},
},
]
with asyncio_patch("gns3server.compute.docker.Docker.query", return_value=response):
images = await Docker.instance().list_images()
by_tag = {image["image"]: image for image in images}
assert by_tag["ubuntu:latest"]["created"] == 1792923967
assert by_tag["no-label:latest"]["created"] == 0
assert by_tag["normal:latest"]["created"] == 1365714795
assert by_tag["broken-label:latest"]["created"] == 0
@pytest.mark.asyncio
@@ -165,7 +225,50 @@ async def test_pull_image():
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp404Error("404")):
with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=mock_query) as mock:
await Docker.instance().pull_image("ubuntu")
mock.assert_called_with("POST", "images/create", params={"fromImage": "ubuntu"}, timeout=None)
args, kwargs = mock.call_args
assert args == ("POST", "images/create")
assert kwargs["params"] == {"fromImage": "ubuntu", "tag": "latest"}
# no total timeout (a pull can take as long as it needs) but an
# idle socket read timeout, so an unreachable registry fails
assert kwargs["timeout"].total is None
assert kwargs["timeout"].sock_read == PULL_IDLE_TIMEOUT
@pytest.mark.asyncio
async def test_pull_image_reports_aggregated_progress():
class Content:
def __init__(self):
self._chunks = [
b'{"status": "Pulling fs layer", "id": "sha256:a"}\n'
b'{"status": "Pulling fs layer", "id": "sha256:b"}\n'
b'{"status": "Downloading", "id": "sha256:a", "progress": "[==> ] 40/100"}\n'
b'{"status": "Pull complete", "id": "sha256:a"}\n',
b'{"status": "Pull complete", "id": "sha256:b"}\n',
b"",
]
async def read(self, size):
return self._chunks.pop(0)
response = MagicMock()
response.content = Content()
progress = []
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp404Error("404")):
with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=response):
await Docker.instance().pull_image("ubuntu", progress_callback=progress.append)
# the callback sees the running totals of layers, not raw daemon lines
assert progress[0] == {
"layers_total": 0,
"layers_done": 0,
"message": "Pulling 'ubuntu' from Docker repository",
"state": "started",
}
assert progress[1] == {"layers_total": 1, "layers_done": 0, "message": "Pulling fs layer"}
assert progress[2] == {"layers_total": 2, "layers_done": 0, "message": "Pulling fs layer"}
assert {"layers_total": 2, "layers_done": 0, "message": "[==> ] 40/100"} in progress
assert progress[-1] == {"layers_total": 2, "layers_done": 2, "message": "Pull complete"}
@pytest.mark.asyncio
@@ -188,7 +291,40 @@ async def test_force_pull_image():
with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=response) as pull_mock:
await Docker.instance().pull_image("ubuntu", force=True)
query_mock.assert_not_called()
pull_mock.assert_called_with("POST", "images/create", params={"fromImage": "ubuntu"}, timeout=None)
args, kwargs = pull_mock.call_args
assert args == ("POST", "images/create")
assert kwargs["params"] == {"fromImage": "ubuntu", "tag": "latest"}
assert kwargs["timeout"].sock_read == PULL_IDLE_TIMEOUT
@pytest.mark.asyncio
@pytest.mark.parametrize(
"image, expected_params",
[
# without a tag or digest the daemon would pull every tag of the
# repository: default to latest so the pull targets a single tag
("ubuntu", {"fromImage": "ubuntu", "tag": "latest"}),
("gns3/ubuntu", {"fromImage": "gns3/ubuntu", "tag": "latest"}),
# the ':' before the last '/' is a registry port, not a tag
("registry:5000/ubuntu", {"fromImage": "registry:5000/ubuntu", "tag": "latest"}),
("registry:5000/gns3/ubuntu", {"fromImage": "registry:5000/gns3/ubuntu", "tag": "latest"}),
# an explicit tag or digest is left alone
("ubuntu:24.04", {"fromImage": "ubuntu:24.04"}),
("registry:5000/ubuntu:24.04", {"fromImage": "registry:5000/ubuntu:24.04"}),
("ubuntu@sha256:8b2f", {"fromImage": "ubuntu@sha256:8b2f"}),
],
)
async def test_pull_image_targets_a_single_tag(image, expected_params):
response = MagicMock()
response.content.read = AsyncioMagicMock(return_value=b"")
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp404Error("404")):
with asyncio_patch("gns3server.compute.docker.Docker.http_query", return_value=response) as pull_mock:
await Docker.instance().pull_image(image)
args, kwargs = pull_mock.call_args
assert args == ("POST", "images/create")
assert kwargs["params"] == expected_params
@pytest.mark.asyncio
@@ -211,6 +347,24 @@ async def test_pull_image_error():
response.close.assert_called_once()
@pytest.mark.asyncio
async def test_pull_image_not_found_is_not_reported_as_a_network_error():
"""
A 404 from the registry means the image name is wrong or the registry needs
authentication: telling the user to check the Internet connection sends
them in the wrong direction.
"""
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp404Error("404")):
with asyncio_patch(
"gns3server.compute.docker.Docker.http_query",
side_effect=DockerHttp404Error("Docker has returned an error: 404 pull access denied for debian13"),
):
with pytest.raises(DockerError, match="not found in the registry") as error:
await Docker.instance().pull_image("debian13")
assert "Internet connection" not in str(error.value)
@pytest.mark.asyncio
async def test_pull_image_rejects_incomplete_response():
@@ -330,6 +484,125 @@ 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)
# the daemon query string only accepts strings, ints and floats: a
# Python bool would make the aiohttp URL builder raise a TypeError
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
DAEMON_DELETE_CONFLICT = (
"Docker has returned an error: 409 conflict: unable to remove repository reference "
'"alpine:3" (must force) - container 6d59f00236ff is using its referenced image d529dd0c6e55'
)
@pytest.mark.asyncio
async def test_delete_image_conflict_names_the_node_and_project():
"""
A container blocking the deletion is reported as the GNS3 node and project
it belongs to, not as a raw container id.
"""
docker = Docker.instance()
project_id = str(uuid.uuid4())
project = ProjectManager.instance().create_project(name="test-lab", project_id=project_id)
async def query(method, path, **kwargs):
assert path.startswith("images/") or path.startswith("containers/")
if method == "DELETE":
raise DockerHttp409Error(DAEMON_DELETE_CONFLICT)
return {"Name": f"/GNS3.alpine-1.{project_id}", "State": {"Running": True}}
try:
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=query):
with pytest.raises(DockerHttp409Error) as excinfo:
await docker.delete_image("alpine:3")
message = str(excinfo.value)
assert "node 'alpine-1' in project 'test-lab' (running)" in message
assert "force=true" in message
assert "6d59f00236ff" not in message
finally:
ProjectManager.instance().remove_project(project.id)
@pytest.mark.asyncio
async def test_delete_image_conflict_reports_a_leftover_container():
"""
When the project of the blocking container is closed on this compute the
container is reported as a leftover.
"""
docker = Docker.instance()
async def query(method, path, **kwargs):
if method == "DELETE":
raise DockerHttp409Error(DAEMON_DELETE_CONFLICT)
return {"Name": f"/GNS3.E2E-2.{uuid.uuid4()}", "State": {"Running": False}}
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=query):
with pytest.raises(DockerHttp409Error, match="leftover container of node 'E2E-2' \\(stopped"):
await docker.delete_image("alpine:3")
@pytest.mark.asyncio
async def test_delete_image_conflict_reports_a_non_gns3_container():
"""
A container created outside GNS3 is reported by its plain container name.
"""
docker = Docker.instance()
async def query(method, path, **kwargs):
if method == "DELETE":
raise DockerHttp409Error(DAEMON_DELETE_CONFLICT)
return {"Name": "/my-own-container", "State": {"Running": True}}
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=query):
with pytest.raises(DockerHttp409Error, match="container 'my-own-container' \\(running\\)"):
await docker.delete_image("alpine:3")
@pytest.mark.asyncio
async def test_delete_image_conflict_without_containers_is_not_rewritten():
"""
A daemon conflict naming no container (e.g. a multi repository reference)
is passed through unchanged.
"""
docker = Docker.instance()
original = "Docker has returned an error: 409 conflict: image is referenced in multiple repositories"
with asyncio_patch("gns3server.compute.docker.Docker.query", side_effect=DockerHttp409Error(original)):
with pytest.raises(DockerHttp409Error, match="multiple repositories"):
await docker.delete_image("alpine:3")
@pytest.mark.asyncio
async def test_docker_check_connection_docker_minimum_version(vm):
+28
View File
@@ -119,6 +119,34 @@ async def test_dispatch_node_updated(controller, node, project):
assert event["properties"]["startup_config"] == "ip 192"
@pytest.mark.asyncio
async def test_dispatch_docker_image_routed_to_controller_stream(controller, project):
"""
docker.image.* events are scoped to a compute, not to a project: they must
reach the controller stream even when no project is open, and not the
project stream.
"""
notif = controller.notification
with notif.controller_queue() as controller_q, notif.project_queue(project.id) as project_q:
await controller_q.get(0.1) # ping
await project_q.get(0.1) # ping
await notif.dispatch(
"docker.image.pull", {"image": "debian", "state": "started"}, project_id=None, compute_id="local"
)
msg = await controller_q.get(5)
assert msg == (
"docker.image.pull",
{"image": "debian", "state": "started", "compute_id": "local"},
{},
)
# the project stream only carries its periodic ping
msg = await project_q.get(0.2)
assert msg[0] == "ping"
@pytest.mark.asyncio
async def test_dispatch_marker_routed_to_marker_channel(controller, project):
"""
@@ -222,6 +222,22 @@ async def test_external_symlinks_hidden_files_and_libraries_are_not_imported(inv
assert outside.read_bytes() == QCOW
async def test_non_image_files_next_to_images_are_ignored(inventory, config):
"""Files a user keeps next to images (scripts, notes, licenses) must not be
reported as invalid images nor turn the sync job partial."""
image_file(config, "IOU/CiscoIOUKeygen.py", b"#!/usr/bin/env python\ndef main(): ...")
image_file(config, "IOU/README.md", b"# IOU images")
image_file(config, "QEMU/notes.TXT", b"my qemu notes")
image_file(config, "IOS/license.lic", b"license text")
result = await scan(inventory)
assert result["counts"]["scanned"] == 0
assert result["counts"]["invalid"] == 0
assert result["counts"]["errors"] == 0
assert result["errors"] == []
assert result["status"] == "completed"
@pytest.mark.parametrize(
"name,data,expected",
[
+30 -1
View File
@@ -20,7 +20,13 @@ import threading
import pytest
from gns3server.utils import force_unix_path
from gns3server.utils.images import images_directories, list_images, md5sum, remove_checksum
from gns3server.utils.images import (
canonical_docker_image_name,
images_directories,
list_images,
md5sum,
remove_checksum,
)
def test_images_directories(tmpdir, config):
@@ -108,6 +114,29 @@ def test_remove_checksum(tmpdir):
remove_checksum(str(tmpdir / "not_exists"))
@pytest.mark.parametrize(
"reference, expected",
(
("alpine", "library/alpine:latest"),
("alpine:3", "library/alpine:3"),
("library/alpine:3", "library/alpine:3"),
("docker.io/library/alpine:3", "library/alpine:3"),
("index.docker.io/library/alpine:3", "library/alpine:3"),
("localhost/alpine:3", "library/alpine:3"),
("gns3/frr", "gns3/frr:latest"),
("gns3/frr:latest", "gns3/frr:latest"),
("quay.io/some/namespace/image:2.0", "some/namespace/image:2.0"),
("alpine@sha256:" + "a" * 64, "library/alpine@sha256:" + "a" * 64),
("alpine:3@sha256:" + "a" * 64, "library/alpine@sha256:" + "a" * 64),
),
)
def test_canonical_docker_image_name(reference, expected):
assert canonical_docker_image_name(reference) == expected
# the canonical form is stable: canonicalizing twice does not change it
assert canonical_docker_image_name(expected) == expected
@pytest.mark.asyncio
async def test_list_images(tmpdir, config):