2015-01-14 00:05:26 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
|
|
|
|
# Copyright (C) 2015 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/>.
|
|
|
|
|
|
2015-02-02 22:36:13 +00:00
|
|
|
|
import sys
|
2015-01-14 00:05:26 +00:00
|
|
|
|
import json
|
2016-07-28 12:59:44 +00:00
|
|
|
|
import urllib
|
2015-01-14 00:05:26 +00:00
|
|
|
|
import asyncio
|
|
|
|
|
import aiohttp
|
2015-02-02 22:36:13 +00:00
|
|
|
|
import traceback
|
2016-07-28 12:59:44 +00:00
|
|
|
|
import jsonschema
|
2018-11-16 16:02:10 +00:00
|
|
|
|
import jsonschema.exceptions
|
2015-01-16 16:09:45 +00:00
|
|
|
|
|
2016-06-07 14:06:37 +00:00
|
|
|
|
from ..compute.error import NodeError, ImageMissingError
|
2016-03-04 15:11:31 +00:00
|
|
|
|
from ..controller.controller_error import ControllerError
|
2015-07-21 23:58:53 +00:00
|
|
|
|
from ..ubridge.ubridge_error import UbridgeError
|
2016-08-24 09:36:32 +00:00
|
|
|
|
from ..controller.gns3vm.gns3_vm_error import GNS3VMError
|
2015-01-14 00:05:26 +00:00
|
|
|
|
from .response import Response
|
2015-02-24 16:40:01 +00:00
|
|
|
|
from ..crash_report import CrashReport
|
2015-03-13 20:43:39 +00:00
|
|
|
|
from ..config import Config
|
2015-01-14 00:05:26 +00:00
|
|
|
|
|
2015-02-12 21:28:12 +00:00
|
|
|
|
|
2019-11-11 04:44:31 +00:00
|
|
|
|
import logging
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
2018-11-17 11:12:46 +00:00
|
|
|
|
async def parse_request(request, input_schema, raw):
|
2015-01-14 00:05:26 +00:00
|
|
|
|
"""Parse body of request and raise HTTP errors in case of problems"""
|
2016-07-25 16:58:34 +00:00
|
|
|
|
|
2017-01-31 14:16:05 +00:00
|
|
|
|
request.json = {}
|
|
|
|
|
if not raw:
|
2018-10-15 10:05:49 +00:00
|
|
|
|
body = await request.read()
|
2017-01-31 14:16:05 +00:00
|
|
|
|
if body:
|
|
|
|
|
try:
|
|
|
|
|
request.json = json.loads(body.decode('utf-8'))
|
|
|
|
|
except ValueError as e:
|
|
|
|
|
request.json = {"malformed_json": body.decode('utf-8')}
|
|
|
|
|
raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))
|
2016-07-25 16:58:34 +00:00
|
|
|
|
|
|
|
|
|
# Parse the query string
|
|
|
|
|
if len(request.query_string) > 0:
|
|
|
|
|
for (k, v) in urllib.parse.parse_qs(request.query_string).items():
|
|
|
|
|
request.json[k] = v[0]
|
|
|
|
|
|
|
|
|
|
if input_schema:
|
|
|
|
|
try:
|
2018-11-17 11:12:46 +00:00
|
|
|
|
jsonschema.validate(request.json, input_schema)
|
2016-07-25 16:58:34 +00:00
|
|
|
|
except jsonschema.ValidationError as e:
|
2018-11-17 11:12:46 +00:00
|
|
|
|
message = "JSON schema error with API request '{}' and JSON data '{}': {}".format(request.path_qs,
|
|
|
|
|
request.json,
|
|
|
|
|
e.message)
|
2018-11-16 16:02:10 +00:00
|
|
|
|
log.error(message)
|
|
|
|
|
log.debug("Input schema: {}".format(json.dumps(input_schema)))
|
|
|
|
|
raise aiohttp.web.HTTPBadRequest(text=message)
|
2016-07-25 16:58:34 +00:00
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
return request
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Route(object):
|
2015-01-20 12:24:00 +00:00
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
""" Decorator adding:
|
|
|
|
|
* json schema verification
|
|
|
|
|
* routing inside handlers
|
|
|
|
|
* documentation information about endpoints
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
_routes = []
|
|
|
|
|
_documentation = {}
|
|
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
|
_node_locks = {}
|
2015-02-24 20:53:38 +00:00
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def get(cls, path, *args, **kw):
|
|
|
|
|
return cls._route('GET', path, *args, **kw)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def post(cls, path, *args, **kw):
|
|
|
|
|
return cls._route('POST', path, *args, **kw)
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def put(cls, path, *args, **kw):
|
|
|
|
|
return cls._route('PUT', path, *args, **kw)
|
|
|
|
|
|
2015-01-16 20:39:58 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def delete(cls, path, *args, **kw):
|
|
|
|
|
return cls._route('DELETE', path, *args, **kw)
|
|
|
|
|
|
2015-06-03 13:38:34 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def authenticate(cls, request, route, server_config):
|
|
|
|
|
"""
|
|
|
|
|
Ask user for authentication
|
|
|
|
|
|
|
|
|
|
:returns: Response if you need to auth the user otherwise None
|
|
|
|
|
"""
|
2018-12-03 10:46:24 +00:00
|
|
|
|
|
2020-01-31 10:30:26 +00:00
|
|
|
|
# FIXME: ugly exception to not require authentication for websocket consoles
|
|
|
|
|
if not server_config.getboolean("auth", False) or request.path.endswith("console/ws"):
|
2018-12-03 10:46:24 +00:00
|
|
|
|
return None
|
2015-06-10 21:14:18 +00:00
|
|
|
|
|
2015-06-03 13:38:34 +00:00
|
|
|
|
user = server_config.get("user", "").strip()
|
|
|
|
|
password = server_config.get("password", "").strip()
|
|
|
|
|
|
2019-10-09 07:56:20 +00:00
|
|
|
|
if user and "AUTHORIZATION" in request.headers:
|
2017-03-27 08:38:41 +00:00
|
|
|
|
if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
|
2018-12-03 10:46:24 +00:00
|
|
|
|
return None
|
2015-06-03 13:38:34 +00:00
|
|
|
|
|
2019-10-09 07:56:20 +00:00
|
|
|
|
if not user:
|
|
|
|
|
log.error("HTTP authentication is enabled but no username is configured")
|
|
|
|
|
else:
|
2019-10-09 08:35:42 +00:00
|
|
|
|
log.error("Invalid HTTP authentication for username '{}'".format(user))
|
2015-08-27 14:06:11 +00:00
|
|
|
|
|
2015-06-03 13:38:34 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
|
|
|
|
response.set_status(401)
|
|
|
|
|
response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
|
2015-09-16 13:52:13 +00:00
|
|
|
|
# Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
|
|
|
|
|
# this happen only for the first query send by the client.
|
|
|
|
|
response.force_close()
|
2015-06-03 13:38:34 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
@classmethod
|
|
|
|
|
def _route(cls, method, path, *args, **kw):
|
|
|
|
|
# This block is executed only the first time
|
|
|
|
|
output_schema = kw.get("output", {})
|
|
|
|
|
input_schema = kw.get("input", {})
|
2016-03-07 16:57:12 +00:00
|
|
|
|
api_version = kw.get("api_version", 2)
|
2015-04-24 08:15:23 +00:00
|
|
|
|
raw = kw.get("raw", False)
|
2015-02-23 16:21:39 +00:00
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
def register(func):
|
2016-03-07 14:01:35 +00:00
|
|
|
|
# Add the type of server to the route
|
|
|
|
|
if "controller" in func.__module__:
|
2016-03-11 16:16:09 +00:00
|
|
|
|
route = "/v{version}{path}".format(path=path, version=api_version)
|
2016-04-15 15:57:06 +00:00
|
|
|
|
elif "compute" in func.__module__:
|
|
|
|
|
route = "/v{version}/compute{path}".format(path=path, version=api_version)
|
2016-03-07 14:01:35 +00:00
|
|
|
|
else:
|
|
|
|
|
route = path
|
|
|
|
|
|
|
|
|
|
# Compute metadata for the documentation
|
|
|
|
|
if api_version:
|
|
|
|
|
handler = func.__module__.replace("_handler", "").replace("gns3server.handlers.api.", "")
|
|
|
|
|
cls._documentation.setdefault(handler, {})
|
|
|
|
|
cls._documentation[handler].setdefault(route, {"api_version": api_version,
|
|
|
|
|
"controller": kw.get("controller", False),
|
|
|
|
|
"methods": []})
|
|
|
|
|
|
|
|
|
|
cls._documentation[handler][route]["methods"].append({
|
|
|
|
|
"method": method,
|
|
|
|
|
"status_codes": kw.get("status_codes", {200: "OK"}),
|
|
|
|
|
"parameters": kw.get("parameters", {}),
|
|
|
|
|
"output_schema": output_schema,
|
|
|
|
|
"input_schema": input_schema,
|
|
|
|
|
"description": kw.get("description", ""),
|
|
|
|
|
})
|
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
func = asyncio.coroutine(func)
|
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
|
async def control_schema(request):
|
2015-01-14 00:05:26 +00:00
|
|
|
|
# This block is executed at each method call
|
2015-06-03 13:38:34 +00:00
|
|
|
|
server_config = Config.instance().get_section_config("Server")
|
|
|
|
|
|
|
|
|
|
# Authenticate
|
|
|
|
|
response = cls.authenticate(request, route, server_config)
|
2018-12-03 10:46:24 +00:00
|
|
|
|
if response is not None:
|
2015-06-03 13:38:34 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2016-07-20 15:17:42 +00:00
|
|
|
|
try:
|
|
|
|
|
# Non API call
|
|
|
|
|
if api_version is None or raw is True:
|
|
|
|
|
response = Response(request=request, route=route, output_schema=output_schema)
|
2015-04-24 08:15:23 +00:00
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
|
request = await parse_request(request, None, raw)
|
|
|
|
|
await func(request, response)
|
2016-07-20 15:17:42 +00:00
|
|
|
|
return response
|
2015-02-23 16:21:39 +00:00
|
|
|
|
|
2016-07-20 15:17:42 +00:00
|
|
|
|
# API call
|
2018-11-17 11:12:46 +00:00
|
|
|
|
request = await parse_request(request, input_schema, raw)
|
2015-03-13 20:43:39 +00:00
|
|
|
|
record_file = server_config.get("record")
|
|
|
|
|
if record_file:
|
|
|
|
|
try:
|
2015-04-25 17:58:34 +00:00
|
|
|
|
with open(record_file, "a", encoding="utf-8") as f:
|
2015-03-13 20:43:39 +00:00
|
|
|
|
f.write("curl -X {} 'http://{}{}' -d '{}'".format(request.method, request.host, request.path_qs, json.dumps(request.json)))
|
|
|
|
|
f.write("\n")
|
|
|
|
|
except OSError as e:
|
2018-03-15 07:17:39 +00:00
|
|
|
|
log.warning("Could not write to the record file {}: {}".format(record_file, e))
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route, output_schema=output_schema)
|
2018-10-15 10:05:49 +00:00
|
|
|
|
await func(request, response)
|
2015-04-09 08:22:25 +00:00
|
|
|
|
except aiohttp.web.HTTPBadRequest as e:
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-04-09 08:22:25 +00:00
|
|
|
|
response.set_status(e.status)
|
2016-07-04 13:00:46 +00:00
|
|
|
|
response.json({"message": e.text, "status": e.status, "path": route, "request": request.json, "method": request.method})
|
2020-05-06 07:01:18 +00:00
|
|
|
|
except aiohttp.web.HTTPFound as e:
|
|
|
|
|
response = Response(request=request, route=route)
|
|
|
|
|
response.set_status(e.status)
|
|
|
|
|
raise # must raise to let aiohttp know about the redirection
|
2015-01-14 00:05:26 +00:00
|
|
|
|
except aiohttp.web.HTTPException as e:
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-01-14 00:05:26 +00:00
|
|
|
|
response.set_status(e.status)
|
|
|
|
|
response.json({"message": e.text, "status": e.status})
|
2016-08-11 21:58:29 +00:00
|
|
|
|
except (ControllerError, GNS3VMError) as e:
|
2016-03-04 15:11:31 +00:00
|
|
|
|
log.error("Controller error detected: {type}".format(type=type(e)), exc_info=1)
|
|
|
|
|
response = Response(request=request, route=route)
|
|
|
|
|
response.set_status(409)
|
|
|
|
|
response.json({"message": str(e), "status": 409})
|
2016-06-07 17:38:01 +00:00
|
|
|
|
except (NodeError, UbridgeError) as e:
|
2016-06-07 14:06:37 +00:00
|
|
|
|
log.error("Node error detected: {type}".format(type=e.__class__.__name__), exc_info=1)
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-02-19 00:48:02 +00:00
|
|
|
|
response.set_status(409)
|
2016-06-07 14:06:37 +00:00
|
|
|
|
response.json({"message": str(e), "status": 409, "exception": e.__class__.__name__})
|
2017-09-06 11:12:22 +00:00
|
|
|
|
except ImageMissingError as e:
|
2016-06-07 17:38:01 +00:00
|
|
|
|
log.error("Image missing error detected: {}".format(e.image))
|
|
|
|
|
response = Response(request=request, route=route)
|
|
|
|
|
response.set_status(409)
|
|
|
|
|
response.json({"message": str(e), "status": 409, "image": e.image, "exception": e.__class__.__name__})
|
2019-11-11 04:44:31 +00:00
|
|
|
|
except asyncio.CancelledError:
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-02-25 10:42:02 +00:00
|
|
|
|
response.set_status(408)
|
|
|
|
|
response.json({"message": "Request canceled", "status": 408})
|
2018-12-03 11:14:22 +00:00
|
|
|
|
raise # must raise to let aiohttp know the connection has been closed
|
2017-05-16 17:28:47 +00:00
|
|
|
|
except aiohttp.ClientError:
|
2018-03-15 07:17:39 +00:00
|
|
|
|
log.warning("Client error")
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-03-31 20:05:50 +00:00
|
|
|
|
response.set_status(408)
|
2017-05-16 17:28:47 +00:00
|
|
|
|
response.json({"message": "Client error", "status": 408})
|
2018-09-06 07:49:12 +00:00
|
|
|
|
except MemoryError:
|
|
|
|
|
log.error("Memory error detected, server has run out of memory!", exc_info=1)
|
|
|
|
|
response = Response(request=request, route=route)
|
|
|
|
|
response.set_status(500)
|
|
|
|
|
response.json({"message": "Memory error", "status": 500})
|
2015-02-02 22:36:13 +00:00
|
|
|
|
except Exception as e:
|
|
|
|
|
log.error("Uncaught exception detected: {type}".format(type=type(e)), exc_info=1)
|
2015-04-23 12:31:36 +00:00
|
|
|
|
response = Response(request=request, route=route)
|
2015-02-02 22:36:13 +00:00
|
|
|
|
response.set_status(500)
|
2020-05-21 08:49:19 +00:00
|
|
|
|
CrashReport.instance().capture_exception(request)
|
2015-02-02 22:36:13 +00:00
|
|
|
|
exc_type, exc_value, exc_tb = sys.exc_info()
|
|
|
|
|
lines = traceback.format_exception(exc_type, exc_value, exc_tb)
|
2015-02-23 10:27:07 +00:00
|
|
|
|
if api_version is not None:
|
|
|
|
|
tb = "".join(lines)
|
|
|
|
|
response.json({"message": tb, "status": 500})
|
|
|
|
|
else:
|
|
|
|
|
tb = "\n".join(lines)
|
|
|
|
|
response.html("<h1>Internal error</h1><pre>{}</pre>".format(tb))
|
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
|
async def node_concurrency(request):
|
2015-02-24 20:53:38 +00:00
|
|
|
|
"""
|
|
|
|
|
To avoid strange effect we prevent concurrency
|
2016-05-11 17:35:36 +00:00
|
|
|
|
between the same instance of the node
|
2020-01-31 09:31:27 +00:00
|
|
|
|
(excepting when streaming a PCAP file and WebSocket consoles).
|
2015-02-24 20:53:38 +00:00
|
|
|
|
"""
|
|
|
|
|
|
2020-01-31 09:31:27 +00:00
|
|
|
|
#FIXME: ugly exceptions for capture and websocket console
|
2020-01-31 10:30:26 +00:00
|
|
|
|
if "node_id" in request.match_info and not "pcap" in request.path and not request.path.endswith("console/ws"):
|
2016-05-11 17:35:36 +00:00
|
|
|
|
node_id = request.match_info.get("node_id")
|
2015-02-25 10:19:16 +00:00
|
|
|
|
|
2016-04-15 15:57:06 +00:00
|
|
|
|
if "compute" in request.path:
|
2016-04-14 10:15:45 +00:00
|
|
|
|
type = "compute"
|
2016-04-14 10:22:10 +00:00
|
|
|
|
else:
|
|
|
|
|
type = "controller"
|
2016-05-11 17:35:36 +00:00
|
|
|
|
lock_key = "{}:{}:{}".format(type, request.match_info["project_id"], node_id)
|
|
|
|
|
cls._node_locks.setdefault(lock_key, {"lock": asyncio.Lock(), "concurrency": 0})
|
|
|
|
|
cls._node_locks[lock_key]["concurrency"] += 1
|
2016-04-14 10:15:45 +00:00
|
|
|
|
|
2018-10-15 10:05:49 +00:00
|
|
|
|
async with cls._node_locks[lock_key]["lock"]:
|
|
|
|
|
response = await control_schema(request)
|
2016-05-11 17:35:36 +00:00
|
|
|
|
cls._node_locks[lock_key]["concurrency"] -= 1
|
2015-02-25 10:19:16 +00:00
|
|
|
|
|
|
|
|
|
# No more waiting requests, garbage collect the lock
|
2016-05-11 17:35:36 +00:00
|
|
|
|
if cls._node_locks[lock_key]["concurrency"] <= 0:
|
|
|
|
|
del cls._node_locks[lock_key]
|
2015-02-24 22:26:03 +00:00
|
|
|
|
else:
|
2018-10-15 10:05:49 +00:00
|
|
|
|
response = await control_schema(request)
|
2015-02-24 20:53:38 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
|
cls._routes.append((method, route, node_concurrency))
|
2015-01-14 00:05:26 +00:00
|
|
|
|
|
2016-05-11 17:35:36 +00:00
|
|
|
|
return node_concurrency
|
2015-01-14 00:05:26 +00:00
|
|
|
|
return register
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_routes(cls):
|
|
|
|
|
return cls._routes
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def get_documentation(cls):
|
|
|
|
|
return cls._documentation
|