2013-10-30 23:58:17 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
# Copyright (C) 2013 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/>.
|
|
|
|
|
2013-12-06 06:39:27 +02:00
|
|
|
"""
|
2014-03-11 23:45:04 +02:00
|
|
|
Set up and run the server.
|
2013-12-06 06:39:27 +02:00
|
|
|
"""
|
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
import zmq
|
|
|
|
from zmq.eventloop import ioloop, zmqstream
|
|
|
|
ioloop.install()
|
|
|
|
|
2014-03-16 05:41:04 +02:00
|
|
|
import sys
|
2013-12-05 09:21:06 +02:00
|
|
|
import os
|
2014-03-11 23:45:04 +02:00
|
|
|
import tempfile
|
2013-12-07 02:52:16 +02:00
|
|
|
import signal
|
2013-12-06 06:39:27 +02:00
|
|
|
import errno
|
2013-10-30 23:58:17 +02:00
|
|
|
import socket
|
|
|
|
import tornado.ioloop
|
|
|
|
import tornado.web
|
2013-12-05 09:21:06 +02:00
|
|
|
import tornado.autoreload
|
2014-05-29 10:30:18 +03:00
|
|
|
import pkg_resources
|
2014-09-03 07:33:45 +03:00
|
|
|
from os.path import expanduser
|
2014-04-11 04:42:26 +03:00
|
|
|
|
|
|
|
from pkg_resources import parse_version
|
2014-03-11 23:45:04 +02:00
|
|
|
from .config import Config
|
2013-12-22 02:34:51 +02:00
|
|
|
from .handlers.jsonrpc_websocket import JSONRPCWebSocket
|
2013-12-06 06:39:27 +02:00
|
|
|
from .handlers.version_handler import VersionHandler
|
2014-03-11 23:45:04 +02:00
|
|
|
from .handlers.file_upload_handler import FileUploadHandler
|
2014-05-08 04:31:53 +03:00
|
|
|
from .builtins.server_version import server_version
|
|
|
|
from .builtins.interfaces import interfaces
|
2014-03-16 05:41:04 +02:00
|
|
|
from .modules import MODULES
|
2013-10-30 23:58:17 +02:00
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
import logging
|
|
|
|
log = logging.getLogger(__name__)
|
2013-10-30 23:58:17 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Server(object):
|
|
|
|
|
|
|
|
# built-in handlers
|
2014-03-11 23:45:04 +02:00
|
|
|
handlers = [(r"/version", VersionHandler),
|
|
|
|
(r"/upload", FileUploadHandler)]
|
2013-10-30 23:58:17 +02:00
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
def __init__(self, host, port, ipc=False):
|
2013-10-30 23:58:17 +02:00
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
self._host = host
|
|
|
|
self._port = port
|
2014-04-27 02:51:47 +03:00
|
|
|
self._router = None
|
|
|
|
self._stream = None
|
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
if ipc:
|
2014-03-03 00:20:03 +02:00
|
|
|
self._zmq_port = 0 # this forces to use IPC for communications with the ZeroMQ server
|
2013-12-05 09:21:06 +02:00
|
|
|
else:
|
2014-04-12 03:33:42 +03:00
|
|
|
# communication between the ZeroMQ server and the modules (ZeroMQ dealers)
|
|
|
|
# is IPv4 and local (127.0.0.1)
|
2014-03-03 00:20:03 +02:00
|
|
|
try:
|
|
|
|
# let the OS find an unused port for the ZeroMQ server
|
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
2014-04-12 03:33:42 +03:00
|
|
|
sock.bind(("127.0.0.1", 0))
|
2014-03-03 00:20:03 +02:00
|
|
|
self._zmq_port = sock.getsockname()[1]
|
2014-04-06 20:37:34 +03:00
|
|
|
except OSError as e:
|
2014-04-12 03:33:42 +03:00
|
|
|
log.critical("server cannot listen to {}: {}".format(self._host, e))
|
|
|
|
raise SystemExit
|
2013-12-05 09:21:06 +02:00
|
|
|
self._ipc = ipc
|
|
|
|
self._modules = []
|
2013-10-30 23:58:17 +02:00
|
|
|
|
2014-03-11 23:45:04 +02:00
|
|
|
# get the projects and temp directories from the configuration file (passed to the modules)
|
|
|
|
config = Config.instance()
|
|
|
|
server_config = config.get_default_section()
|
2014-06-29 19:14:15 +03:00
|
|
|
# default projects directory is "~/GNS3/projects"
|
|
|
|
self._projects_dir = os.path.expandvars(os.path.expanduser(server_config.get("projects_directory", "~/GNS3/projects")))
|
2014-03-11 23:45:04 +02:00
|
|
|
self._temp_dir = server_config.get("temporary_directory", tempfile.gettempdir())
|
|
|
|
|
2014-04-13 01:46:02 +03:00
|
|
|
try:
|
|
|
|
os.makedirs(self._projects_dir)
|
|
|
|
log.info("projects directory '{}' created".format(self._projects_dir))
|
|
|
|
except FileExistsError:
|
|
|
|
pass
|
|
|
|
except OSError as e:
|
|
|
|
log.error("could not create the projects directory {}: {}".format(self._projects_dir, e))
|
2014-03-11 23:45:04 +02:00
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
def load_modules(self):
|
2013-12-06 06:39:27 +02:00
|
|
|
"""
|
2013-12-22 02:34:51 +02:00
|
|
|
Loads the modules.
|
2013-10-30 23:58:17 +02:00
|
|
|
"""
|
|
|
|
|
2014-03-16 05:41:04 +02:00
|
|
|
#=======================================================================
|
|
|
|
# cwd = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
# module_path = os.path.join(cwd, 'modules')
|
|
|
|
# log.info("loading modules from {}".format(module_path))
|
|
|
|
# module_manager = ModuleManager([module_path])
|
|
|
|
# module_manager.load_modules()
|
|
|
|
# for module in module_manager.get_all_modules():
|
|
|
|
# instance = module_manager.activate_module(module,
|
|
|
|
# "127.0.0.1", # ZeroMQ server address
|
|
|
|
# self._zmq_port, # ZeroMQ server port
|
|
|
|
# projects_dir=self._projects_dir,
|
|
|
|
# temp_dir=self._temp_dir)
|
|
|
|
# if not instance:
|
|
|
|
# continue
|
|
|
|
# self._modules.append(instance)
|
|
|
|
# destinations = instance.destinations()
|
|
|
|
# for destination in destinations:
|
|
|
|
# JSONRPCWebSocket.register_destination(destination, module.name)
|
|
|
|
# instance.start() # starts the new process
|
|
|
|
#=======================================================================
|
|
|
|
|
2014-05-08 04:31:53 +03:00
|
|
|
# special built-in to return the server version
|
|
|
|
JSONRPCWebSocket.register_destination("builtin.version", server_version)
|
|
|
|
# special built-in to return the available interfaces on this host
|
|
|
|
JSONRPCWebSocket.register_destination("builtin.interfaces", interfaces)
|
|
|
|
|
2014-03-16 05:41:04 +02:00
|
|
|
for module in MODULES:
|
|
|
|
instance = module(module.__name__.lower(),
|
|
|
|
"127.0.0.1", # ZeroMQ server address
|
|
|
|
self._zmq_port, # ZeroMQ server port
|
2014-04-12 03:33:42 +03:00
|
|
|
host=self._host, # server host address
|
2014-03-16 05:41:04 +02:00
|
|
|
projects_dir=self._projects_dir,
|
|
|
|
temp_dir=self._temp_dir)
|
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
self._modules.append(instance)
|
|
|
|
destinations = instance.destinations()
|
|
|
|
for destination in destinations:
|
2014-03-16 05:41:04 +02:00
|
|
|
JSONRPCWebSocket.register_destination(destination, instance.name)
|
2013-12-05 09:21:06 +02:00
|
|
|
instance.start() # starts the new process
|
2013-10-30 23:58:17 +02:00
|
|
|
|
2014-09-03 07:33:45 +03:00
|
|
|
|
|
|
|
def _get_cert_info(self):
|
|
|
|
"""
|
|
|
|
Finds the cert and key file needed for SSL
|
|
|
|
"""
|
|
|
|
|
|
|
|
home = expanduser("~")
|
|
|
|
ssl_dir = "%s/.conf/GNS3Certs/" % (home)
|
|
|
|
log.debug("Looking for SSL certs in: %s" % (ssl_dir))
|
|
|
|
|
|
|
|
keyfile = "%s/gns3server.localdomain.com.key" % (ssl_dir)
|
|
|
|
certfile = "%s/gns3server.localdomain.com.crt" % (ssl_dir)
|
|
|
|
|
|
|
|
if os.path.isfile(keyfile) and os.path.isfile(certfile):
|
|
|
|
return { "certfile" : certfile,
|
|
|
|
"keyfile" : keyfile,
|
|
|
|
}
|
|
|
|
|
2013-10-30 23:58:17 +02:00
|
|
|
def run(self):
|
2013-12-05 09:21:06 +02:00
|
|
|
"""
|
2013-12-22 02:34:51 +02:00
|
|
|
Starts the Tornado web server and ZeroMQ server.
|
2013-10-30 23:58:17 +02:00
|
|
|
"""
|
|
|
|
|
2013-12-05 09:21:06 +02:00
|
|
|
router = self._create_zmq_router()
|
2013-12-22 02:34:51 +02:00
|
|
|
# Add our JSON-RPC Websocket handler to Tornado
|
|
|
|
self.handlers.extend([(r"/", JSONRPCWebSocket, dict(zmq_router=router))])
|
2014-05-29 10:30:18 +03:00
|
|
|
if hasattr(sys, "frozen"):
|
|
|
|
templates_dir = "templates"
|
|
|
|
else:
|
|
|
|
templates_dir = pkg_resources.resource_filename("gns3server", "templates")
|
2014-03-30 06:29:10 +03:00
|
|
|
tornado_app = tornado.web.Application(self.handlers,
|
2014-05-29 10:30:18 +03:00
|
|
|
template_path=templates_dir,
|
2014-03-30 06:29:10 +03:00
|
|
|
debug=True) # FIXME: debug mode!
|
2014-04-09 22:03:01 +03:00
|
|
|
|
2013-10-30 23:58:17 +02:00
|
|
|
try:
|
2014-04-30 19:17:45 +03:00
|
|
|
print("Starting server on {}:{} (Tornado v{}, PyZMQ v{}, ZMQ v{})".format(self._host,
|
|
|
|
self._port,
|
|
|
|
tornado.version,
|
|
|
|
zmq.__version__,
|
|
|
|
zmq.zmq_version()))
|
2014-04-11 04:42:26 +03:00
|
|
|
kwargs = {"address": self._host}
|
2014-08-30 10:32:48 +03:00
|
|
|
|
2014-09-03 07:33:45 +03:00
|
|
|
ssl_options = self._get_cert_info()
|
2014-08-30 10:32:48 +03:00
|
|
|
|
2014-09-03 07:33:45 +03:00
|
|
|
if ssl_options:
|
|
|
|
log.info("Certs found - starting in SSL mode")
|
|
|
|
kwargs['ssl_options'] = ssl_options
|
2014-08-30 10:32:48 +03:00
|
|
|
|
2014-04-11 04:42:26 +03:00
|
|
|
if parse_version(tornado.version) >= parse_version("3.1"):
|
|
|
|
kwargs["max_buffer_size"] = 524288000 # 500 MB file upload limit
|
|
|
|
tornado_app.listen(self._port, **kwargs)
|
2014-04-06 20:37:34 +03:00
|
|
|
except OSError as e:
|
2013-12-06 06:39:27 +02:00
|
|
|
if e.errno == errno.EADDRINUSE: # socket already in use
|
2014-04-06 20:37:34 +03:00
|
|
|
logging.critical("socket in use for {}:{}".format(self._host, self._port))
|
2014-05-14 20:24:14 +03:00
|
|
|
self._cleanup(graceful=False)
|
2013-12-05 09:21:06 +02:00
|
|
|
|
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
2014-04-27 02:51:47 +03:00
|
|
|
self._stream = zmqstream.ZMQStream(router, ioloop)
|
|
|
|
self._stream.on_recv_stream(JSONRPCWebSocket.dispatch_message)
|
2014-05-14 02:17:26 +03:00
|
|
|
tornado.autoreload.add_reload_hook(self._reload_callback)
|
2013-12-05 09:21:06 +02:00
|
|
|
|
2013-12-07 02:52:16 +02:00
|
|
|
def signal_handler(signum=None, frame=None):
|
2014-07-18 00:28:02 +03:00
|
|
|
try:
|
|
|
|
log.warning("Server got signal {}, exiting...".format(signum))
|
|
|
|
self._cleanup(signum)
|
|
|
|
except RuntimeError:
|
|
|
|
# to ignore logging exception: RuntimeError: reentrant call inside <_io.BufferedWriter name='<stderr>'>
|
|
|
|
pass
|
2013-12-07 02:52:16 +02:00
|
|
|
|
2014-03-16 05:41:04 +02:00
|
|
|
signals = [signal.SIGTERM, signal.SIGINT]
|
|
|
|
if not sys.platform.startswith("win"):
|
|
|
|
signals.extend([signal.SIGHUP, signal.SIGQUIT])
|
2014-04-01 03:36:45 +03:00
|
|
|
else:
|
|
|
|
signals.extend([signal.SIGBREAK])
|
2014-03-16 05:41:04 +02:00
|
|
|
for sig in signals:
|
2013-12-07 02:52:16 +02:00
|
|
|
signal.signal(sig, signal_handler)
|
|
|
|
|
2013-10-30 23:58:17 +02:00
|
|
|
try:
|
2013-12-05 09:21:06 +02:00
|
|
|
ioloop.start()
|
2013-10-30 23:58:17 +02:00
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
|
|
print("\nExiting...")
|
2013-12-05 09:21:06 +02:00
|
|
|
self._cleanup()
|
|
|
|
|
|
|
|
def _create_zmq_router(self):
|
|
|
|
"""
|
|
|
|
Creates the ZeroMQ router socket to send
|
|
|
|
requests to modules.
|
|
|
|
|
2013-12-06 06:39:27 +02:00
|
|
|
:returns: ZeroMQ router socket
|
2013-12-05 09:21:06 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
context = zmq.Context()
|
|
|
|
context.linger = 0
|
2014-04-27 02:51:47 +03:00
|
|
|
self._router = context.socket(zmq.ROUTER)
|
2013-12-05 09:21:06 +02:00
|
|
|
if self._ipc:
|
|
|
|
try:
|
2014-04-27 02:51:47 +03:00
|
|
|
self._router.bind("ipc:///tmp/gns3.ipc")
|
2013-12-05 09:21:06 +02:00
|
|
|
except zmq.error.ZMQError as e:
|
|
|
|
log.critical("Could not start ZeroMQ server on ipc:///tmp/gns3.ipc, reason: {}".format(e))
|
2014-05-14 20:24:14 +03:00
|
|
|
self._cleanup(graceful=False)
|
2013-12-05 09:21:06 +02:00
|
|
|
raise SystemExit
|
|
|
|
log.info("ZeroMQ server listening to ipc:///tmp/gns3.ipc")
|
|
|
|
else:
|
|
|
|
try:
|
2014-04-27 02:51:47 +03:00
|
|
|
self._router.bind("tcp://127.0.0.1:{}".format(self._zmq_port))
|
2013-12-05 09:21:06 +02:00
|
|
|
except zmq.error.ZMQError as e:
|
|
|
|
log.critical("Could not start ZeroMQ server on 127.0.0.1:{}, reason: {}".format(self._zmq_port, e))
|
2014-05-14 20:24:14 +03:00
|
|
|
self._cleanup(graceful=False)
|
2013-12-05 09:21:06 +02:00
|
|
|
raise SystemExit
|
|
|
|
log.info("ZeroMQ server listening to 127.0.0.1:{}".format(self._zmq_port))
|
2014-04-27 02:51:47 +03:00
|
|
|
return self._router
|
2013-12-05 09:21:06 +02:00
|
|
|
|
2014-05-13 23:17:04 +03:00
|
|
|
def stop_module(self, module):
|
|
|
|
"""
|
|
|
|
Stop a given module.
|
|
|
|
|
|
|
|
:param module: module name
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not self._router.closed:
|
|
|
|
self._router.send_string(module, zmq.SNDMORE)
|
|
|
|
self._router.send_string("stop")
|
|
|
|
|
2014-05-14 02:17:26 +03:00
|
|
|
def _reload_callback(self):
|
|
|
|
"""
|
|
|
|
Callback for the Tornado reload hook.
|
|
|
|
"""
|
|
|
|
|
|
|
|
for module in self._modules:
|
|
|
|
if module.is_alive():
|
|
|
|
module.terminate()
|
|
|
|
module.join(timeout=1)
|
|
|
|
|
2014-04-02 19:33:35 +03:00
|
|
|
def _shutdown(self):
|
|
|
|
"""
|
2014-04-27 02:51:47 +03:00
|
|
|
Shutdowns the I/O loop and the ZeroMQ stream & socket.
|
2014-04-02 19:33:35 +03:00
|
|
|
"""
|
|
|
|
|
2014-04-27 02:51:47 +03:00
|
|
|
if self._stream and not self._stream.closed:
|
|
|
|
# close the ZeroMQ stream
|
|
|
|
self._stream.close()
|
|
|
|
|
|
|
|
if self._router and not self._router.closed:
|
|
|
|
# close the ZeroMQ router socket
|
|
|
|
self._router.close()
|
|
|
|
|
2014-04-02 19:33:35 +03:00
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
|
|
|
ioloop.stop()
|
|
|
|
|
2014-05-14 20:24:14 +03:00
|
|
|
def _cleanup(self, signum=None, graceful=True):
|
2013-12-05 09:21:06 +02:00
|
|
|
"""
|
2014-02-21 02:39:03 +02:00
|
|
|
Shutdowns any running module processes
|
2014-04-27 02:51:47 +03:00
|
|
|
and adds a callback to stop the event loop & ZeroMQ
|
2013-12-05 09:21:06 +02:00
|
|
|
|
2014-05-14 02:17:26 +03:00
|
|
|
:param signum: signal number (if called by a signal handler)
|
2014-05-14 20:24:14 +03:00
|
|
|
:param graceful: gracefully stop the modules
|
2013-12-05 09:21:06 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
# terminate all modules
|
|
|
|
for module in self._modules:
|
2014-05-14 20:24:14 +03:00
|
|
|
if module.is_alive() and graceful:
|
2014-05-13 23:17:04 +03:00
|
|
|
log.info("stopping {}".format(module.name))
|
|
|
|
self.stop_module(module.name)
|
|
|
|
module.join(timeout=3)
|
2014-05-14 20:24:14 +03:00
|
|
|
if module.is_alive():
|
|
|
|
# just kill the module if it is still alive.
|
|
|
|
log.info("terminating {}".format(module.name))
|
|
|
|
module.terminate()
|
|
|
|
module.join(timeout=1)
|
2013-12-05 09:21:06 +02:00
|
|
|
|
2014-05-14 02:17:26 +03:00
|
|
|
ioloop = tornado.ioloop.IOLoop.instance()
|
|
|
|
if signum:
|
|
|
|
ioloop.add_callback_from_signal(self._shutdown)
|
|
|
|
else:
|
|
|
|
ioloop.add_callback(self._shutdown)
|