2013-10-30 21:58:17 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2015-01-14 00:05:26 +00:00
|
|
|
# Copyright (C) 2015 GNS3 Technologies Inc.
|
2013-10-30 21:58:17 +00:00
|
|
|
#
|
|
|
|
# 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/>.
|
|
|
|
|
2013-12-06 04:39:27 +00:00
|
|
|
"""
|
2014-03-11 21:45:04 +00:00
|
|
|
Set up and run the server.
|
2013-12-06 04:39:27 +00:00
|
|
|
"""
|
|
|
|
|
2013-12-05 07:21:06 +00:00
|
|
|
import os
|
2015-01-14 00:05:26 +00:00
|
|
|
import sys
|
2013-12-07 00:52:16 +00:00
|
|
|
import signal
|
2016-06-13 21:07:20 +00:00
|
|
|
import socket
|
2016-06-15 23:37:43 +00:00
|
|
|
import json
|
2016-06-13 21:07:20 +00:00
|
|
|
import ipaddress
|
2015-01-14 00:05:26 +00:00
|
|
|
import asyncio
|
2016-06-16 17:17:12 +00:00
|
|
|
import threading
|
2015-01-14 00:05:26 +00:00
|
|
|
import aiohttp
|
2016-05-17 10:39:23 +00:00
|
|
|
import aiohttp_cors
|
2015-01-14 00:05:26 +00:00
|
|
|
import functools
|
|
|
|
import time
|
2015-05-05 09:33:47 +00:00
|
|
|
import atexit
|
2014-04-11 01:42:26 +00:00
|
|
|
|
2016-03-03 15:02:27 +00:00
|
|
|
from .route import Route
|
|
|
|
from .request_handler import RequestHandler
|
|
|
|
from ..config import Config
|
2016-04-15 15:57:06 +00:00
|
|
|
from ..compute import MODULES
|
|
|
|
from ..compute.port_manager import PortManager
|
2016-04-19 13:35:50 +00:00
|
|
|
from ..controller import Controller
|
2016-06-15 23:37:43 +00:00
|
|
|
from ..version import __version__
|
2016-04-19 13:35:50 +00:00
|
|
|
|
2013-10-30 21:58:17 +00:00
|
|
|
|
2015-02-27 02:31:18 +00:00
|
|
|
# do not delete this import
|
|
|
|
import gns3server.handlers
|
2015-01-14 00:05:26 +00:00
|
|
|
|
2013-12-05 07:21:06 +00:00
|
|
|
import logging
|
|
|
|
log = logging.getLogger(__name__)
|
2013-10-30 21:58:17 +00:00
|
|
|
|
2014-09-29 21:56:01 +00:00
|
|
|
|
2016-03-03 15:02:27 +00:00
|
|
|
class WebServer:
|
2013-10-30 21:58:17 +00:00
|
|
|
|
2016-06-15 23:37:43 +00:00
|
|
|
def __init__(self, host, port):
|
2013-10-30 21:58:17 +00:00
|
|
|
|
2013-12-05 07:21:06 +00:00
|
|
|
self._host = host
|
|
|
|
self._port = port
|
2015-01-14 00:05:26 +00:00
|
|
|
self._loop = None
|
2015-03-13 00:44:05 +00:00
|
|
|
self._handler = None
|
2015-01-14 00:05:26 +00:00
|
|
|
self._start_time = time.time()
|
2015-01-23 20:01:23 +00:00
|
|
|
self._port_manager = PortManager(host)
|
2016-06-15 23:37:43 +00:00
|
|
|
self._running = False
|
2014-11-10 06:01:13 +00:00
|
|
|
|
2015-03-13 00:44:05 +00:00
|
|
|
@staticmethod
|
2016-06-15 23:37:43 +00:00
|
|
|
def instance(host=None, port=None):
|
2015-03-13 00:44:05 +00:00
|
|
|
"""
|
|
|
|
Singleton to return only one instance of Server.
|
|
|
|
|
|
|
|
:returns: instance of Server
|
|
|
|
"""
|
|
|
|
|
2016-03-03 15:02:27 +00:00
|
|
|
if not hasattr(WebServer, "_instance") or WebServer._instance is None:
|
2015-03-13 00:50:38 +00:00
|
|
|
assert host is not None
|
|
|
|
assert port is not None
|
2016-06-15 23:37:43 +00:00
|
|
|
WebServer._instance = WebServer(host, port)
|
2016-03-03 15:02:27 +00:00
|
|
|
return WebServer._instance
|
2015-03-13 00:44:05 +00:00
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
@asyncio.coroutine
|
2015-02-22 19:36:44 +00:00
|
|
|
def _run_application(self, handler, ssl_context=None):
|
2015-01-14 00:05:26 +00:00
|
|
|
|
2015-02-01 22:56:10 +00:00
|
|
|
try:
|
2015-02-22 19:36:44 +00:00
|
|
|
server = yield from self._loop.create_server(handler, self._host, self._port, ssl=ssl_context)
|
2015-02-01 22:56:10 +00:00
|
|
|
except OSError as e:
|
|
|
|
log.critical("Could not start the server: {}".format(e))
|
|
|
|
self._loop.stop()
|
|
|
|
return
|
2015-01-14 00:05:26 +00:00
|
|
|
return server
|
|
|
|
|
2015-02-03 00:01:25 +00:00
|
|
|
@asyncio.coroutine
|
2015-03-13 00:44:05 +00:00
|
|
|
def shutdown_server(self):
|
2013-12-06 04:39:27 +00:00
|
|
|
"""
|
2015-03-13 00:44:05 +00:00
|
|
|
Cleanly shutdown the server.
|
2013-10-30 21:58:17 +00:00
|
|
|
"""
|
|
|
|
|
2015-03-13 00:44:05 +00:00
|
|
|
if self._handler:
|
2015-07-22 00:00:03 +00:00
|
|
|
yield from self._handler.finish_connections()
|
2015-07-20 22:02:28 +00:00
|
|
|
self._handler = None
|
2015-03-13 00:44:05 +00:00
|
|
|
|
2016-06-02 11:44:12 +00:00
|
|
|
if Config.instance().get_section_config("Server").getboolean("controller"):
|
|
|
|
yield from Controller.instance().close()
|
|
|
|
|
2015-01-22 10:49:22 +00:00
|
|
|
for module in MODULES:
|
|
|
|
log.debug("Unloading module {}".format(module.__name__))
|
|
|
|
m = module.instance()
|
2015-02-03 00:01:25 +00:00
|
|
|
yield from m.unload()
|
2015-02-24 00:42:55 +00:00
|
|
|
|
|
|
|
if self._port_manager.tcp_ports:
|
|
|
|
log.warning("TCP ports are still used {}".format(self._port_manager.tcp_ports))
|
|
|
|
|
|
|
|
if self._port_manager.udp_ports:
|
|
|
|
log.warning("UDP ports are still used {}".format(self._port_manager.udp_ports))
|
|
|
|
|
2015-10-16 18:42:13 +00:00
|
|
|
for task in asyncio.Task.all_tasks():
|
|
|
|
task.cancel()
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
self._loop.stop()
|
2014-03-16 03:41:04 +00:00
|
|
|
|
2015-03-13 00:44:05 +00:00
|
|
|
def _signal_handling(self):
|
2014-05-08 01:31:53 +00:00
|
|
|
|
2016-05-30 13:28:53 +00:00
|
|
|
def signal_handler(signame, *args):
|
2015-01-20 13:59:19 +00:00
|
|
|
log.warning("Server has got signal {}, exiting...".format(signame))
|
2015-10-12 14:16:44 +00:00
|
|
|
asyncio.async(self.shutdown_server())
|
2015-01-14 00:05:26 +00:00
|
|
|
|
|
|
|
signals = ["SIGTERM", "SIGINT"]
|
|
|
|
if sys.platform.startswith("win"):
|
|
|
|
signals.extend(["SIGBREAK"])
|
|
|
|
else:
|
|
|
|
signals.extend(["SIGHUP", "SIGQUIT"])
|
2014-03-16 03:41:04 +00:00
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
for signal_name in signals:
|
2015-10-12 14:16:44 +00:00
|
|
|
callback = functools.partial(signal_handler, signal_name)
|
2015-01-14 00:05:26 +00:00
|
|
|
if sys.platform.startswith("win"):
|
|
|
|
# add_signal_handler() is not yet supported on Windows
|
|
|
|
signal.signal(getattr(signal, signal_name), callback)
|
|
|
|
else:
|
|
|
|
self._loop.add_signal_handler(getattr(signal, signal_name), callback)
|
|
|
|
|
2015-01-24 19:11:51 +00:00
|
|
|
def _create_ssl_context(self, server_config):
|
|
|
|
|
|
|
|
import ssl
|
|
|
|
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
|
|
|
|
certfile = server_config["certfile"]
|
|
|
|
certkey = server_config["certkey"]
|
|
|
|
try:
|
|
|
|
ssl_context.load_cert_chain(certfile, certkey)
|
|
|
|
except FileNotFoundError:
|
|
|
|
log.critical("Could not find the SSL certfile or certkey")
|
|
|
|
raise SystemExit
|
|
|
|
except ssl.SSLError as e:
|
|
|
|
log.critical("SSL error: {}".format(e))
|
|
|
|
raise SystemExit
|
2015-06-11 15:07:13 +00:00
|
|
|
log.info("SSL is enabled")
|
2015-01-24 19:11:51 +00:00
|
|
|
return ssl_context
|
|
|
|
|
2015-02-20 21:40:20 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def start_shell(self):
|
2015-02-24 00:08:34 +00:00
|
|
|
try:
|
|
|
|
from ptpython.repl import embed
|
|
|
|
except ImportError:
|
|
|
|
log.error("Unable to start a shell: the ptpython module must be installed!")
|
|
|
|
return
|
2015-02-20 21:40:20 +00:00
|
|
|
yield from embed(globals(), locals(), return_asyncio_coroutine=True, patch_stdout=True)
|
|
|
|
|
2015-05-05 09:33:47 +00:00
|
|
|
def _exit_handling(self):
|
2015-07-20 22:02:28 +00:00
|
|
|
"""
|
|
|
|
Makes sure the asyncio loop is closed.
|
|
|
|
"""
|
|
|
|
|
2015-05-05 09:33:47 +00:00
|
|
|
def close_asyncio_loop():
|
|
|
|
loop = None
|
|
|
|
try:
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
if loop is not None:
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
atexit.register(close_asyncio_loop)
|
|
|
|
|
2016-06-15 23:37:43 +00:00
|
|
|
def _udp_server_discovery(self):
|
2016-06-13 21:07:20 +00:00
|
|
|
"""
|
2016-06-15 23:37:43 +00:00
|
|
|
UDP multicast and broadcast server discovery (Linux only)
|
2016-06-13 21:07:20 +00:00
|
|
|
"""
|
|
|
|
|
2016-06-15 23:37:43 +00:00
|
|
|
import ctypes
|
|
|
|
uint32_t = ctypes.c_uint32
|
|
|
|
in_addr_t = uint32_t
|
|
|
|
|
|
|
|
class in_addr(ctypes.Structure):
|
|
|
|
_fields_ = [('s_addr', in_addr_t)]
|
|
|
|
|
|
|
|
class in_pktinfo(ctypes.Structure):
|
|
|
|
_fields_ = [('ipi_ifindex', ctypes.c_int),
|
|
|
|
('ipi_spec_dst', in_addr),
|
|
|
|
('ipi_addr', in_addr)]
|
|
|
|
|
|
|
|
IP_PKTINFO = 8
|
2016-06-16 17:17:12 +00:00
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
|
|
|
membership = socket.inet_aton("239.42.42.1") + socket.inet_aton("0.0.0.0")
|
|
|
|
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
|
|
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
|
|
sock.setsockopt(socket.SOL_IP, IP_PKTINFO, 1)
|
|
|
|
try:
|
|
|
|
sock.bind(("", self._port))
|
|
|
|
except OSError as e:
|
|
|
|
log.error("UDP server discovery could not bind on port {}: {}".format(self._port, e))
|
|
|
|
return
|
|
|
|
|
|
|
|
log.info("UDP server discovery started on port {}".format(self._port))
|
|
|
|
while self._loop.is_running():
|
|
|
|
try:
|
|
|
|
data, ancdata, _, address = sock.recvmsg(255, socket.CMSG_LEN(255))
|
|
|
|
except OSError as e:
|
|
|
|
log.error("Error while receiving UDP server discovery request: {}".format(e))
|
|
|
|
continue
|
2016-06-15 23:37:43 +00:00
|
|
|
cmsg_level, cmsg_type, cmsg_data = ancdata[0]
|
|
|
|
if cmsg_level == socket.SOL_IP and cmsg_type == IP_PKTINFO:
|
|
|
|
pktinfo = in_pktinfo.from_buffer_copy(cmsg_data)
|
|
|
|
request_address = ipaddress.IPv4Address(memoryview(pktinfo.ipi_addr).tobytes())
|
2016-06-16 17:17:12 +00:00
|
|
|
receiving_interface = socket.if_indextoname(pktinfo.ipi_ifindex)
|
|
|
|
log.debug("UDP server discovery request received on {} using {}".format(receiving_interface,
|
2016-06-15 23:37:43 +00:00
|
|
|
request_address))
|
|
|
|
local_address = ipaddress.IPv4Address(memoryview(pktinfo.ipi_spec_dst).tobytes())
|
2016-06-16 17:17:12 +00:00
|
|
|
if self._host != "0.0.0.0" and self._host != str(local_address):
|
|
|
|
log.debug("Ignoring UDP discovery request received on {} instead of {}".format(local_address,
|
|
|
|
self._host))
|
|
|
|
continue
|
2016-06-15 23:37:43 +00:00
|
|
|
server_info = {"version": __version__,
|
|
|
|
"ip": str(local_address),
|
|
|
|
"port": self._port}
|
|
|
|
data = json.dumps(server_info)
|
|
|
|
sock.sendto(data.encode(), address)
|
2016-06-16 17:17:12 +00:00
|
|
|
log.debug("Sent server info to {}:{} {}".format(address[0], address[1], data))
|
2016-06-15 23:37:43 +00:00
|
|
|
time.sleep(1) # this is to prevent too many request to slow down the server
|
2016-06-16 17:17:12 +00:00
|
|
|
log.debug("UDP server discovery stopped")
|
2016-06-13 21:07:20 +00:00
|
|
|
|
2013-10-30 21:58:17 +00:00
|
|
|
def run(self):
|
2013-12-05 07:21:06 +00:00
|
|
|
"""
|
2015-01-14 00:05:26 +00:00
|
|
|
Starts the server.
|
2013-10-30 21:58:17 +00:00
|
|
|
"""
|
|
|
|
|
2015-01-20 22:28:40 +00:00
|
|
|
logger = logging.getLogger("asyncio")
|
2015-10-14 16:10:05 +00:00
|
|
|
logger.setLevel(logging.ERROR)
|
2015-01-20 22:28:40 +00:00
|
|
|
|
2015-01-23 04:11:57 +00:00
|
|
|
if sys.platform.startswith("win"):
|
2016-05-30 13:18:49 +00:00
|
|
|
loop = asyncio.get_event_loop()
|
2015-02-27 19:51:39 +00:00
|
|
|
# Add a periodic callback to give a chance to process signals on Windows
|
|
|
|
# because asyncio.add_signal_handler() is not supported yet on that platform
|
|
|
|
# otherwise the loop runs outside of signal module's ability to trap signals.
|
2016-06-02 11:44:12 +00:00
|
|
|
|
2015-02-27 19:51:39 +00:00
|
|
|
def wakeup():
|
2015-03-14 00:57:27 +00:00
|
|
|
loop.call_later(0.5, wakeup)
|
|
|
|
loop.call_later(0.5, wakeup)
|
2015-02-27 19:51:39 +00:00
|
|
|
asyncio.set_event_loop(loop)
|
2015-01-23 04:11:57 +00:00
|
|
|
|
2016-05-30 13:18:49 +00:00
|
|
|
server_config = Config.instance().get_section_config("Server")
|
|
|
|
|
2015-01-24 19:11:51 +00:00
|
|
|
ssl_context = None
|
|
|
|
if server_config.getboolean("ssl"):
|
|
|
|
if sys.platform.startswith("win"):
|
|
|
|
log.critical("SSL mode is not supported on Windows")
|
|
|
|
raise SystemExit
|
|
|
|
ssl_context = self._create_ssl_context(server_config)
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
self._loop = asyncio.get_event_loop()
|
2015-10-12 14:26:07 +00:00
|
|
|
# Asyncio will raise error if coroutine is not called
|
|
|
|
self._loop.set_debug(True)
|
|
|
|
|
2016-04-19 13:35:50 +00:00
|
|
|
if server_config.getboolean("controller"):
|
|
|
|
asyncio.async(Controller.instance().load())
|
|
|
|
|
2016-01-15 09:11:32 +00:00
|
|
|
for key, val in os.environ.items():
|
|
|
|
log.debug("ENV %s=%s", key, val)
|
|
|
|
|
2015-01-14 00:05:26 +00:00
|
|
|
app = aiohttp.web.Application()
|
2016-05-17 10:39:23 +00:00
|
|
|
# Allow CORS for this domains
|
|
|
|
cors = aiohttp_cors.setup(app, defaults={
|
|
|
|
# Default web server for web gui dev
|
2016-05-25 09:36:39 +00:00
|
|
|
"http://127.0.0.1:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
|
2016-05-17 15:51:22 +00:00
|
|
|
"http://localhost:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
|
|
|
|
"http://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*")
|
2016-05-17 10:39:23 +00:00
|
|
|
})
|
2015-01-14 00:05:26 +00:00
|
|
|
for method, route, handler in Route.get_routes():
|
2015-01-20 13:59:19 +00:00
|
|
|
log.debug("Adding route: {} {}".format(method, route))
|
2016-05-17 10:39:23 +00:00
|
|
|
cors.add(app.router.add_route(method, route, handler))
|
2015-01-14 00:05:26 +00:00
|
|
|
for module in MODULES:
|
2015-01-20 13:59:19 +00:00
|
|
|
log.debug("Loading module {}".format(module.__name__))
|
2015-01-15 15:59:01 +00:00
|
|
|
m = module.instance()
|
|
|
|
m.port_manager = self._port_manager
|
2013-12-07 00:52:16 +00:00
|
|
|
|
2015-01-20 13:59:19 +00:00
|
|
|
log.info("Starting server on {}:{}".format(self._host, self._port))
|
2015-03-13 00:44:05 +00:00
|
|
|
self._handler = app.make_handler(handler=RequestHandler)
|
2015-07-20 22:02:28 +00:00
|
|
|
server = self._run_application(self._handler, ssl_context)
|
|
|
|
self._loop.run_until_complete(server)
|
2015-03-13 00:44:05 +00:00
|
|
|
self._signal_handling()
|
2015-05-05 09:33:47 +00:00
|
|
|
self._exit_handling()
|
|
|
|
|
2015-02-20 21:40:20 +00:00
|
|
|
if server_config.getboolean("shell"):
|
|
|
|
asyncio.async(self.start_shell())
|
|
|
|
|
2016-06-16 17:27:10 +00:00
|
|
|
if sys.platform.startswith("linux") and server_config.getboolean("server_discovery"):
|
2016-06-16 17:17:12 +00:00
|
|
|
# UDP discovery is only supported on Linux
|
|
|
|
udp_server_discovery = threading.Thread(target=self._udp_server_discovery, daemon=True)
|
|
|
|
udp_server_discovery.start()
|
2016-06-15 23:37:43 +00:00
|
|
|
|
2015-03-13 00:48:07 +00:00
|
|
|
try:
|
|
|
|
self._loop.run_forever()
|
|
|
|
except TypeError as e:
|
|
|
|
# This is to ignore an asyncio.windows_events exception
|
2015-03-13 00:50:38 +00:00
|
|
|
# on Windows when the process gets the SIGBREAK signal
|
2015-03-13 00:48:07 +00:00
|
|
|
# TypeError: async() takes 1 positional argument but 3 were given
|
|
|
|
log.warning("TypeError exception in the loop {}".format(e))
|
2015-07-20 22:02:28 +00:00
|
|
|
finally:
|
2016-06-16 17:17:12 +00:00
|
|
|
|
2015-07-26 21:27:47 +00:00
|
|
|
if self._handler and self._loop.is_running():
|
2015-07-22 00:00:03 +00:00
|
|
|
self._loop.run_until_complete(self._handler.finish_connections())
|
2015-07-20 22:02:28 +00:00
|
|
|
server.close()
|
2015-07-26 21:27:47 +00:00
|
|
|
if self._loop.is_running():
|
|
|
|
self._loop.run_until_complete(app.finish())
|