提交 731a72e7 编写于 作者: N nicolargo

Refactor __init__ and main scripts #1050 - Need to find a way to kill server when CTRL-C

上级 75f75154
......@@ -70,130 +70,40 @@ def __signal_handler(signal, frame):
def end():
"""Stop Glances."""
if core.is_standalone() and not WINDOWS:
# Stop the standalone (CLI)
standalone.end()
logger.info("Stop Glances (with CTRL-C)")
elif core.is_client() and not WINDOWS:
# Stop the client
client.end()
logger.info("Stop Glances client (with CTRL-C)")
elif core.is_server():
# Stop the server
server.end()
logger.info("Stop Glances server (with CTRL-C)")
elif core.is_webserver():
# Stop the Web server
webserver.end()
logger.info("Stop Glances web server(with CTRL-C)")
mode.end()
logger.info("Glances stopped with CTRL-C")
# The end...
sys.exit(0)
def start_standalone(config, args):
"""Start the standalone mode"""
logger.info("Start standalone mode")
# Share global var
global standalone
# Import the Glances standalone module
from glances.standalone import GlancesStandalone
# Init the standalone mode
standalone = GlancesStandalone(config=config, args=args)
# Start the standalone (CLI) loop
standalone.serve_forever()
def start_clientbrowser(config, args):
"""Start the browser client mode"""
logger.info("Start client mode (browser)")
# Share global var
global client
# Import the Glances client browser module
from glances.client_browser import GlancesClientBrowser
# Init the client
client = GlancesClientBrowser(config=config, args=args)
# Start the client loop
client.serve_forever()
# Shutdown the client
client.end()
def start_client(config, args):
"""Start the client mode"""
logger.info("Start client mode")
# Share global var
global client
# Import the Glances client browser module
from glances.client import GlancesClient
# Init the client
client = GlancesClient(config=config, args=args)
# Test if client and server are in the same major version
if not client.login():
logger.critical("The server version is not compatible with the client")
sys.exit(2)
# Start the client loop
client.serve_forever()
def start(config, args):
"""Start Glances"""
# Shutdown the client
client.end()
# Load mode
global mode
if core.is_standalone() and not WINDOWS:
from glances.standalone import GlancesStandalone as GlancesMode
elif core.is_client() and not WINDOWS:
if core.is_client_browser():
from glances.client_browser import GlancesClientBrowser as GlancesMode
else:
from glances.client import GlancesClient as GlancesMode
elif core.is_server():
from glances.server import GlancesServer as GlancesMode
elif core.is_webserver():
from glances.webserver import GlancesWebServer as GlancesMode
def start_server(config, args):
"""Start the server mode"""
logger.info("Start server mode")
# Share global var
global server
# Import the Glances server module
from glances.server import GlancesServer
server = GlancesServer(cached_time=args.cached_time,
config=config,
args=args)
print('Glances server is running on {}:{}'.format(args.bind_address, args.port))
# Set the server login/password (if -P/--password tag)
if args.password != "":
server.add_user(args.username, args.password)
# Start the server loop
server.serve_forever()
# Shutdown the server?
server.server_close()
def start_webserver(config, args):
"""Start the Web server mode"""
logger.info("Start web server mode")
# Share global var
global webserver
# Import the Glances web server module
from glances.webserver import GlancesWebServer
# Init the mode
logger.info("Start {} mode".format(GlancesMode.__name__))
mode = GlancesMode(config=config, args=args)
# Init the web server mode
webserver = GlancesWebServer(config=config, args=args)
# Start the main loop
mode.serve_forever()
# Start the web server loop
webserver.serve_forever()
# Shutdown
mode.end()
def main():
......@@ -221,15 +131,4 @@ def main():
signal.signal(signal.SIGINT, __signal_handler)
# Glances can be ran in standalone, client or server mode
if core.is_standalone() and not WINDOWS:
start_standalone(config=config, args=args)
elif core.is_client() and not WINDOWS:
if core.is_client_browser():
start_clientbrowser(config=config, args=args)
else:
start_client(config=config, args=args)
elif core.is_server():
start_server(config=config, args=args)
elif core.is_webserver():
# Web server mode replace the standalone mode on Windows OS
start_webserver(config=config, args=args)
start(config=config, args=args)
......@@ -223,6 +223,13 @@ class GlancesClient(object):
def serve_forever(self):
"""Main client loop."""
# Test if client and server are in the same major version
if not self.login():
logger.critical("The server version is not compatible with the client")
self.end()
return self.client_mode
exitkey = False
try:
while True and not exitkey:
......
......@@ -31,7 +31,7 @@ PY3 = sys.version_info[0] == 3
if PY3:
import queue
from configparser import ConfigParser, NoOptionError, NoSectionError
from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport
from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport, Server
from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
......@@ -88,7 +88,7 @@ else:
from itertools import imap as map
from ConfigParser import SafeConfigParser as ConfigParser, NoOptionError, NoSectionError
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport
from xmlrpclib import Fault, ProtocolError, ServerProxy, Transport, Server
from urllib2 import urlopen, HTTPError, URLError
input = raw_input
......
......@@ -406,21 +406,6 @@ Examples of use:
return args
def __get_username(self, description=''):
"""Read a username from the command line.
"""
return input(description)
def __get_password(self, description='', confirm=False, clear=False, username='glances'):
"""Read a password from the command line.
- if confirm = True, with confirmation
- if clear = True, plain (clear password)
"""
from glances.password import GlancesPassword
password = GlancesPassword(username=username)
return password.get_password(description, confirm, clear)
def is_standalone(self):
"""Return True if Glances is running in standalone mode."""
return (not self.args.client and
......@@ -451,3 +436,22 @@ Examples of use:
def get_args(self):
"""Return the arguments."""
return self.args
def get_mode(self):
"""Return the mode."""
return self.mode
def __get_username(self, description=''):
"""Read an username from the command line.
"""
return input(description)
def __get_password(self, description='', confirm=False, clear=False, username='glances'):
"""Read a password from the command line.
- if confirm = True, with confirmation
- if clear = True, plain (clear password)
"""
from glances.password import GlancesPassword
password = GlancesPassword(username=username)
return password.get_password(description, confirm, clear)
......@@ -25,7 +25,7 @@ import sys
from base64 import b64decode
from glances import __version__
from glances.compat import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
from glances.compat import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer, Server
from glances.autodiscover import GlancesAutoDiscoverClient
from glances.logger import logger
from glances.stats_server import GlancesStatsServer
......@@ -100,9 +100,13 @@ class GlancesXMLRPCServer(SimpleXMLRPCServer, object):
"""Init a SimpleXMLRPCServer instance (IPv6-ready)."""
finished = False
def __init__(self, bind_address, bind_port=61209,
requestHandler=GlancesXMLRPCHandler):
self.bind_address = bind_address
self.bind_port = bind_port
try:
self.address_family = socket.getaddrinfo(bind_address, bind_port)[0][0]
except socket.error as e:
......@@ -111,13 +115,23 @@ class GlancesXMLRPCServer(SimpleXMLRPCServer, object):
super(GlancesXMLRPCServer, self).__init__((bind_address, bind_port), requestHandler)
def end(self):
"""Stop the server"""
self.server_close()
self.finished = True
def serve_forever(self):
"""Main loop"""
while not self.finished:
self.handle_request()
logger.info(self.finished)
class GlancesInstance(object):
"""All the methods of this class are published as XML-RPC methods."""
def __init__(self,
cached_time=1,
config=None,
args=None):
# Init stats
......@@ -130,7 +144,7 @@ class GlancesInstance(object):
# i.e. XML/RPC calls will not retrieve updated info until the time
# since last update is passed (will retrieve old cached info instead)
self.timer = Timer(0)
self.cached_time = cached_time
self.cached_time = args.cached_time
def __update__(self):
# Never update more than 1 time per cached_time
......@@ -186,7 +200,6 @@ class GlancesServer(object):
def __init__(self,
requestHandler=GlancesXMLRPCHandler,
cached_time=1,
config=None,
args=None):
# Args
......@@ -198,6 +211,8 @@ class GlancesServer(object):
except Exception as e:
logger.critical("Cannot start Glances server: {}".format(e))
sys.exit(2)
else:
print('Glances XML-RPC server is running on {}:{}'.format(args.bind_address, args.port))
# The users dict
# username / password couple
......@@ -207,7 +222,7 @@ class GlancesServer(object):
# Register functions
self.server.register_introspection_functions()
self.server.register_instance(GlancesInstance(cached_time, config, args))
self.server.register_instance(GlancesInstance(config, args))
if not self.args.disable_autodiscover:
# Note: The Zeroconf service name will be based on the hostname
......@@ -223,14 +238,14 @@ class GlancesServer(object):
def serve_forever(self):
"""Call the main loop."""
# Set the server login/password (if -P/--password tag)
if self.args.password != "":
self.add_user(self.args.username, self.args.password)
# Serve forever
self.server.serve_forever()
def server_close(self):
"""Close the Glances server session."""
self.server.server_close()
def end(self):
"""End of the Glances server session."""
if not self.args.disable_autodiscover:
self.autodiscover_client.close()
self.server_close()
self.server.end()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册