mirror of
https://github.com/GNS3/gns3-server.git
synced 2026-11-03 22:11:14 +02:00
feat(api): add strict_names and batch node and link creation
This commit is contained in:
11 files changed
+359
-37
No files matched your search
@@ -32,8 +32,9 @@ from fastapi.responses import FileResponse, StreamingResponse
|
||||
from gns3server import schemas
|
||||
from gns3server.agent.web_wireshark.manager import WebWiresharkManager
|
||||
from gns3server.controller import Controller
|
||||
from gns3server.controller.controller_error import ControllerError
|
||||
from gns3server.controller.controller_error import ControllerError, controller_error_status_code
|
||||
from gns3server.controller.link import _UNSET, Link
|
||||
from gns3server.controller.project import Project
|
||||
from gns3server.db.repositories.rbac import RbacRepository
|
||||
from gns3server.utils.http_client import HTTPClient
|
||||
from gns3server.utils.port_allocator import link_id_to_port
|
||||
@@ -91,7 +92,7 @@ async def get_links(project_id: UUID) -> List[schemas.Link]:
|
||||
},
|
||||
dependencies=[Depends(has_privilege("Link.Allocate"))],
|
||||
)
|
||||
async def create_link(project_id: UUID, link_create: schemas.LinkCreate) -> schemas.Link:
|
||||
async def create_link(project_id: UUID, link_create: schemas.LinkCreate) -> dict:
|
||||
"""
|
||||
Create a new link.
|
||||
|
||||
@@ -99,17 +100,22 @@ async def create_link(project_id: UUID, link_create: schemas.LinkCreate) -> sche
|
||||
"""
|
||||
|
||||
project = await Controller.instance().get_loaded_project(str(project_id))
|
||||
return await _create_link(project, link_create)
|
||||
|
||||
|
||||
async def _create_link(project: Project, link_create: schemas.LinkCreate) -> dict:
|
||||
|
||||
link = await project.add_link()
|
||||
link_data = jsonable_encoder(link_create, exclude_unset=True)
|
||||
if "filters" in link_data:
|
||||
await link.update_filters(link_data["filters"])
|
||||
if "link_style" in link_data:
|
||||
await link.update_link_style(link_data["link_style"])
|
||||
if "suspend" in link_data:
|
||||
await link.update_suspend(link_data["suspend"])
|
||||
if "show_filters_icon" in link_data:
|
||||
await link.update_show_filters_icon(link_data["show_filters_icon"])
|
||||
try:
|
||||
if "filters" in link_data:
|
||||
await link.update_filters(link_data["filters"])
|
||||
if "link_style" in link_data:
|
||||
await link.update_link_style(link_data["link_style"])
|
||||
if "suspend" in link_data:
|
||||
await link.update_suspend(link_data["suspend"])
|
||||
if "show_filters_icon" in link_data:
|
||||
await link.update_show_filters_icon(link_data["show_filters_icon"])
|
||||
for node in link_data["nodes"]:
|
||||
await link.add_node(
|
||||
project.get_node(node["node_id"]),
|
||||
@@ -123,6 +129,40 @@ async def create_link(project_id: UUID, link_create: schemas.LinkCreate) -> sche
|
||||
return link.asdict()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch",
|
||||
response_model=List[schemas.LinkBatchResult],
|
||||
responses={
|
||||
404: {"model": schemas.ErrorMessage, "description": "Could not find project"},
|
||||
},
|
||||
dependencies=[Depends(has_privilege("Link.Allocate"))],
|
||||
)
|
||||
async def create_links(project_id: UUID, links_create: List[schemas.LinkCreate]) -> List[schemas.LinkBatchResult]:
|
||||
"""
|
||||
Create several links in the order they are listed.
|
||||
|
||||
The response lists one result per link in the same order. A link that fails to be created
|
||||
does not stop the following ones.
|
||||
|
||||
Required privilege: Link.Allocate
|
||||
"""
|
||||
|
||||
project = await Controller.instance().get_loaded_project(str(project_id))
|
||||
results = []
|
||||
for link_create in links_create:
|
||||
try:
|
||||
link = await _create_link(project, link_create)
|
||||
results.append(schemas.LinkBatchResult(status_code=status.HTTP_201_CREATED, link=link))
|
||||
except ControllerError as e:
|
||||
log.error(f"Could not create link in batch: {e}")
|
||||
results.append(
|
||||
schemas.LinkBatchResult(
|
||||
status_code=controller_error_status_code(e), error=schemas.ErrorMessage(message=str(e))
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/{link_id}/available_filters", dependencies=[Depends(has_privilege("Link.Audit"))])
|
||||
async def get_filters(link: Link = Depends(dep_link)) -> List[dict]:
|
||||
"""
|
||||
|
||||
@@ -34,7 +34,12 @@ from fastapi.routing import APIRoute
|
||||
from gns3server import schemas
|
||||
from gns3server.config import Config
|
||||
from gns3server.controller import Controller
|
||||
from gns3server.controller.controller_error import ControllerBadRequestError, ControllerForbiddenError
|
||||
from gns3server.controller.controller_error import (
|
||||
ControllerBadRequestError,
|
||||
ControllerError,
|
||||
ControllerForbiddenError,
|
||||
controller_error_status_code,
|
||||
)
|
||||
from gns3server.controller.node import Node
|
||||
from gns3server.controller.project import Project
|
||||
from gns3server.db.repositories.rbac import RbacRepository
|
||||
@@ -128,13 +133,20 @@ def _check_node_type(node: Node, *required_types: str) -> None:
|
||||
},
|
||||
dependencies=[Depends(has_privilege("Node.Allocate"))],
|
||||
)
|
||||
async def create_node(node_create: schemas.NodeCreate, project: Project = Depends(dep_project)) -> schemas.Node:
|
||||
async def create_node(node_create: schemas.NodeCreate, project: Project = Depends(dep_project)) -> dict:
|
||||
"""
|
||||
Create a new node.
|
||||
|
||||
Set strict_names to get a 409 error instead of an automatic rename when the node name is already used.
|
||||
|
||||
Required privilege: Node.Allocate
|
||||
"""
|
||||
|
||||
return await _create_node(project, node_create)
|
||||
|
||||
|
||||
async def _create_node(project: Project, node_create: schemas.NodeCreate) -> dict:
|
||||
|
||||
controller = Controller.instance()
|
||||
compute = controller.get_compute(str(node_create.compute_id))
|
||||
node_data = jsonable_encoder(node_create, exclude_unset=True)
|
||||
@@ -142,6 +154,41 @@ async def create_node(node_create: schemas.NodeCreate, project: Project = Depend
|
||||
return node.asdict()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch",
|
||||
response_model=List[schemas.NodeBatchResult],
|
||||
responses={
|
||||
404: {"model": schemas.ErrorMessage, "description": "Could not find project"},
|
||||
},
|
||||
dependencies=[Depends(has_privilege("Node.Allocate"))],
|
||||
)
|
||||
async def create_nodes(
|
||||
nodes_create: List[schemas.NodeCreate], project: Project = Depends(dep_project)
|
||||
) -> List[schemas.NodeBatchResult]:
|
||||
"""
|
||||
Create several nodes in the order they are listed.
|
||||
|
||||
The response lists one result per node in the same order. A node that fails to be created
|
||||
does not stop the following ones.
|
||||
|
||||
Required privilege: Node.Allocate
|
||||
"""
|
||||
|
||||
results = []
|
||||
for node_create in nodes_create:
|
||||
try:
|
||||
node = await _create_node(project, node_create)
|
||||
results.append(schemas.NodeBatchResult(status_code=status.HTTP_201_CREATED, node=node))
|
||||
except ControllerError as e:
|
||||
log.error(f"Could not create node {node_create.name} in batch: {e}")
|
||||
results.append(
|
||||
schemas.NodeBatchResult(
|
||||
status_code=controller_error_status_code(e), error=schemas.ErrorMessage(message=str(e))
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=List[schemas.Node],
|
||||
|
||||
@@ -75,3 +75,21 @@ class ComputeConflictError(ComputeError):
|
||||
|
||||
def response(self):
|
||||
return self._response
|
||||
|
||||
|
||||
def controller_error_status_code(error: ControllerError) -> int:
|
||||
"""
|
||||
HTTP status code returned by the API for a controller error.
|
||||
"""
|
||||
|
||||
if isinstance(error, ControllerTimeoutError):
|
||||
return 408
|
||||
if isinstance(error, ControllerUnauthorizedError):
|
||||
return 401
|
||||
if isinstance(error, ControllerForbiddenError):
|
||||
return 403
|
||||
if isinstance(error, ControllerNotFoundError):
|
||||
return 404
|
||||
if isinstance(error, ControllerBadRequestError):
|
||||
return 400
|
||||
return 409
|
||||
@@ -100,7 +100,9 @@ class Node:
|
||||
"default_password",
|
||||
]
|
||||
|
||||
def __init__(self, project, compute, name, node_id=None, node_type=None, template_id=None, **kwargs):
|
||||
def __init__(
|
||||
self, project, compute, name, node_id=None, node_type=None, template_id=None, strict_names=False, **kwargs
|
||||
):
|
||||
"""
|
||||
:param project: Project of the node
|
||||
:param compute: Compute where the server will run
|
||||
@@ -108,6 +110,7 @@ class Node:
|
||||
:param node_id: UUID of the node (integer)
|
||||
:param node_type: Type of emulator
|
||||
:param template_id: Template ID used to create this node
|
||||
:param strict_names: Fail instead of renaming the node when the name is already used
|
||||
:param kwargs: Node properties
|
||||
"""
|
||||
|
||||
@@ -125,7 +128,7 @@ class Node:
|
||||
self._label = None
|
||||
self._links = set()
|
||||
self._name = None
|
||||
self.name = name
|
||||
self._name = project.update_node_name(self, name, strict=strict_names)
|
||||
self._console = None
|
||||
self._console_type = None
|
||||
self._aux = None
|
||||
|
||||
@@ -557,17 +557,20 @@ class Project:
|
||||
if name in self._allocated_node_names:
|
||||
self._allocated_node_names.remove(name)
|
||||
|
||||
def update_allocated_node_name(self, base_name):
|
||||
def update_allocated_node_name(self, base_name, strict=False):
|
||||
"""
|
||||
Updates a node name or generate a new if no node
|
||||
name is available.
|
||||
|
||||
:param base_name: new node base name
|
||||
:param strict: raise an error instead of renaming when the name is already taken
|
||||
"""
|
||||
|
||||
if base_name is None:
|
||||
return None
|
||||
base_name = re.sub(r"[ ]", "", base_name) # remove spaces in node name
|
||||
if strict and base_name in self._allocated_node_names:
|
||||
raise ControllerError(f"Node name {base_name} is already used")
|
||||
if base_name in self._allocated_node_names:
|
||||
base_name = re.sub(r"[0-9]+$", "{0}", base_name)
|
||||
|
||||
@@ -595,11 +598,11 @@ class Project:
|
||||
return name
|
||||
raise ControllerError("A node name could not be allocated (node limit reached?)")
|
||||
|
||||
def update_node_name(self, node, new_name):
|
||||
def update_node_name(self, node, new_name, strict=False):
|
||||
|
||||
if new_name and node.name != new_name:
|
||||
self.remove_allocated_node_name(node.name)
|
||||
return self.update_allocated_node_name(new_name)
|
||||
return self.update_allocated_node_name(new_name, strict=strict)
|
||||
return new_name
|
||||
|
||||
@open_required
|
||||
@@ -630,26 +633,32 @@ class Project:
|
||||
node = await self.add_node(compute, name, node_id, node_type=node_type, **template)
|
||||
return node
|
||||
|
||||
async def _create_node(self, compute, name, node_id, node_type=None, allow_missing_image=False, **kwargs):
|
||||
async def _create_node(
|
||||
self, compute, name, node_id, node_type=None, allow_missing_image=False, strict_names=False, **kwargs
|
||||
):
|
||||
|
||||
node = Node(self, compute, name, node_id=node_id, node_type=node_type, **kwargs)
|
||||
# Hold the lock across the check + POST + register so that concurrent
|
||||
# node creations on the same compute don't all race past the check and
|
||||
# each POST /projects (the compute-side sync handler then instantiated
|
||||
# the Project N times). Once one creation registers the compute, the
|
||||
# rest see it in the set and return immediately.
|
||||
async with self._create_node_lock:
|
||||
if compute not in self._project_created_on_compute:
|
||||
if compute.id == "local":
|
||||
data = {"name": self._name, "project_id": self._id, "path": self._path}
|
||||
else:
|
||||
data = {"name": self._name, "project_id": self._id}
|
||||
if self._variables:
|
||||
data["variables"] = self._variables
|
||||
await compute.post("/projects", data=data)
|
||||
self._project_created_on_compute.add(compute)
|
||||
node = Node(self, compute, name, node_id=node_id, node_type=node_type, strict_names=strict_names, **kwargs)
|
||||
try:
|
||||
# Hold the lock across the check + POST + register so that concurrent
|
||||
# node creations on the same compute don't all race past the check and
|
||||
# each POST /projects (the compute-side sync handler then instantiated
|
||||
# the Project N times). Once one creation registers the compute, the
|
||||
# rest see it in the set and return immediately.
|
||||
async with self._create_node_lock:
|
||||
if compute not in self._project_created_on_compute:
|
||||
if compute.id == "local":
|
||||
data = {"name": self._name, "project_id": self._id, "path": self._path}
|
||||
else:
|
||||
data = {"name": self._name, "project_id": self._id}
|
||||
if self._variables:
|
||||
data["variables"] = self._variables
|
||||
await compute.post("/projects", data=data)
|
||||
self._project_created_on_compute.add(compute)
|
||||
|
||||
await node.create(allow_missing_image=allow_missing_image)
|
||||
await node.create(allow_missing_image=allow_missing_image)
|
||||
except BaseException:
|
||||
self.remove_allocated_node_name(node.name)
|
||||
raise
|
||||
self._nodes[node.id] = node
|
||||
|
||||
return node
|
||||
|
||||
@@ -35,6 +35,7 @@ from .controller.images import Image, ImageSyncJob, ImageSyncRequest, ImageType,
|
||||
from .controller.links import (
|
||||
EthernetPortInfo,
|
||||
Link,
|
||||
LinkBatchResult,
|
||||
LinkCapture,
|
||||
LinkCreate,
|
||||
LinkUpdate,
|
||||
@@ -43,7 +44,7 @@ from .controller.links import (
|
||||
MarkerUpdate,
|
||||
UDPPortInfo,
|
||||
)
|
||||
from .controller.nodes import Node, NodeCapture, NodeCreate, NodeDuplicate, NodeUpdate
|
||||
from .controller.nodes import Node, NodeBatchResult, NodeCapture, NodeCreate, NodeDuplicate, NodeUpdate
|
||||
from .controller.projects import (
|
||||
NodeFile,
|
||||
Project,
|
||||
@@ -242,6 +243,7 @@ __all__ = [
|
||||
"LLMModelConfigUpdate",
|
||||
"LLMModelConfigWithSource",
|
||||
"Link",
|
||||
"LinkBatchResult",
|
||||
"LinkCapture",
|
||||
"LinkCreate",
|
||||
"LinkUpdate",
|
||||
@@ -256,6 +258,7 @@ __all__ = [
|
||||
"NetmikoDeviceType",
|
||||
"NetmikoDeviceTypeList",
|
||||
"Node",
|
||||
"NodeBatchResult",
|
||||
"NodeCapture",
|
||||
"NodeCreate",
|
||||
"NodeDuplicate",
|
||||
|
||||
@@ -20,6 +20,7 @@ from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from ..common import ErrorMessage
|
||||
from ..update import PartialUpdateModel
|
||||
from .labels import Label
|
||||
|
||||
@@ -97,6 +98,16 @@ class Link(LinkBase):
|
||||
)
|
||||
|
||||
|
||||
class LinkBatchResult(BaseModel):
|
||||
"""
|
||||
Outcome of one link of a batch creation request.
|
||||
"""
|
||||
|
||||
status_code: int = Field(..., description="HTTP status code the same request would have returned on its own")
|
||||
link: Optional[Link] = Field(None, description="The created link, set when status_code is 201")
|
||||
error: Optional[ErrorMessage] = Field(None, description="The error, set when the link could not be created")
|
||||
|
||||
|
||||
class UDPPortInfo(BaseModel):
|
||||
"""
|
||||
UDP port information.
|
||||
|
||||
@@ -20,7 +20,7 @@ from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..common import ConsoleType, CustomAdapter, NodeStatus
|
||||
from ..common import ConsoleType, CustomAdapter, ErrorMessage, NodeStatus
|
||||
from ..update import PartialUpdateModel
|
||||
from .labels import Label
|
||||
|
||||
@@ -168,6 +168,10 @@ class NodeCreate(NodeBase):
|
||||
name: str
|
||||
node_type: NodeType
|
||||
node_id: UUID = Field(default_factory=uuid4)
|
||||
strict_names: bool = Field(
|
||||
False,
|
||||
description="Return a 409 error instead of renaming the node when the requested name is already used",
|
||||
)
|
||||
|
||||
|
||||
class NodeUpdate(PartialUpdateModel, NodeBase):
|
||||
@@ -205,6 +209,16 @@ class Node(NodeBase):
|
||||
)
|
||||
|
||||
|
||||
class NodeBatchResult(BaseModel):
|
||||
"""
|
||||
Outcome of one node of a batch creation request.
|
||||
"""
|
||||
|
||||
status_code: int = Field(..., description="HTTP status code the same request would have returned on its own")
|
||||
node: Optional[Node] = Field(None, description="The created node, set when status_code is 201")
|
||||
error: Optional[ErrorMessage] = Field(None, description="The error, set when the node could not be created")
|
||||
|
||||
|
||||
class NodeDuplicate(BaseModel):
|
||||
"""
|
||||
Data to duplicate a node.
|
||||
|
||||
Reference in new issue
Block a user