From 84113922335e9c2b96c37c23bc84b6dbfdf21836 Mon Sep 17 00:00:00 2001 From: Guobin Yue <72330500+yueguobin@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:24:20 +0800 Subject: [PATCH] Add snapshot description support (#3094) Pass the description when creating a snapshot instead of silently dropping it, and add a PUT endpoint to edit the description later. An empty description resets to the default text. Also accept an optional description in the MCP snapshot_create tool. --- gns3server/agent/mcp/__init__.py | 2 + gns3server/agent/mcp/snapshots.py | 6 ++- gns3server/api/routes/controller/snapshots.py | 20 +++++++- gns3server/controller/project.py | 19 +++++++- gns3server/controller/snapshot.py | 29 ++++++++--- gns3server/schemas/__init__.py | 3 +- gns3server/schemas/controller/snapshots.py | 8 ++++ tests/api/routes/controller/test_snapshots.py | 48 +++++++++++++++++++ tests/controller/test_snapshot.py | 24 ++++++++++ 9 files changed, 148 insertions(+), 11 deletions(-) diff --git a/gns3server/agent/mcp/__init__.py b/gns3server/agent/mcp/__init__.py index d6e4af6c6..425a42f20 100644 --- a/gns3server/agent/mcp/__init__.py +++ b/gns3server/agent/mcp/__init__.py @@ -1621,6 +1621,7 @@ async def snapshot_list( async def snapshot_create( project_id: Annotated[str, Field(description="Project name or UUID")], name: Annotated[str, Field(description="Name for the new snapshot")], + description: Annotated[str | None, Field(description="Optional description for the snapshot")] = None, ) -> list[dict[str, Any]]: """Create a new snapshot of a project. @@ -1634,6 +1635,7 @@ async def snapshot_create( { "project_id": project_id, "name": name, + "description": description, }, ) diff --git a/gns3server/agent/mcp/snapshots.py b/gns3server/agent/mcp/snapshots.py index 9f741a91e..43b69f573 100644 --- a/gns3server/agent/mcp/snapshots.py +++ b/gns3server/agent/mcp/snapshots.py @@ -56,8 +56,12 @@ def create_snapshot_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> name = params.get("name") if not project_id or not name: return {"error": "project_id and name are required"} + body: dict[str, Any] = {"name": name} + description = params.get("description") + if description: + body["description"] = description conn = _get_connector(gns3_ctx) - result = conn.http_call("post", f"{conn.base_url}/projects/{project_id}/snapshots", json_data={"name": name}).json() + result = conn.http_call("post", f"{conn.base_url}/projects/{project_id}/snapshots", json_data=body).json() return {"message": f"Snapshot '{name}' created", "snapshot": result} diff --git a/gns3server/api/routes/controller/snapshots.py b/gns3server/api/routes/controller/snapshots.py index b0ed679f5..56cca0004 100644 --- a/gns3server/api/routes/controller/snapshots.py +++ b/gns3server/api/routes/controller/snapshots.py @@ -67,7 +67,7 @@ async def create_snapshot( Required privilege: Snapshot.Allocate """ - snapshot = await project.snapshot(snapshot_data.name) + snapshot = await project.snapshot(snapshot_data.name, snapshot_data.description) return snapshot.asdict() @@ -88,6 +88,24 @@ def get_snapshots(project: Project = Depends(dep_project)) -> List[schemas.Snaps return [s.asdict() for s in sorted(snapshots, key=lambda s: (s.created_at, s.name))] +@router.put( + "/{snapshot_id}", + response_model=schemas.Snapshot, + dependencies=[Depends(has_privilege("Snapshot.Allocate"))], +) +async def update_snapshot( + snapshot_data: schemas.SnapshotUpdate, snapshot_id: UUID, project: Project = Depends(dep_project) +) -> schemas.Snapshot: + """ + Update a snapshot, for example its description. + + Required privilege: Snapshot.Allocate + """ + + snapshot = project.update_snapshot(str(snapshot_id), snapshot_data.description) + return snapshot.asdict() + + @router.delete( "/{snapshot_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(has_privilege("Snapshot.Allocate"))] ) diff --git a/gns3server/controller/project.py b/gns3server/controller/project.py index dcbebc8bc..1b4ed5d31 100644 --- a/gns3server/controller/project.py +++ b/gns3server/controller/project.py @@ -1614,21 +1614,36 @@ class Project: log.error(f"Cannot write snapshot config '{self._snapshot_conf_path}': {e}") @open_required - async def snapshot(self, name): + async def snapshot(self, name, description=None): """ Snapshot the project :param name: Name of the snapshot + :param description: Description of the snapshot """ if name in [snap.name for snap in self._snapshots.values()]: raise ControllerError(f"The snapshot name {name} already exists") - snapshot = Snapshot(self, name=name) + snapshot = Snapshot(self, name=name, description=description) await snapshot.create() self._snapshots[snapshot.id] = snapshot self._save_snapshot_config() return snapshot + @open_required + def update_snapshot(self, snapshot_id, description=None): + """ + Update a snapshot, for example its description + + :param snapshot_id: ID of the snapshot + :param description: New description of the snapshot + """ + + snapshot = self.get_snapshot(snapshot_id) + snapshot.update(description=description) + self._save_snapshot_config() + return snapshot + @open_required async def delete_snapshot(self, snapshot_id): snapshot = self.get_snapshot(snapshot_id) diff --git a/gns3server/controller/snapshot.py b/gns3server/controller/snapshot.py index b7d615d76..493026df6 100644 --- a/gns3server/controller/snapshot.py +++ b/gns3server/controller/snapshot.py @@ -74,12 +74,7 @@ class Snapshot: ) if not description: - date = ( - datetime.fromtimestamp(self._created_at, tz=UTC) - .replace(tzinfo=None) - .strftime(DESCRIPTION_DATETIME_FORMAT) - ) - description = f"Snapshot '{self._name}' taken on {date}" + description = self._default_description() self._description = description self._filename = filename @@ -105,6 +100,28 @@ class Snapshot: def created_at(self): return self._created_at + def _default_description(self) -> str: + """ + Return the default description of the snapshot. + """ + + date = ( + datetime.fromtimestamp(self._created_at, tz=UTC).replace(tzinfo=None).strftime(DESCRIPTION_DATETIME_FORMAT) + ) + return f"Snapshot '{self._name}' taken on {date}" + + def update(self, description: str | None = None) -> None: + """ + Update the snapshot description. An empty or null description + resets it to the default one. + + :param description: New description of the snapshot + """ + + if not description: + description = self._default_description() + self._description = description + async def create(self): """ Create the snapshot diff --git a/gns3server/schemas/__init__.py b/gns3server/schemas/__init__.py index 14281e397..bb5eb56c6 100644 --- a/gns3server/schemas/__init__.py +++ b/gns3server/schemas/__init__.py @@ -155,7 +155,7 @@ from .controller.notifications import Notification, NotificationAction from .controller.pools import Resource, ResourceCreate, ResourcePool, ResourcePoolCreate, ResourcePoolUpdate from .controller.rbac import ACE, ACECreate, ACEEndpoint, ACEUpdate, Privilege, Role, RoleCreate, RoleUpdate from .controller.settings import SettingsResponse, SettingsUpdate, SettingsUpdateResponse -from .controller.snapshots import Snapshot, SnapshotCreate +from .controller.snapshots import Snapshot, SnapshotCreate, SnapshotUpdate from .controller.statistics import ( ComputeStatistics, ComputeStatisticsEntry, @@ -387,6 +387,7 @@ __all__ = [ "SettingsUpdateResponse", "Snapshot", "SnapshotCreate", + "SnapshotUpdate", "SymbolDimensions", "SymbolInfo", "Template", diff --git a/gns3server/schemas/controller/snapshots.py b/gns3server/schemas/controller/snapshots.py index adbb7b726..01787937b 100644 --- a/gns3server/schemas/controller/snapshots.py +++ b/gns3server/schemas/controller/snapshots.py @@ -39,6 +39,14 @@ class SnapshotCreate(SnapshotBase): pass +class SnapshotUpdate(BaseModel): + """ + Properties for snapshot update. + """ + + description: Optional[str] = Field(None, description="Description of the snapshot") + + class Snapshot(SnapshotBase): snapshot_id: UUID project_id: UUID diff --git a/tests/api/routes/controller/test_snapshots.py b/tests/api/routes/controller/test_snapshots.py index d4180a562..ec1ad4362 100644 --- a/tests/api/routes/controller/test_snapshots.py +++ b/tests/api/routes/controller/test_snapshots.py @@ -88,6 +88,54 @@ class TestSnapshotRoutes: assert isinstance(data["created_at"], int) assert datetime.fromisoformat(data["created"]) == datetime.fromtimestamp(data["created_at"], tz=UTC) + async def test_create_snapshot_with_description(self, app: FastAPI, client: AsyncClient, project: Project) -> None: + + response = await client.post( + app.url_path_for("create_snapshot", project_id=project.id), + json={"name": "snap1", "description": "before adding the second node"}, + ) + assert response.status_code == status.HTTP_201_CREATED + data = response.json() + assert data["description"] == "before adding the second node" + + # the description must survive a reload of the snapshot config file + project._load_snapshot_config() + assert project.get_snapshot(data["snapshot_id"]).description == "before adding the second node" + + async def test_update_snapshot( + self, app: FastAPI, client: AsyncClient, project: Project, snapshot: Snapshot + ) -> None: + + response = await client.put( + app.url_path_for("update_snapshot", project_id=project.id, snapshot_id=snapshot.id), + json={"description": "before adding the second node"}, + ) + assert response.status_code == status.HTTP_200_OK + assert response.json()["description"] == "before adding the second node" + + # the new description must be saved in the snapshot config file + project._load_snapshot_config() + assert project.get_snapshot(snapshot.id).description == "before adding the second node" + + async def test_update_snapshot_reset_description( + self, app: FastAPI, client: AsyncClient, project: Project, snapshot: Snapshot + ) -> None: + + response = await client.put( + app.url_path_for("update_snapshot", project_id=project.id, snapshot_id=snapshot.id), + json={"description": ""}, + ) + assert response.status_code == status.HTTP_200_OK + assert response.json()["description"].startswith("Snapshot 'test' taken on ") + + async def test_update_snapshot_not_found(self, app: FastAPI, client: AsyncClient, project: Project) -> None: + + response = await client.put( + app.url_path_for("update_snapshot", project_id=project.id, snapshot_id=str(uuid.uuid4())), + json={"description": "test"}, + ) + assert response.status_code == status.HTTP_404_NOT_FOUND + async def test_snapshot_schema_timestamps(self, app: FastAPI) -> None: schemas = app.openapi()["components"]["schemas"] diff --git a/tests/controller/test_snapshot.py b/tests/controller/test_snapshot.py index c180eb957..08623d9df 100644 --- a/tests/controller/test_snapshot.py +++ b/tests/controller/test_snapshot.py @@ -37,6 +37,30 @@ def test_snapshot_name(project): assert snapshot.path == os.path.join(project.path, "snapshots", "test1.gns3snapshot") +def test_snapshot_description(project): + """ + Test snapshot description handling + """ + + snapshot = Snapshot(project, name="test1", description="my description") + assert snapshot.description == "my description" + + # a missing or empty description falls back to the default one + snapshot = Snapshot(project, name="test2") + assert snapshot.description.startswith("Snapshot 'test2' taken on ") + snapshot = Snapshot(project, name="test3", description="") + assert snapshot.description.startswith("Snapshot 'test3' taken on ") + + # updating the description + snapshot.update(description="new description") + assert snapshot.description == "new description" + # an empty description resets to the default one + snapshot.update(description="") + assert snapshot.description.startswith("Snapshot 'test3' taken on ") + snapshot.update(description=None) + assert snapshot.description.startswith("Snapshot 'test3' taken on ") + + def test_snapshot_filename(project): """ Test create a snapshot object with a filename