mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-19 04:35:14 +02:00
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.
This commit is contained in:
1 parent
fe51feec66
commit
8411392233
9 files changed
+148
-11
No files matched your search
@@ -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,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
|
||||
@@ -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"))]
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user