gns3-server/gns3server/api/routes/controller/links.py

208 lines
6.4 KiB
Python
Raw Normal View History

2020-10-02 06:37:50 +00:00
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# 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
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
API routes for links.
2020-10-02 06:37:50 +00:00
"""
import multidict
import aiohttp
from fastapi import APIRouter, Depends, Request, status
2020-10-02 06:37:50 +00:00
from fastapi.responses import StreamingResponse
from fastapi.encoders import jsonable_encoder
2020-10-02 06:37:50 +00:00
from typing import List
from uuid import UUID
from gns3server.controller import Controller
from gns3server.controller.controller_error import ControllerError
from gns3server.controller.link import Link
from gns3server.utils.http_client import HTTPClient
2020-10-31 05:32:21 +00:00
from gns3server import schemas
2020-10-02 06:37:50 +00:00
import logging
log = logging.getLogger(__name__)
responses = {
2020-10-31 05:32:21 +00:00
404: {"model": schemas.ErrorMessage, "description": "Could not find project or link"}
}
2020-10-02 06:37:50 +00:00
2021-04-13 06:49:56 +00:00
router = APIRouter(responses=responses)
async def dep_link(project_id: UUID, link_id: UUID):
"""
Dependency to retrieve a link.
"""
project = await Controller.instance().get_loaded_project(str(project_id))
link = project.get_link(str(link_id))
return link
2020-10-02 06:37:50 +00:00
@router.get("",
response_model=List[schemas.Link],
2020-10-02 06:37:50 +00:00
response_model_exclude_unset=True)
async def get_links(project_id: UUID):
"""
Return all links for a given project.
"""
2020-10-02 06:37:50 +00:00
project = await Controller.instance().get_loaded_project(str(project_id))
return [v.__json__() for v in project.links.values()]
@router.post("",
2020-10-02 06:37:50 +00:00
status_code=status.HTTP_201_CREATED,
response_model=schemas.Link,
2020-10-31 05:32:21 +00:00
responses={404: {"model": schemas.ErrorMessage, "description": "Could not find project"},
409: {"model": schemas.ErrorMessage, "description": "Could not create link"}})
async def create_link(project_id: UUID, link_data: schemas.Link):
2020-10-02 06:37:50 +00:00
"""
Create a new link.
2020-10-02 06:37:50 +00:00
"""
project = await Controller.instance().get_loaded_project(str(project_id))
link = await project.add_link()
link_data = jsonable_encoder(link_data, exclude_unset=True)
if "filters" in link_data:
await link.update_filters(link_data["filters"])
if "suspend" in link_data:
await link.update_suspend(link_data["suspend"])
try:
for node in link_data["nodes"]:
await link.add_node(project.get_node(node["node_id"]),
node.get("adapter_number", 0),
node.get("port_number", 0),
label=node.get("label"))
except ControllerError as e:
await project.delete_link(link.id)
raise e
return link.__json__()
2021-04-13 06:49:56 +00:00
@router.get("/{link_id}/available_filters")
async def get_filters(link: Link = Depends(dep_link)):
2020-10-02 06:37:50 +00:00
"""
Return all filters available for a given link.
2020-10-02 06:37:50 +00:00
"""
return link.available_filters()
@router.get("/{link_id}",
response_model=schemas.Link,
2021-04-13 06:49:56 +00:00
response_model_exclude_unset=True)
async def get_link(link: Link = Depends(dep_link)):
"""
Return a link.
"""
2020-10-02 06:37:50 +00:00
return link.__json__()
@router.put("/{link_id}",
response_model=schemas.Link,
2021-04-13 06:49:56 +00:00
response_model_exclude_unset=True)
async def update_link(link_data: schemas.Link, link: Link = Depends(dep_link)):
"""
Update a link.
"""
2020-10-02 06:37:50 +00:00
link_data = jsonable_encoder(link_data, exclude_unset=True)
if "filters" in link_data:
await link.update_filters(link_data["filters"])
if "suspend" in link_data:
await link.update_suspend(link_data["suspend"])
if "nodes" in link_data:
await link.update_nodes(link_data["nodes"])
return link.__json__()
@router.delete("/{link_id}",
2021-04-13 06:49:56 +00:00
status_code=status.HTTP_204_NO_CONTENT)
async def delete_link(project_id: UUID, link: Link = Depends(dep_link)):
2020-10-02 06:37:50 +00:00
"""
Delete a link.
2020-10-02 06:37:50 +00:00
"""
project = await Controller.instance().get_loaded_project(str(project_id))
await project.delete_link(link.id)
2020-10-02 06:37:50 +00:00
@router.post("/{link_id}/reset",
2021-04-13 06:49:56 +00:00
response_model=schemas.Link)
async def reset_link(link: Link = Depends(dep_link)):
"""
Reset a link.
"""
2020-10-02 06:37:50 +00:00
await link.reset()
return link.__json__()
@router.post("/{link_id}/capture/start",
status_code=status.HTTP_201_CREATED,
2021-04-13 06:49:56 +00:00
response_model=schemas.Link)
async def start_capture(capture_data: dict, link: Link = Depends(dep_link)):
"""
Start packet capture on the link.
"""
await link.start_capture(data_link_type=capture_data.get("data_link_type", "DLT_EN10MB"),
capture_file_name=capture_data.get("capture_file_name"))
return link.__json__()
@router.post("/{link_id}/capture/stop",
2021-04-13 06:49:56 +00:00
status_code=status.HTTP_204_NO_CONTENT)
async def stop_capture(link: Link = Depends(dep_link)):
"""
Stop packet capture on the link.
"""
await link.stop_capture()
2021-04-13 06:49:56 +00:00
@router.get("/{link_id}/capture/stream")
async def stream_pcap(request: Request, link: Link = Depends(dep_link)):
"""
Stream the PCAP capture file from compute.
"""
if not link.capturing:
raise ControllerError("This link has no active packet capture")
compute = link.compute
pcap_streaming_url = link.pcap_streaming_url()
headers = multidict.MultiDict(request.headers)
headers['Host'] = compute.host
headers['Router-Host'] = request.client.host
body = await request.body()
2020-10-19 07:58:01 +00:00
async def compute_pcap_stream():
try:
async with HTTPClient.request(request.method, pcap_streaming_url, timeout=None, data=body) as response:
async for data in response.content.iter_any():
if not data:
break
yield data
except aiohttp.ClientError as e:
raise ControllerError(f"Client error received when receiving pcap stream from compute: {e}")
2020-10-19 07:58:01 +00:00
return StreamingResponse(compute_pcap_stream(), media_type="application/vnd.tcpdump.pcap")