1
0
mirror of https://github.com/GNS3/gns3-server synced 2024-12-26 00:38:10 +00:00

Move schemas between compute and controller subpackages

This commit is contained in:
grossmj 2021-04-15 18:12:08 +09:30
parent c59fc375f2
commit 9c850e0f2b
57 changed files with 332 additions and 214 deletions

View File

@ -138,35 +138,103 @@ async def http_exception_handler(request: Request, exc: StarletteHTTPException):
) )
compute_api.include_router(capabilities.router, tags=["Capabilities"])
compute_api.include_router(compute.router, tags=["Compute"])
compute_api.include_router(notifications.router, tags=["Notifications"])
compute_api.include_router(projects.router, tags=["Projects"])
compute_api.include_router(images.router, tags=["Images"])
compute_api.include_router( compute_api.include_router(
atm_switch_nodes.router, prefix="/projects/{project_id}/atm_switch/nodes", tags=["ATM switch"] capabilities.router,
tags=["Capabilities"]
) )
compute_api.include_router(cloud_nodes.router, prefix="/projects/{project_id}/cloud/nodes", tags=["Cloud nodes"])
compute_api.include_router(docker_nodes.router, prefix="/projects/{project_id}/docker/nodes", tags=["Docker nodes"])
compute_api.include_router( compute_api.include_router(
dynamips_nodes.router, prefix="/projects/{project_id}/dynamips/nodes", tags=["Dynamips nodes"] compute.router,
tags=["Compute"]
)
compute_api.include_router(
notifications.router,
tags=["Notifications"]
)
compute_api.include_router(
projects.router,
tags=["Projects"]
)
compute_api.include_router(
images.router,
tags=["Images"]
)
compute_api.include_router(
atm_switch_nodes.router,
prefix="/projects/{project_id}/atm_switch/nodes",
tags=["ATM switch"]
) )
compute_api.include_router( compute_api.include_router(
ethernet_hub_nodes.router, prefix="/projects/{project_id}/ethernet_hub/nodes", tags=["Ethernet hub nodes"] cloud_nodes.router,
prefix="/projects/{project_id}/cloud/nodes",
tags=["Cloud nodes"]
) )
compute_api.include_router( compute_api.include_router(
ethernet_switch_nodes.router, prefix="/projects/{project_id}/ethernet_switch/nodes", tags=["Ethernet switch nodes"] docker_nodes.router,
prefix="/projects/{project_id}/docker/nodes",
tags=["Docker nodes"]
) )
compute_api.include_router(
dynamips_nodes.router,
prefix="/projects/{project_id}/dynamips/nodes",
tags=["Dynamips nodes"]
)
compute_api.include_router(
ethernet_hub_nodes.router,
prefix="/projects/{project_id}/ethernet_hub/nodes",
tags=["Ethernet hub nodes"]
)
compute_api.include_router(
ethernet_switch_nodes.router,
prefix="/projects/{project_id}/ethernet_switch/nodes",
tags=["Ethernet switch nodes"]
)
compute_api.include_router( compute_api.include_router(
frame_relay_switch_nodes.router, frame_relay_switch_nodes.router,
prefix="/projects/{project_id}/frame_relay_switch/nodes", prefix="/projects/{project_id}/frame_relay_switch/nodes",
tags=["Frame Relay switch nodes"], tags=["Frame Relay switch nodes"]
) )
compute_api.include_router(iou_nodes.router, prefix="/projects/{project_id}/iou/nodes", tags=["IOU nodes"])
compute_api.include_router(nat_nodes.router, prefix="/projects/{project_id}/nat/nodes", tags=["NAT nodes"])
compute_api.include_router(qemu_nodes.router, prefix="/projects/{project_id}/qemu/nodes", tags=["Qemu nodes"])
compute_api.include_router( compute_api.include_router(
virtualbox_nodes.router, prefix="/projects/{project_id}/virtualbox/nodes", tags=["VirtualBox nodes"] iou_nodes.router,
prefix="/projects/{project_id}/iou/nodes",
tags=["IOU nodes"])
compute_api.include_router(
nat_nodes.router,
prefix="/projects/{project_id}/nat/nodes",
tags=["NAT nodes"]
)
compute_api.include_router(
qemu_nodes.router,
prefix="/projects/{project_id}/qemu/nodes",
tags=["Qemu nodes"]
)
compute_api.include_router(
virtualbox_nodes.router,
prefix="/projects/{project_id}/virtualbox/nodes",
tags=["VirtualBox nodes"]
)
compute_api.include_router(
vmware_nodes.router,
prefix="/projects/{project_id}/vmware/nodes",
tags=["VMware nodes"]
)
compute_api.include_router(
vpcs_nodes.router,
prefix="/projects/{project_id}/vpcs/nodes",
tags=["VPCS nodes"]
) )
compute_api.include_router(vmware_nodes.router, prefix="/projects/{project_id}/vmware/nodes", tags=["VMware nodes"])
compute_api.include_router(vpcs_nodes.router, prefix="/projects/{project_id}/vpcs/nodes", tags=["VPCS nodes"])

View File

@ -149,11 +149,6 @@ async def start_virtualbox_node(node: VirtualBoxVM = Depends(dep_node)):
Start a VirtualBox node. Start a VirtualBox node.
""" """
if await node.check_hw_virtualization():
pm = ProjectManager.instance()
if pm.check_hardware_virtualization(node) is False:
pass # FIXME: check this
# raise ComputeError("Cannot start VM with hardware acceleration (KVM/HAX) enabled because hardware virtualization (VT-x/AMD-V) is already used by another software like VMware or VirtualBox")
await node.start() await node.start()

View File

@ -117,11 +117,6 @@ async def start_vmware_node(node: VMwareVM = Depends(dep_node)):
Start a VMware node. Start a VMware node.
""" """
if node.check_hw_virtualization():
pm = ProjectManager.instance()
if pm.check_hardware_virtualization(node) is False:
pass # FIXME: check this
# raise ComputeError("Cannot start VM with hardware acceleration (KVM/HAX) enabled because hardware virtualization (VT-x/AMD-V) is already used by another software like VMware or VirtualBox")
await node.start() await node.start()

View File

@ -108,7 +108,7 @@ async def dep_node(node_id: UUID, project: Project = Depends(dep_project)):
409: {"model": schemas.ErrorMessage, "description": "Could not create node"}, 409: {"model": schemas.ErrorMessage, "description": "Could not create node"},
}, },
) )
async def create_node(node_data: schemas.Node, project: Project = Depends(dep_project)): async def create_node(node_data: schemas.NodeCreate, project: Project = Depends(dep_project)):
""" """
Create a new node. Create a new node.
""" """

View File

@ -120,18 +120,3 @@ class ProjectManager:
if project_id not in self._projects: if project_id not in self._projects:
raise ComputeNotFoundError(f"Project ID {project_id} doesn't exist") raise ComputeNotFoundError(f"Project ID {project_id} doesn't exist")
del self._projects[project_id] del self._projects[project_id]
def check_hardware_virtualization(self, source_node):
"""
Checks if hardware virtualization can be used.
:returns: boolean
"""
for project in self._projects.values():
for node in project.nodes:
if node == source_node:
continue
if node.hw_virtualization and node.__class__.__name__ != source_node.__class__.__name__:
return False
return True

View File

@ -47,7 +47,7 @@ from ...utils.asyncio import monitor_process
from ...utils.images import md5sum from ...utils.images import md5sum
from ...utils import macaddress_to_int, int_to_macaddress from ...utils import macaddress_to_int, int_to_macaddress
from gns3server.schemas.qemu_nodes import Qemu, QemuPlatform from gns3server.schemas.compute.qemu_nodes import Qemu, QemuPlatform
import logging import logging

View File

@ -353,6 +353,7 @@ class Controller:
self._computes[compute.id] = compute self._computes[compute.id] = compute
# self.save() # self.save()
if connect: if connect:
# call compute.connect() later to give time to the controller to be fully started
asyncio.get_event_loop().call_later(1, lambda: asyncio.ensure_future(compute.connect())) asyncio.get_event_loop().call_later(1, lambda: asyncio.ensure_future(compute.connect()))
self.notification.controller_emit("compute.created", compute.__json__()) self.notification.controller_emit("compute.created", compute.__json__())
return compute return compute

View File

@ -203,6 +203,7 @@ class Drawing:
""" """
:param topology_dump: Filter to keep only properties require for saving on disk :param topology_dump: Filter to keep only properties require for saving on disk
""" """
if topology_dump: if topology_dump:
return { return {
"drawing_id": self._id, "drawing_id": self._id,

View File

@ -31,8 +31,8 @@ from ..utils.qt import qt_font_to_style
from ..compute.dynamips import PLATFORMS_DEFAULT_RAM from ..compute.dynamips import PLATFORMS_DEFAULT_RAM
from .controller_error import ControllerError from .controller_error import ControllerError
from gns3server.schemas.topology import Topology from gns3server.schemas.controller.topology import Topology
from gns3server.schemas.dynamips_nodes import DynamipsCreate from gns3server.schemas.compute.dynamips_nodes import DynamipsCreate
import logging import logging

View File

@ -33,6 +33,10 @@ log = logging.getLogger(__name__)
def create_startup_handler(app: FastAPI) -> Callable: def create_startup_handler(app: FastAPI) -> Callable:
"""
Tasks to be performed when the server is starting.
"""
async def start_app() -> None: async def start_app() -> None:
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
logger = logging.getLogger("asyncio") logger = logging.getLogger("asyncio")
@ -77,6 +81,10 @@ def create_startup_handler(app: FastAPI) -> Callable:
def create_shutdown_handler(app: FastAPI) -> Callable: def create_shutdown_handler(app: FastAPI) -> Callable:
"""
Tasks to be performed when the server is shutdown.
"""
async def shutdown_handler() -> None: async def shutdown_handler() -> None:
await HTTPClient.close_session() await HTTPClient.close_session()
await Controller.instance().stop() await Controller.instance().stop()

View File

@ -14,46 +14,36 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# General schemas
from .config import ServerConfig from .config import ServerConfig
from .iou_license import IOULicense
from .links import Link
from .common import ErrorMessage from .common import ErrorMessage
from .version import Version from .version import Version
from .computes import ComputeCreate, ComputeUpdate, AutoIdlePC, Compute
from .templates import TemplateCreate, TemplateUpdate, TemplateUsage, Template
from .drawings import Drawing
from .gns3vm import GNS3VM
from .nodes import NodeUpdate, NodeDuplicate, NodeCapture, Node
from .projects import ProjectCreate, ProjectUpdate, ProjectDuplicate, Project, ProjectFile
from .users import UserCreate, UserUpdate, User
from .tokens import Token
from .snapshots import SnapshotCreate, Snapshot
from .capabilities import Capabilities
from .nios import UDPNIO, TAPNIO, EthernetNIO
from .atm_switch_nodes import ATMSwitchCreate, ATMSwitchUpdate, ATMSwitch
from .cloud_nodes import CloudCreate, CloudUpdate, Cloud
from .docker_nodes import DockerCreate, DockerUpdate, Docker
from .dynamips_nodes import DynamipsCreate, DynamipsUpdate, Dynamips
from .ethernet_hub_nodes import EthernetHubCreate, EthernetHubUpdate, EthernetHub
from .ethernet_switch_nodes import EthernetSwitchCreate, EthernetSwitchUpdate, EthernetSwitch
from .frame_relay_switch_nodes import FrameRelaySwitchCreate, FrameRelaySwitchUpdate, FrameRelaySwitch
from .qemu_nodes import QemuCreate, QemuUpdate, QemuImageCreate, QemuImageUpdate, QemuDiskResize, Qemu
from .iou_nodes import IOUCreate, IOUUpdate, IOUStart, IOU
from .nat_nodes import NATCreate, NATUpdate, NAT
from .vpcs_nodes import VPCSCreate, VPCSUpdate, VPCS
from .vmware_nodes import VMwareCreate, VMwareUpdate, VMware
from .virtualbox_nodes import VirtualBoxCreate, VirtualBoxUpdate, VirtualBox
from .vpcs_templates import VPCSTemplate # Controller schemas
from .cloud_templates import CloudTemplate from .controller.links import Link
from .iou_templates import IOUTemplate from .controller.computes import ComputeCreate, ComputeUpdate, AutoIdlePC, Compute
from .docker_templates import DockerTemplate from .controller.templates import TemplateCreate, TemplateUpdate, TemplateUsage, Template
from .ethernet_hub_templates import EthernetHubTemplate from .controller.drawings import Drawing
from .ethernet_switch_templates import EthernetSwitchTemplate from .controller.gns3vm import GNS3VM
from .virtualbox_templates import VirtualBoxTemplate from .controller.nodes import NodeCreate, NodeUpdate, NodeDuplicate, NodeCapture, Node
from .vmware_templates import VMwareTemplate from .controller.projects import ProjectCreate, ProjectUpdate, ProjectDuplicate, Project, ProjectFile
from .qemu_templates import QemuTemplate from .controller.users import UserCreate, UserUpdate, User
from .dynamips_templates import ( from .controller.tokens import Token
from .controller.snapshots import SnapshotCreate, Snapshot
from .controller.iou_license import IOULicense
from .controller.capabilities import Capabilities
# Controller template schemas
from .controller.templates.vpcs_templates import VPCSTemplate
from .controller.templates.cloud_templates import CloudTemplate
from .controller.templates.iou_templates import IOUTemplate
from .controller.templates.docker_templates import DockerTemplate
from .controller.templates.ethernet_hub_templates import EthernetHubTemplate
from .controller.templates.ethernet_switch_templates import EthernetSwitchTemplate
from .controller.templates.virtualbox_templates import VirtualBoxTemplate
from .controller.templates.vmware_templates import VMwareTemplate
from .controller.templates.qemu_templates import QemuTemplate
from .controller.templates.dynamips_templates import (
DynamipsTemplate, DynamipsTemplate,
C1700DynamipsTemplate, C1700DynamipsTemplate,
C2600DynamipsTemplate, C2600DynamipsTemplate,
@ -63,3 +53,19 @@ from .dynamips_templates import (
C3745DynamipsTemplate, C3745DynamipsTemplate,
C7200DynamipsTemplate, C7200DynamipsTemplate,
) )
# Compute schemas
from .compute.nios import UDPNIO, TAPNIO, EthernetNIO
from .compute.atm_switch_nodes import ATMSwitchCreate, ATMSwitchUpdate, ATMSwitch
from .compute.cloud_nodes import CloudCreate, CloudUpdate, Cloud
from .compute.docker_nodes import DockerCreate, DockerUpdate, Docker
from .compute.dynamips_nodes import DynamipsCreate, DynamipsUpdate, Dynamips
from .compute.ethernet_hub_nodes import EthernetHubCreate, EthernetHubUpdate, EthernetHub
from .compute.ethernet_switch_nodes import EthernetSwitchCreate, EthernetSwitchUpdate, EthernetSwitch
from .compute.frame_relay_switch_nodes import FrameRelaySwitchCreate, FrameRelaySwitchUpdate, FrameRelaySwitch
from .compute.qemu_nodes import QemuCreate, QemuUpdate, QemuImageCreate, QemuImageUpdate, QemuDiskResize, Qemu
from .compute.iou_nodes import IOUCreate, IOUUpdate, IOUStart, IOU
from .compute.nat_nodes import NATCreate, NATUpdate, NAT
from .compute.vpcs_nodes import VPCSCreate, VPCSUpdate, VPCS
from .compute.vmware_nodes import VMwareCreate, VMwareUpdate, VMware
from .compute.virtualbox_nodes import VirtualBoxCreate, VirtualBoxUpdate, VirtualBox

View File

@ -16,6 +16,7 @@
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, Union from typing import Optional, Union
from enum import Enum
class ErrorMessage(BaseModel): class ErrorMessage(BaseModel):
@ -26,14 +27,45 @@ class ErrorMessage(BaseModel):
message: str message: str
class Label(BaseModel): class NodeStatus(str, Enum):
""" """
Label data. Supported node statuses.
""" """
text: str stopped = "stopped"
style: Optional[Union[str, None]] = Field(None, description="SVG style attribute. Apply default style if null") started = "started"
x: Optional[Union[int, None]] = Field(None, description="Relative X position of the label. Center it if null") suspended = "suspended"
y: Optional[int] = Field(None, description="Relative Y position of the label")
rotation: Optional[int] = Field(None, ge=-359, le=360, description="Rotation of the label")
class CustomAdapter(BaseModel):
"""
Custom adapter data.
"""
adapter_number: int
port_name: Optional[str] = None
adapter_type: Optional[str] = None
mac_address: Optional[str] = Field(None, regex="^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$")
class ConsoleType(str, Enum):
"""
Supported console types.
"""
vnc = "vnc"
telnet = "telnet"
http = "http"
https = "https"
spice = "spice"
spice_agent = "spice+agent"
none = "none"
class AuxType(str, Enum):
"""
Supported auxiliary console types.
"""
telnet = "telnet"
none = "none"

View File

@ -18,7 +18,7 @@ from pydantic import BaseModel
from typing import Optional from typing import Optional
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class ATMSwitchBase(BaseModel): class ATMSwitchBase(BaseModel):

View File

@ -19,7 +19,7 @@ from typing import Optional, Union, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class HostInterfaceType(Enum): class HostInterfaceType(Enum):

View File

@ -18,7 +18,7 @@ from pydantic import BaseModel, Field
from typing import Optional, List from typing import Optional, List
from uuid import UUID from uuid import UUID
from .nodes import CustomAdapter, ConsoleType, AuxType, NodeStatus from ..common import NodeStatus, CustomAdapter, ConsoleType, AuxType
class DockerBase(BaseModel): class DockerBase(BaseModel):

View File

@ -20,7 +20,7 @@ from typing import Optional, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class DynamipsPlatform(str, Enum): class DynamipsPlatform(str, Enum):

View File

@ -18,7 +18,7 @@ from pydantic import BaseModel
from typing import Optional, List from typing import Optional, List
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class EthernetHubPort(BaseModel): class EthernetHubPort(BaseModel):

View File

@ -19,7 +19,7 @@ from typing import Optional, List
from uuid import UUID from uuid import UUID
from enum import Enum from enum import Enum
from .nodes import NodeStatus from ..common import NodeStatus
class EthernetSwitchPortType(Enum): class EthernetSwitchPortType(Enum):

View File

@ -18,7 +18,7 @@ from pydantic import BaseModel
from typing import Optional from typing import Optional
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class FrameRelaySwitchBase(BaseModel): class FrameRelaySwitchBase(BaseModel):

View File

@ -18,7 +18,7 @@ from pydantic import BaseModel, Field
from typing import Optional from typing import Optional
from uuid import UUID from uuid import UUID
from .nodes import ConsoleType, NodeStatus from ..common import NodeStatus, ConsoleType
class IOUBase(BaseModel): class IOUBase(BaseModel):

View File

@ -19,7 +19,7 @@ from typing import Optional, Union, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus from ..common import NodeStatus
class HostInterfaceType(Enum): class HostInterfaceType(Enum):

View File

@ -16,9 +16,8 @@
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, Union, Generic from typing import Optional
from enum import Enum from enum import Enum
from uuid import UUID
class UDPNIOType(Enum): class UDPNIOType(Enum):

View File

@ -19,7 +19,7 @@ from typing import Optional, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import CustomAdapter, NodeStatus from ..common import NodeStatus, CustomAdapter
class QemuPlatform(str, Enum): class QemuPlatform(str, Enum):

View File

@ -19,7 +19,7 @@ from typing import Optional, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus, CustomAdapter from ..common import NodeStatus, CustomAdapter
class VirtualBoxConsoleType(str, Enum): class VirtualBoxConsoleType(str, Enum):

View File

@ -19,7 +19,7 @@ from typing import Optional, List
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus, CustomAdapter from ..common import NodeStatus, CustomAdapter
class VMwareConsoleType(str, Enum): class VMwareConsoleType(str, Enum):

View File

@ -19,7 +19,7 @@ from typing import Optional
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeStatus, CustomAdapter from ..common import NodeStatus
class ConsoleType(str, Enum): class ConsoleType(str, Enum):

View File

@ -15,7 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import Enum from enum import Enum
from pydantic import BaseModel, Field, SecretStr, FilePath, validator from pydantic import BaseModel, Field, SecretStr, FilePath, DirectoryPath, validator
from typing import List from typing import List
@ -113,7 +113,7 @@ class ServerSettings(BaseModel):
protocol: ServerProtocol = ServerProtocol.http protocol: ServerProtocol = ServerProtocol.http
host: str = "0.0.0.0" host: str = "0.0.0.0"
port: int = Field(3080, gt=0, le=65535) port: int = Field(3080, gt=0, le=65535)
secrets_dir: str = None secrets_dir: DirectoryPath = None
certfile: FilePath = None certfile: FilePath = None
certkey: FilePath = None certkey: FilePath = None
enable_ssl: bool = False enable_ssl: bool = False
@ -167,7 +167,7 @@ class ServerSettings(BaseModel):
if v is True: if v is True:
if "user" not in values or not values["user"]: if "user" not in values or not values["user"]:
raise ValueError("HTTP authentication is enabled but no username is configured") raise ValueError("HTTP authentication is enabled but user is not configured")
return v return v
@validator("enable_ssl") @validator("enable_ssl")

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python
# #
# Copyright (C) 2020 GNS3 Technologies Inc. # Copyright (C) 2021 GNS3 Technologies Inc.
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
@ -14,3 +13,18 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from pydantic import BaseModel, Field
from typing import Optional, Union
class Label(BaseModel):
"""
Label data.
"""
text: str
style: Optional[Union[str, None]] = Field(None, description="SVG style attribute. Apply default style if null")
x: Optional[Union[int, None]] = Field(None, description="Relative X position of the label. Center it if null")
y: Optional[int] = Field(None, description="Relative Y position of the label")
rotation: Optional[int] = Field(None, ge=-359, le=360, description="Rotation of the label")

View File

@ -19,7 +19,7 @@ from typing import List, Optional
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .common import Label from .labels import Label
class LinkNode(BaseModel): class LinkNode(BaseModel):

View File

@ -14,12 +14,13 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from pydantic import BaseModel, Field from pydantic import BaseModel, Field, validator
from typing import List, Optional, Union from typing import List, Optional, Union
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID, uuid4
from .common import Label from .labels import Label
from ..common import ConsoleType, NodeStatus, CustomAdapter
class NodeType(str, Enum): class NodeType(str, Enum):
@ -74,39 +75,6 @@ class DataLinkType(str, Enum):
ppp = "DLT_PPP_SERIAL" ppp = "DLT_PPP_SERIAL"
class ConsoleType(str, Enum):
"""
Supported console types.
"""
vnc = "vnc"
telnet = "telnet"
http = "http"
https = "https"
spice = "spice"
spice_agent = "spice+agent"
none = "none"
class AuxType(str, Enum):
"""
Supported auxiliary console types.
"""
telnet = "telnet"
none = "none"
class NodeStatus(str, Enum):
"""
Supported node statuses.
"""
stopped = "stopped"
started = "started"
suspended = "suspended"
class NodeCapture(BaseModel): class NodeCapture(BaseModel):
""" """
Node capture data. Node capture data.
@ -116,17 +84,6 @@ class NodeCapture(BaseModel):
data_link_type: Optional[DataLinkType] = None data_link_type: Optional[DataLinkType] = None
class CustomAdapter(BaseModel):
"""
Custom adapter data.
"""
adapter_number: int
port_name: Optional[str] = None
adapter_type: Optional[str] = None
mac_address: Optional[str] = Field(None, regex="^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$")
class NodePort(BaseModel): class NodePort(BaseModel):
""" """
Node port data. Node port data.
@ -142,7 +99,7 @@ class NodePort(BaseModel):
mac_address: Union[str, None] = Field(None, regex="^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$") mac_address: Union[str, None] = Field(None, regex="^([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})$")
class Node(BaseModel): class NodeBase(BaseModel):
""" """
Node data. Node data.
""" """
@ -150,44 +107,56 @@ class Node(BaseModel):
compute_id: Union[UUID, str] compute_id: Union[UUID, str]
name: str name: str
node_type: NodeType node_type: NodeType
project_id: Optional[UUID] = None
node_id: Optional[UUID] = None node_id: Optional[UUID] = None
template_id: Optional[UUID] = Field(
None, description="Template UUID from which the node has been created. Read only"
)
node_directory: Optional[str] = Field(None, description="Working directory of the node. Read only")
command_line: Optional[str] = Field(None, description="Command line use to start the node")
console: Optional[int] = Field(None, gt=0, le=65535, description="Console TCP port") console: Optional[int] = Field(None, gt=0, le=65535, description="Console TCP port")
console_host: Optional[str] = Field(
None,
description="Console host. Warning if the host is 0.0.0.0 or :: (listen on all interfaces) you need to use the same address you use to connect to the controller",
)
console_type: Optional[ConsoleType] = None console_type: Optional[ConsoleType] = None
console_auto_start: Optional[bool] = Field( console_auto_start: Optional[bool] = Field(
None, description="Automatically start the console when the node has started" False, description="Automatically start the console when the node has started"
) )
aux: Optional[int] = Field(None, gt=0, le=65535, description="Auxiliary console TCP port") aux: Optional[int] = Field(None, gt=0, le=65535, description="Auxiliary console TCP port")
aux_type: Optional[ConsoleType] aux_type: Optional[ConsoleType]
properties: Optional[dict] = Field(None, description="Properties specific to an emulator") properties: Optional[dict] = Field(default_factory=dict, description="Properties specific to an emulator")
status: Optional[NodeStatus] = None
label: Optional[Label] = None label: Optional[Label] = None
symbol: Optional[str] = None symbol: Optional[str] = None
width: Optional[int] = Field(None, description="Width of the node (Read only)")
height: Optional[int] = Field(None, description="Height of the node (Read only)") x: Optional[int] = 0
x: Optional[int] = None y: Optional[int] = 0
y: Optional[int] = None z: Optional[int] = 1
z: Optional[int] = None locked: Optional[bool] = Field(False, description="Whether the element locked or not")
locked: Optional[bool] = Field(None, description="Whether the element locked or not")
port_name_format: Optional[str] = Field( port_name_format: Optional[str] = Field(
None, description="Formatting for port name {0} will be replace by port number" None, descript_port_name_formation="Formatting for port name {0} will be replace by port number"
) )
port_segment_size: Optional[int] = Field(None, description="Size of the port segment") port_segment_size: Optional[int] = Field(None, description="Size of the port segment")
first_port_name: Optional[str] = Field(None, description="Name of the first port") first_port_name: Optional[str] = Field(None, description="Name of the first port")
custom_adapters: Optional[List[CustomAdapter]] = None custom_adapters: Optional[List[CustomAdapter]] = None
ports: Optional[List[NodePort]] = Field(None, description="List of node ports (read only)")
@validator("port_name_format", pre=True, always=True)
def default_port_name_format(cls, v, values):
if v is None:
if "node_type" in values and values["node_type"] == NodeType.iou:
return "Ethernet{segment0}/{port0}"
return "Ethernet{0}"
return v
@validator("port_segment_size", pre=True, always=True)
def default_port_segment_size(cls, v, values):
if v is None:
if "node_type" in values and values["node_type"] == NodeType.iou:
return 4
return 0
return v
class NodeUpdate(Node): class NodeCreate(NodeBase):
node_id: UUID = Field(default_factory=uuid4)
class NodeUpdate(NodeBase):
""" """
Data to update a node. Data to update a node.
""" """
@ -197,6 +166,23 @@ class NodeUpdate(Node):
node_type: Optional[NodeType] = None node_type: Optional[NodeType] = None
class Node(NodeBase):
template_id: Optional[UUID] = Field(None,
description="Template UUID from which the node has been created. Read only")
project_id: Optional[UUID] = None
node_directory: Optional[str] = Field(None, description="Working directory of the node. Read only")
status: Optional[NodeStatus] = Field(None, description="Node status. Read only")
command_line: Optional[str] = Field(None, description="Command line use to start the node. Read only")
width: Optional[int] = Field(None, description="Width of the node. Read only")
height: Optional[int] = Field(None, description="Height of the node. Read only")
ports: Optional[List[NodePort]] = Field(None, description="List of node ports. Read only")
console_host: Optional[str] = Field(
None,
description="Console host. Warning if the host is 0.0.0.0 or :: (listen on all interfaces) you need to use the same address you use to connect to the controller",
)
class NodeDuplicate(BaseModel): class NodeDuplicate(BaseModel):
""" """
Data to duplicate a node. Data to duplicate a node.

View File

@ -1,5 +1,5 @@
# #
# Copyright (C) 2020 GNS3 Technologies Inc. # Copyright (C) 2021 GNS3 Technologies Inc.
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
@ -19,8 +19,8 @@ from typing import Optional, Union
from enum import Enum from enum import Enum
from uuid import UUID from uuid import UUID
from .nodes import NodeType from ..nodes import NodeType
from .base import DateTimeModelMixin from ..base import DateTimeModelMixin
class Category(str, Enum): class Category(str, Enum):

View File

@ -15,8 +15,13 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .cloud_nodes import EthernetPort, TAPPort, UDPPort, CloudConsoleType from gns3server.schemas.compute.cloud_nodes import (
EthernetPort,
TAPPort,
UDPPort,
CloudConsoleType
)
from pydantic import Field from pydantic import Field
from typing import Optional, Union, List from typing import Optional, Union, List

View File

@ -15,9 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .nodes import CustomAdapter from ...common import ConsoleType, AuxType, CustomAdapter
from .docker_nodes import ConsoleType, AuxType
from pydantic import Field from pydantic import Field
from typing import Optional, List from typing import Optional, List

View File

@ -14,8 +14,9 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .dynamips_nodes import (
from gns3server.schemas.compute.dynamips_nodes import (
DynamipsConsoleType, DynamipsConsoleType,
DynamipsPlatform, DynamipsPlatform,
DynamipsAdapters, DynamipsAdapters,

View File

@ -14,9 +14,8 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import Category, TemplateBase
from .templates import Category, TemplateBase from gns3server.schemas.compute.ethernet_hub_nodes import EthernetHubPort
from .ethernet_hub_nodes import EthernetHubPort
from pydantic import Field from pydantic import Field
from typing import Optional, List from typing import Optional, List

View File

@ -15,8 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .ethernet_switch_nodes import EthernetSwitchPort from gns3server.schemas.compute.ethernet_switch_nodes import EthernetSwitchPort
from pydantic import Field from pydantic import Field
from typing import Optional, List from typing import Optional, List

View File

@ -15,8 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .iou_nodes import ConsoleType from gns3server.schemas.compute.iou_nodes import ConsoleType
from pydantic import Field from pydantic import Field
from typing import Optional from typing import Optional

View File

@ -15,8 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .qemu_nodes import ( from gns3server.schemas.compute.qemu_nodes import (
QemuConsoleType, QemuConsoleType,
QemuPlatform, QemuPlatform,
QemuAdapterType, QemuAdapterType,

View File

@ -14,8 +14,13 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .virtualbox_nodes import VirtualBoxConsoleType, VirtualBoxAdapterType, VirtualBoxOnCloseAction, CustomAdapter from gns3server.schemas.compute.virtualbox_nodes import (
VirtualBoxConsoleType,
VirtualBoxAdapterType,
VirtualBoxOnCloseAction,
CustomAdapter
)
from pydantic import Field from pydantic import Field
from typing import Optional, List from typing import Optional, List

View File

@ -15,8 +15,13 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .vmware_nodes import VMwareConsoleType, VMwareAdapterType, VMwareOnCloseAction, CustomAdapter from gns3server.schemas.compute.vmware_nodes import (
VMwareConsoleType,
VMwareAdapterType,
VMwareOnCloseAction,
CustomAdapter
)
from pydantic import Field from pydantic import Field
from typing import Optional, List from typing import Optional, List

View File

@ -15,8 +15,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .templates import Category, TemplateBase from . import Category, TemplateBase
from .vpcs_nodes import ConsoleType from gns3server.schemas.compute.vpcs_nodes import ConsoleType
from pydantic import Field from pydantic import Field
from typing import Optional from typing import Optional

View File

@ -21,7 +21,7 @@ from passlib.context import CryptContext
from typing import Optional from typing import Optional
from fastapi import HTTPException, status from fastapi import HTTPException, status
from gns3server.schemas.tokens import TokenData from gns3server.schemas.controller.tokens import TokenData
from gns3server.config import Config from gns3server.config import Config
from pydantic import ValidationError from pydantic import ValidationError

View File

@ -344,13 +344,27 @@ def run_around_tests(monkeypatch, config, port_manager):#port_manager, controlle
module._instance = None module._instance = None
config.settings.Controller.jwt_secret_key = DEFAULT_JWT_SECRET_KEY config.settings.Controller.jwt_secret_key = DEFAULT_JWT_SECRET_KEY
config.settings.Server.secrets_dir = os.path.join(tmppath, 'secrets')
os.makedirs(os.path.join(tmppath, 'projects')) secrets_dir = os.path.join(tmppath, 'secrets')
config.settings.Server.projects_path = os.path.join(tmppath, 'projects') os.makedirs(secrets_dir)
config.settings.Server.symbols_path = os.path.join(tmppath, 'symbols') config.settings.Server.secrets_dir = secrets_dir
config.settings.Server.images_path = os.path.join(tmppath, 'images')
config.settings.Server.appliances_path = os.path.join(tmppath, 'appliances') projects_dir = os.path.join(tmppath, 'projects')
os.makedirs(projects_dir)
config.settings.Server.projects_path = projects_dir
symbols_dir = os.path.join(tmppath, 'symbols')
os.makedirs(symbols_dir)
config.settings.Server.symbols_path = symbols_dir
images_dir = os.path.join(tmppath, 'images')
os.makedirs(images_dir)
config.settings.Server.images_path = images_dir
appliances_dir = os.path.join(tmppath, 'appliances')
os.makedirs(appliances_dir)
config.settings.Server.appliances_path = appliances_dir
config.settings.Server.ubridge_path = os.path.join(tmppath, 'bin', 'ubridge') config.settings.Server.ubridge_path = os.path.join(tmppath, 'bin', 'ubridge')
config.settings.Server.local = True config.settings.Server.local = True
config.settings.Server.enable_http_auth = False config.settings.Server.enable_http_auth = False