def __init__(self, requestHandler=GlancesXMLRPCHandler, cached_time=1, config=None, args=None): # Args self.args = args # Init the XML RPC server try: self.server = GlancesXMLRPCServer(args.bind_address, args.port, requestHandler) except Exception as e: logger.critical("Cannot start Glances server: {0}".format(e)) sys.exit(2) # The users dict # username / password couple # By default, no auth is needed self.server.user_dict = {} self.server.isAuth = False # Register functions self.server.register_introspection_functions() self.server.register_instance(GlancesInstance(cached_time, config)) if not self.args.disable_autodiscover: # Note: The Zeroconf service name will be based on the hostname self.autodiscover_client = GlancesAutoDiscoverClient( socket.gethostname(), args) else: logger.info("Glances autodiscover announce is disabled")
def init(self): """Init the connection to the InfluxDB server.""" if not self.export_enable: return None try: db = InfluxDBClient(host=self.host, port=self.port, username=self.user, password=self.password, database=self.db) get_all_db = [i['name'] for i in db.get_list_database()] except InfluxDBClientError: # https://github.com/influxdb/influxdb-python/issues/138 logger.info("Trying fallback to InfluxDB v0.8") db = InfluxDBClient08(host=self.host, port=self.port, username=self.user, password=self.password, database=self.db) get_all_db = [i['name'] for i in db.get_list_database()] except InfluxDBClientError08 as e: logger.critical("Cannot connect to InfluxDB database '%s' (%s)" % (self.db, e)) sys.exit(2) if self.db in get_all_db: logger.info( "Stats will be exported to InfluxDB server: {0}".format(db._baseurl)) else: logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.db) sys.exit(2) return db
def log_and_exit(self, msg=''): """Log and exit.""" if not self.return_to_browser: logger.critical(msg) sys.exit(2) else: logger.error(msg)
def log_and_exit(self, msg=''): """Log and (exit)""" if not self.return_to_browser: logger.critical(msg) sys.exit(2) else: logger.error(msg)
def load_conf(self, section="opentsdb"): """Load the OpenTSDB configuration in the Glances configuration file.""" if self.config is None: return False try: self.host = self.config.get_value(section, 'host') self.port = self.config.get_value(section, 'port') except NoSectionError: logger.critical("No OpenTSDB configuration found") return False except NoOptionError as e: logger.critical("Error in the OpenTSDB configuration (%s)" % e) return False else: logger.debug("Load OpenTSDB from the Glances configuration file") # Prefix is optional try: self.prefix = self.config.get_value(section, 'prefix') except NoOptionError: pass # Tags are optional, comma separated key:value pairs. try: self.tags = self.config.get_value(section, 'tags') except NoOptionError: self.tags = '' return True
def __init__(self, requestHandler=GlancesXMLRPCHandler, cached_time=1, config=None, args=None): # Args self.args = args # Init the XML RPC server try: self.server = GlancesXMLRPCServer(args.bind_address, args.port, requestHandler) except Exception as e: logger.critical("Cannot start Glances server: {0}".format(e)) sys.exit(2) # The users dict # username / password couple # By default, no auth is needed self.server.user_dict = {} self.server.isAuth = False # Register functions self.server.register_introspection_functions() self.server.register_instance(GlancesInstance(cached_time, config)) if not self.args.disable_autodiscover: # Note: The Zeroconf service name will be based on the hostname self.autodiscover_client = GlancesAutoDiscoverClient(socket.gethostname(), args) else: logger.info("Glances autodiscover announce is disabled")
def load_conf(self, section="influxdb"): """Load the InfluxDb configuration in the Glances configuration file.""" if self.config is None: return False try: self.host = self.config.get_value(section, 'host') self.port = self.config.get_value(section, 'port') self.user = self.config.get_value(section, 'user') self.password = self.config.get_value(section, 'password') self.db = self.config.get_value(section, 'db') except NoSectionError: logger.critical("No InfluxDB configuration found") return False except NoOptionError as e: logger.critical("Error in the InfluxDB configuration (%s)" % e) return False else: logger.debug("Load InfluxDB from the Glances configuration file") # Prefix is optional try: self.prefix = self.config.get_value(section, 'prefix') except NoOptionError: pass # Tags are optional, comma separated key:value pairs. try: self.tags = self.config.get_value(section, 'tags') except NoOptionError: self.tags = '' return True
def update(self): """Update stats from Glances/SNMP server.""" if self.client_mode == 'glances': return self.update_glances() elif self.client_mode == 'snmp': return self.update_snmp() else: self.end() logger.critical("Unknown server mode: {0}".format(self.client_mode)) sys.exit(2)
def update(self): """Update stats from Glances/SNMP server.""" if self.get_mode() == 'glances': return self.update_glances() elif self.get_mode() == 'snmp': return self.update_snmp() else: self.end() logger.critical("Unknown server mode: {0}".format(self.get_mode())) sys.exit(2)
def get_password(self, description='', confirm=False, clear=False): """Get the password from a Glances client or server. For Glances server, get the password (confirm=True, clear=False): 1) from the password file (if it exists) 2) from the CLI Optionally: save the password to a file (hashed with salt + SHA-256) For Glances client, get the password (confirm=False, clear=True): 1) from the CLI 2) the password is hashed with SHA-256 (only SHA string transit through the network) """ if os.path.exists(self.password_filepath) and not clear: # If the password file exist then use it logger.info("Read password from file {0}".format( self.password_filepath)) password = self.load_password() else: # Else enter the password from the command line if description != '': print(description) # password_plain is the plain SHA-256 password # password_hashed is the salt + SHA-256 password password_sha = hashlib.sha256( getpass.getpass(_("Password: "******"Password (confirm): ")).encode( 'utf-8')).hexdigest() if not self.check_password(password_hashed, password_confirm): logger.critical("Sorry, passwords do not match. Exit.") sys.exit(1) # Return the plain or hashed password if clear: password = password_sha else: password = password_hashed # Save the hashed password to the password file if not clear: save_input = input( _("Do you want to save the password? [Yes/No]: ")) if len(save_input) > 0 and save_input[0].upper() == _('Y'): self.save_password(password_hashed) return password
def init(self): """Init the connection to the rabbitmq server.""" if not self.export_enable: return None try: parameters = pika.URLParameters('amqp://' + self.rabbitmq_user + ':' + self.rabbitmq_password + '@' + self.rabbitmq_host + ':' + self.rabbitmq_port + '/') connection = pika.BlockingConnection(parameters) channel = connection.channel() return channel except Exception as e: logger.critical("Connection to rabbitMQ failed : %s " % e) return None
def init(self): """Init the connection to the rabbitmq server.""" if not self.export_enable: return None try: parameters = pika.URLParameters( 'amqp://' + self.rabbitmq_user + ':' + self.rabbitmq_password + '@' + self.rabbitmq_host + ':' + self.rabbitmq_port + '/') connection = pika.BlockingConnection(parameters) channel = connection.channel() return channel except Exception as e: logger.critical("Connection to rabbitMQ failed : %s " % e) return None
def init(self): """Init the connection to the OpenTSDB server.""" if not self.export_enable: return None try: db = potsdb.Client(self.host, port=int(self.port), check_host=True) except Exception as e: logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)" % (self.host, self.port, e)) sys.exit(2) # Read tags self.parse_tags() return db
def __init__(self, args=None): # CSV file name self.csv_filename = args.output_csv # Set the CSV output file try: if is_py3: self.csv_file = open(self.csv_filename, 'w', newline='') else: self.csv_file = open(self.csv_filename, 'wb') self.writer = csv.writer(self.csv_file) except IOError as e: logger.critical("Cannot create the CSV file: {0}".format(e)) sys.exit(2) logger.info("Stats dumped to CSV file: {0}".format(self.csv_filename))
def get_password(self, description='', confirm=False, clear=False): """Get the password from a Glances client or server. For Glances server, get the password (confirm=True, clear=False): 1) from the password file (if it exists) 2) from the CLI Optionally: save the password to a file (hashed with salt + SHA-256) For Glances client, get the password (confirm=False, clear=True): 1) from the CLI 2) the password is hashed with SHA-256 (only SHA string transit through the network) """ if os.path.exists(self.password_filepath) and not clear: # If the password file exist then use it logger.info("Read password from file {0}".format(self.password_filepath)) password = self.load_password() else: # Else enter the password from the command line if description != '': print(description) # password_sha256 is the plain SHA-256 password # password_hashed is the salt + SHA-256 password password_sha256 = self.sha256_hash(getpass.getpass('Password: '******'Password (confirm): ')) if not self.check_password(password_hashed, password_confirm): logger.critical("Sorry, passwords do not match. Exit.") sys.exit(1) # Return the plain SHA-256 or the salted password if clear: password = password_sha256 else: password = password_hashed # Save the hashed password to the password file if not clear: save_input = input('Do you want to save the password? [Yes/No]: ') if len(save_input) > 0 and save_input[0].upper() == 'Y': self.save_password(password_hashed) return password
def load_conf(self, section="elasticsearch"): """Load the elasticsearch configuration in the Glances configuration file.""" if self.config is None: return False try: #Create URI self.uri = "http://"+ self.config.get_value(section, 'host')+":"+self.config.get_value(section, 'port') +"/"+ self.config.get_value(section, 'index') +"/glances/" logger.debug("createURI :" + self.uri) except NoSectionError: logger.critical("No elasticsearch configuration found") return False except NoOptionError as e: logger.critical("Error in the elasticsearch configuration (%s)" % e) return False else: logger.debug("Load elasticsearch from the Glances configuration file") return True
def load_conf(self, section="rabbitmq"): """Load the rabbitmq configuration in the Glances configuration file.""" if self.config is None: return False try: self.rabbitmq_host = self.config.get_value(section, 'host') self.rabbitmq_port = self.config.get_value(section, 'port') self.rabbitmq_user = self.config.get_value(section, 'user') self.rabbitmq_password = self.config.get_value(section, 'password') self.rabbitmq_queue = self.config.get_value(section, 'queue') except NoSectionError: logger.critical("No rabbitmq configuration found") return False except NoOptionError as e: logger.critical("Error in the RabbitM configuration (%s)" % e) return False else: logger.debug("Load RabbitMQ from the Glances configuration file") return True
def load_conf(self, section="influxdb"): """Load the InfluxDb configuration in the Glances configuration file""" if self.config is None: return False try: self.influxdb_host = self.config.get_raw_option(section, "host") self.influxdb_port = self.config.get_raw_option(section, "port") self.influxdb_user = self.config.get_raw_option(section, "user") self.influxdb_password = self.config.get_raw_option(section, "password") self.influxdb_db = self.config.get_raw_option(section, "db") except NoSectionError: logger.critical("No InfluxDB configuration found") return False except NoOptionError as e: logger.critical("Error in the InfluxDB configuration (%s)" % e) return False else: logger.debug("Load InfluxDB from the Glances configuration file") return True
def serve_forever(self): """Main client loop.""" exitkey = False try: while True and not exitkey: # Update the stats cs_status = self.update() # Update the screen exitkey = self.screen.update(self.stats, cs_status=cs_status, return_to_browser=self.return_to_browser) # Export stats using export modules self.stats.export(self.stats) except Exception as e: logger.critical(e) self.end() return self.client_mode
def load_conf(self, section="statsd"): """Load the Statsd configuration in the Glances configuration file.""" if self.config is None: return False try: self.host = self.config.get_value(section, 'host') self.port = self.config.get_value(section, 'port') except NoSectionError: logger.critical("No Statsd configuration found") return False except NoOptionError as e: logger.critical("Error in the Statsd configuration (%s)" % e) return False else: logger.debug("Load Statsd from the Glances configuration file") # Prefix is optional try: self.prefix = self.config.get_value(section, 'prefix') except NoOptionError: pass return True
def load_conf(self, section="statsd"): """Load the Statsd configuration in the Glances configuration file""" if self.config is None: return False try: self.host = self.config.get_raw_option(section, "host") self.port = self.config.get_raw_option(section, "port") except NoSectionError: logger.critical("No Statsd configuration found") return False except NoOptionError as e: logger.critical("Error in the Statsd configuration (%s)" % e) return False else: logger.debug("Load Statsd from the Glances configuration file") # Prefix is optional try: self.prefix = self.config.get_raw_option(section, "prefix") except NoOptionError as e: pass return True
def serve_forever(self): """Main client loop.""" exitkey = False try: while True and not exitkey: # Update the stats cs_status = self.update() # Update the screen exitkey = self.screen.update( self.stats, cs_status=cs_status, return_to_browser=self.return_to_browser) # Export stats using export modules self.stats.export(self.stats) except Exception as e: logger.critical(e) self.end() return self.client_mode
def init(self): """Init the connection to the InfluxDB server""" if not self.export_enable: return None db = InfluxDBClient(self.influxdb_host, self.influxdb_port, self.influxdb_user, self.influxdb_password, self.influxdb_db) try: get_all_db = db.get_database_list()[0].values() except client.InfluxDBClientError as e: logger.critical("Can not connect to InfluxDB database '%s' (%s)" % (self.influxdb_db, e)) sys.exit(2) if self.influxdb_db in get_all_db: logger.info( "Stats will be exported to InfluxDB server: {0}".format(db._baseurl)) else: logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.influxdb_db) sys.exit(2) return db
def __init__(self, config=None, args=None): """Init the CSV export IF.""" GlancesExport.__init__(self, config=config, args=args) # CSV file name self.csv_filename = args.export_csv # Set the CSV output file try: if is_py3: self.csv_file = open(self.csv_filename, 'w', newline='') else: self.csv_file = open(self.csv_filename, 'wb') self.writer = csv.writer(self.csv_file) except IOError as e: logger.critical("Cannot create the CSV file: {0}".format(e)) sys.exit(2) logger.info("Stats exported to CSV file: {0}".format(self.csv_filename)) self.export_enable = True self.first_line = True
def __init__(self, config=None, args=None): """Init the CSV export IF.""" GlancesExport.__init__(self, config=config, args=args) # CSV file name self.csv_filename = args.export_csv # Set the CSV output file try: if is_py3: self.csv_file = open(self.csv_filename, 'w', newline='') else: self.csv_file = open(self.csv_filename, 'wb') self.writer = csv.writer(self.csv_file) except IOError as e: logger.critical("Cannot create the CSV file: {0}".format(e)) sys.exit(2) logger.info("Stats exported to CSV file: {0}".format( self.csv_filename)) self.export_enable = True self.first_line = True
def load_conf(self, section="influxdb"): """Load the InfluxDb configuration in the Glances configuration file.""" if self.config is None: return False try: self.host = self.config.get_value(section, 'host') self.port = self.config.get_value(section, 'port') self.user = self.config.get_value(section, 'user') self.password = self.config.get_value(section, 'password') self.db = self.config.get_value(section, 'db') except NoSectionError: logger.critical("No InfluxDB configuration found") return False except NoOptionError as e: logger.critical("Error in the InfluxDB configuration (%s)" % e) return False else: logger.debug("Load InfluxDB from the Glances configuration file") # Prefix is optional try: self.prefix = self.config.get_value(section, 'prefix') except NoOptionError: pass return True
# You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import threading import time import msvcrt from glances.core.glances_logging import logger try: import colorconsole import colorconsole.terminal except ImportError: logger.critical("Colorconsole module not found. Glances cannot start in standalone mode.") sys.exit(1) try: import queue except ImportError: # Python 2 import Queue as queue class ListenGetch(threading.Thread): def __init__(self, nom=""): threading.Thread.__init__(self) self.Terminated = False self.q = queue.Queue() def run(self):
# along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import threading import time import msvcrt from glances.core.glances_logging import logger try: import colorconsole import colorconsole.terminal except ImportError: logger.critical( "Colorconsole module not found. Glances cannot start in standalone mode." ) sys.exit(1) try: import queue except ImportError: # Python 2 import Queue as queue class ListenGetch(threading.Thread): def __init__(self, nom=''): threading.Thread.__init__(self) self.Terminated = False self.q = queue.Queue()
# Import Glances lib from glances.core.glances_globals import is_mac, is_windows from glances.core.glances_logging import logger from glances.core.glances_logs import glances_logs from glances.core.glances_processes import glances_processes from glances.core.glances_timer import Timer # Import curses lib for "normal" operating system and consolelog for Windows if not is_windows: try: import curses import curses.panel from curses.textpad import Textbox except ImportError: logger.critical("Curses module not found. Glances cannot start in standalone mode.") sys.exit(1) else: from glances.outputs.glances_colorconsole import WCurseLight curses = WCurseLight() class _GlancesCurses(object): """ This class manages the curses display (and key pressed). Note: It is a private class, use GlancesCursesClient or GlancesCursesBrowser """ def __init__(self, args=None): # Init args
def __init__(self, args=None): # Init args self.args = args # Init windows positions self.term_w = 80 self.term_h = 24 # Space between stats self.space_between_column = 3 self.space_between_line = 2 # Init the curses screen self.screen = curses.initscr() if not self.screen: logger.critical("Cannot init the curses library.\n") sys.exit(1) # Set curses options if hasattr(curses, 'start_color'): curses.start_color() if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'noecho'): curses.noecho() if hasattr(curses, 'cbreak'): curses.cbreak() self.set_cursor(0) # Init colors self.hascolors = False if curses.has_colors() and curses.COLOR_PAIRS > 8: self.hascolors = True # FG color, BG color if args.theme_white: curses.init_pair(1, curses.COLOR_BLACK, -1) else: curses.init_pair(1, curses.COLOR_WHITE, -1) curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED) curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA) curses.init_pair(6, curses.COLOR_RED, -1) curses.init_pair(7, curses.COLOR_GREEN, -1) curses.init_pair(8, curses.COLOR_BLUE, -1) try: curses.init_pair(9, curses.COLOR_MAGENTA, -1) except Exception: if args.theme_white: curses.init_pair(9, curses.COLOR_BLACK, -1) else: curses.init_pair(9, curses.COLOR_WHITE, -1) try: curses.init_pair(10, curses.COLOR_CYAN, -1) except Exception: if args.theme_white: curses.init_pair(10, curses.COLOR_BLACK, -1) else: curses.init_pair(10, curses.COLOR_WHITE, -1) else: self.hascolors = False if args.disable_bold: A_BOLD = curses.A_BOLD else: A_BOLD = 0 self.title_color = A_BOLD self.title_underline_color = A_BOLD | curses.A_UNDERLINE self.help_color = A_BOLD if self.hascolors: # Colors text styles self.no_color = curses.color_pair(1) self.default_color = curses.color_pair(3) | A_BOLD self.nice_color = curses.color_pair(9) | A_BOLD self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD self.ifWARNING_color = curses.color_pair(5) | A_BOLD self.ifCRITICAL_color = curses.color_pair(2) | A_BOLD self.default_color2 = curses.color_pair(7) | A_BOLD self.ifCAREFUL_color2 = curses.color_pair(8) | A_BOLD self.ifWARNING_color2 = curses.color_pair(9) | A_BOLD self.ifCRITICAL_color2 = curses.color_pair(6) | A_BOLD self.filter_color = curses.color_pair(10) | A_BOLD else: # B&W text styles self.no_color = curses.A_NORMAL self.default_color = curses.A_NORMAL self.nice_color = A_BOLD self.ifCAREFUL_color = curses.A_UNDERLINE self.ifWARNING_color = A_BOLD self.ifCRITICAL_color = curses.A_REVERSE self.default_color2 = curses.A_NORMAL self.ifCAREFUL_color2 = curses.A_UNDERLINE self.ifWARNING_color2 = A_BOLD self.ifCRITICAL_color2 = curses.A_REVERSE self.filter_color = A_BOLD # Define the colors list (hash table) for stats self.colors_list = { 'DEFAULT': self.no_color, 'UNDERLINE': curses.A_UNDERLINE, 'BOLD': A_BOLD, 'SORT': A_BOLD, 'OK': self.default_color2, 'FILTER': self.filter_color, 'TITLE': self.title_color, 'PROCESS': self.default_color2, 'STATUS': self.default_color2, 'NICE': self.nice_color, 'CAREFUL': self.ifCAREFUL_color2, 'WARNING': self.ifWARNING_color2, 'CRITICAL': self.ifCRITICAL_color2, 'OK_LOG': self.default_color, 'CAREFUL_LOG': self.ifCAREFUL_color, 'WARNING_LOG': self.ifWARNING_color, 'CRITICAL_LOG': self.ifCRITICAL_color } # Init main window self.term_window = self.screen.subwin(0, 0) # Init refresh time self.__refresh_time = args.time # Init process sort method self.args.process_sorted_by = 'auto' # Init edit filter tag self.edit_filter = False # Catch key pressed with non blocking mode self.term_window.keypad(1) self.term_window.nodelay(1) self.pressedkey = -1 # History tag self.reset_history_tag = False self.history_tag = False if args.enable_history: logger.info('Stats history enabled with output path %s' % args.path_history) from glances.exports.glances_history import GlancesHistory self.glances_history = GlancesHistory(args.path_history) if not self.glances_history.graph_enabled(): args.enable_history = False logger.error( 'Stats history disabled because MatPlotLib is not installed')
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys # Import Glances libs from glances.core.glances_logging import logger # Import mandatory PySNMP lib try: from pysnmp.entity.rfc3413.oneliner import cmdgen except ImportError: logger.critical("PySNMP library not found. To install it: pip install pysnmp") sys.exit(2) class GlancesSNMPClient(object): """SNMP client class (based on pysnmp library).""" def __init__(self, host="localhost", port=161, version="2c", community="public", user="******", auth=""): super(GlancesSNMPClient, self).__init__() self.cmdGen = cmdgen.CommandGenerator() self.version = version self.host = host
# You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Web interface class.""" import json import os import sys from glances.core.glances_globals import is_windows from glances.core.glances_logging import logger try: from bottle import Bottle, static_file, abort, response, request except ImportError: logger.critical('Bottle module not found. Glances cannot start in web server mode.') sys.exit(2) class GlancesBottle(object): """This class manages the Bottle Web server.""" def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None
def main(): """Main entry point for Glances. Select the mode (standalone, client or server) Run it... """ # Setup translations locale.setlocale(locale.LC_ALL, '') gettext.install(gettext_domain, locale_dir) # Share global var global core, standalone, client, server, webserver # Create the Glances main instance core = GlancesMain() # Catch the CTRL-C signal signal.signal(signal.SIGINT, __signal_handler) # Glances can be ran in standalone, client or server mode if core.is_standalone(): logger.info("Start standalone mode") # Import the Glances standalone module from glances.core.glances_standalone import GlancesStandalone # Init the standalone mode standalone = GlancesStandalone(config=core.get_config(), args=core.get_args()) # Start the standalone (CLI) loop standalone.serve_forever() elif core.is_client(): if core.is_client_browser(): logger.info("Start client mode (browser)") # Import the Glances client browser module from glances.core.glances_client_browser import GlancesClientBrowser # Init the client client = GlancesClientBrowser(config=core.get_config(), args=core.get_args()) else: logger.info("Start client mode") # Import the Glances client module from glances.core.glances_client import GlancesClient # Init the client client = GlancesClient(config=core.get_config(), args=core.get_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() # Shutdown the client client.end() elif core.is_server(): logger.info("Start server mode") # Import the Glances server module from glances.core.glances_server import GlancesServer args = core.get_args() server = GlancesServer(cached_time=core.cached_time, config=core.get_config(), args=args) print(_("Glances server is running on {0}:{1}").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() elif core.is_webserver(): logger.info("Start web server mode") # Import the Glances web server module from glances.core.glances_webserver import GlancesWebServer # Init the web server mode webserver = GlancesWebServer(config=core.get_config(), args=core.get_args()) # Start the web server loop webserver.serve_forever()
) zeroconf_tag = True except ImportError: zeroconf_tag = False # Import Glances libs from glances.core.glances_globals import appname from glances.core.glances_logging import logger # Zeroconf 0.16 or higher is needed if zeroconf_tag: zeroconf_min_version = (0, 16, 0) zeroconf_version = tuple([int(num) for num in __zeroconf_version.split('.')]) logger.debug("Zeroconf version {0} detected.".format(__zeroconf_version)) if zeroconf_version < zeroconf_min_version: logger.critical("Please install zeroconf 0.16 or higher.") sys.exit(1) # Global var zeroconf_type = "_%s._tcp." % appname class AutoDiscovered(object): """Class to manage the auto discovered servers dict""" def __init__(self): # server_dict is a list of dict (JSON compliant) # [ {'key': 'zeroconf name', ip': '172.1.2.3', 'port': 61209, 'cpu': 3, 'mem': 34 ...} ... ] self._server_list = []
def main(): """Main entry point for Glances. Select the mode (standalone, client or server) Run it... """ # Setup translations locale.setlocale(locale.LC_ALL, '') gettext.install(gettext_domain, locale_dir) # Share global var global core, standalone, client, server, webserver # Create the Glances main instance core = GlancesMain() # Catch the CTRL-C signal signal.signal(signal.SIGINT, __signal_handler) # Glances can be ran in standalone, client or server mode if core.is_standalone(): logger.info("Start standalone mode") # Import the Glances standalone module from glances.core.glances_standalone import GlancesStandalone # Init the standalone mode standalone = GlancesStandalone(config=core.get_config(), args=core.get_args()) # Start the standalone (CLI) loop standalone.serve_forever() elif core.is_client(): if core.is_client_browser(): logger.info("Start client mode (browser)") # Import the Glances client browser module from glances.core.glances_client_browser import GlancesClientBrowser # Init the client client = GlancesClientBrowser(config=core.get_config(), args=core.get_args()) else: logger.info("Start client mode") # Import the Glances client module from glances.core.glances_client import GlancesClient # Init the client client = GlancesClient(config=core.get_config(), args=core.get_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() # Shutdown the client client.end() elif core.is_server(): logger.info("Start server mode") # Import the Glances server module from glances.core.glances_server import GlancesServer args = core.get_args() server = GlancesServer(cached_time=core.cached_time, config=core.get_config(), args=args) print( _("Glances server is running on {0}:{1}").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() elif core.is_webserver(): logger.info("Start web server mode") # Import the Glances web server module from glances.core.glances_webserver import GlancesWebServer # Init the web server mode webserver = GlancesWebServer(config=core.get_config(), args=core.get_args()) # Start the web server loop webserver.serve_forever()
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys # Import Glances libs from glances.core.glances_logging import logger # Import mandatory PySNMP lib try: from pysnmp.entity.rfc3413.oneliner import cmdgen except ImportError: logger.critical( "PySNMP library not found. To install it: pip install pysnmp") sys.exit(2) class GlancesSNMPClient(object): """SNMP client class (based on pysnmp library).""" def __init__(self, host='localhost', port=161, version='2c', community='public', user='******', auth=''): super(GlancesSNMPClient, self).__init__() self.cmdGen = cmdgen.CommandGenerator()
from glances.core.glances_logging import logger from glances.core.glances_main import GlancesMain # Get PSutil version psutil_min_version = (2, 0, 0) psutil_version = tuple([int(num) for num in __psutil_version.split('.')]) # First log with Glances and PSUtil version logger.info('Start Glances {0}'.format(__version__)) logger.info('{0} {1} and PSutil {2} detected'.format( platform.python_implementation(), platform.python_version(), __psutil_version)) # Check PSutil version if psutil_version < psutil_min_version: logger.critical('PSutil 2.0 or higher is needed. Glances cannot start.') sys.exit(1) def __signal_handler(signal, frame): """Callback for CTRL-C.""" end() def end(): """Stop Glances.""" if core.is_standalone(): # Stop the standalone (CLI) standalone.end() logger.info("Stop Glances (with CTRL-C)") elif core.is_client():
def parse_args(self): """Parse command line arguments.""" args = self.init_args().parse_args() # Load the configuration file, if it exists self.config = Config(args.conf_file) # Debug mode if args.debug: from logging import DEBUG logger.setLevel(DEBUG) # Client/server Port if args.port is None: if args.webserver: args.port = self.web_server_port else: args.port = self.server_port # Autodiscover if args.disable_autodiscover: logger.info("Auto discover mode is disabled") # In web server mode, defaul refresh time: 5 sec if args.webserver: args.time = 5 args.process_short_name = True # Server or client login/password args.username = self.username if args.password_prompt: # Interactive or file password if args.server: args.password = self.__get_password( description='Define the password for the Glances server', confirm=True) elif args.webserver: args.password = self.__get_password( description='Define the password for the Glances web server\nUser name: glances', confirm=True) elif args.client: args.password = self.__get_password( description='Enter the Glances server password', clear=True) else: # Default is no password args.password = self.password # By default help is hidden args.help_tag = False # Display Rx and Tx, not the sum for the network args.network_sum = False args.network_cumul = False # Manage full quicklook option if args.full_quicklook: args.disable_quicklook = False args.disable_cpu = True args.disable_mem = True args.disable_swap = True args.disable_load = False else: args.disable_quicklook = False args.disable_cpu = False args.disable_mem = False args.disable_swap = False args.disable_load = False # Control parameter and exit if it is not OK self.args = args # Export is only available in standalone or client mode (issue #614) export_tag = args.export_csv or args.export_statsd or args.export_influxdb or args.export_opentsdb or args.export_rabbitmq if not (self.is_standalone() or self.is_client()) and export_tag: logger.critical("Export is only available in standalone or client mode") sys.exit(2) # Filter is only available in standalone mode if args.process_filter is not None and not self.is_standalone(): logger.critical("Process filter is only available in standalone mode") sys.exit(2) # Check graph output path if args.enable_history and args.path_history is not None: if not os.access(args.path_history, os.W_OK): logger.critical("History output path {0} do not exist or is not writable".format(args.path_history)) sys.exit(2) logger.debug("History output path is set to {0}".format(args.path_history)) # Disable HDDTemp if sensors are disabled if args.disable_sensors: args.disable_hddtemp = True logger.debug("Sensors and HDDTemp are disabled") return args
def main(): """Main entry point for Glances. Select the mode (standalone, client or server) Run it... """ # Log Glances and PSutil version logger.info('Start Glances {0}'.format(__version__)) logger.info('{0} {1} and PSutil {2} detected'.format( platform.python_implementation(), platform.python_version(), __psutil_version)) # Share global var global core, standalone, client, server, webserver # Create the Glances main instance core = GlancesMain() prctl.prctl(prctl.PDEATHSIG, signal.SIGTERM) # Catch the CTRL-C signal signal.signal(signal.SIGINT, __signal_handler) # Glances can be ran in standalone, client or server mode if core.is_standalone(): logger.info("Start standalone mode") # Import the Glances standalone module from glances.core.glances_standalone import GlancesStandalone # Init the standalone mode standalone = GlancesStandalone(config=core.get_config(), args=core.get_args()) # Start the standalone (CLI) loop standalone.serve_forever() elif core.is_client(): if core.is_client_browser(): logger.info("Start client mode (browser)") # Import the Glances client browser module from glances.core.glances_client_browser import GlancesClientBrowser # Init the client client = GlancesClientBrowser(config=core.get_config(), args=core.get_args()) else: logger.info("Start client mode") # Import the Glances client module from glances.core.glances_client import GlancesClient # Init the client client = GlancesClient(config=core.get_config(), args=core.get_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() # Shutdown the client client.end() elif core.is_server(): logger.info("Start server mode") # Import the Glances server module from glances.core.glances_server import GlancesServer args = core.get_args() server = GlancesServer(cached_time=core.cached_time, config=core.get_config(), args=args) print('Glances server is running on {0}:{1}'.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() elif core.is_webserver(): logger.info("Start web server mode") # Import the Glances web server module from glances.core.glances_webserver import GlancesWebServer # Init the web server mode webserver = GlancesWebServer(config=core.get_config(), args=core.get_args()) # Start the web server loop webserver.serve_forever()
) zeroconf_tag = True except ImportError: zeroconf_tag = False # Import Glances libs from glances.core.glances_globals import appname from glances.core.glances_logging import logger # Zeroconf 0.17 or higher is needed if zeroconf_tag: zeroconf_min_version = (0, 17, 0) zeroconf_version = tuple([int(num) for num in __zeroconf_version.split('.')]) logger.debug("Zeroconf version {0} detected.".format(__zeroconf_version)) if zeroconf_version < zeroconf_min_version: logger.critical("Please install zeroconf 0.17 or higher.") sys.exit(1) # Global var zeroconf_type = "_%s._tcp." % appname class AutoDiscovered(object): """Class to manage the auto discovered servers dict.""" def __init__(self): # server_dict is a list of dict (JSON compliant) # [ {'key': 'zeroconf name', ip': '172.1.2.3', 'port': 61209, 'cpu': 3, 'mem': 34 ...} ... ] self._server_list = []
from glances.core.glances_logging import logger from glances.core.glances_main import GlancesMain # Get PSutil version psutil_min_version = (2, 0, 0) psutil_version = tuple([int(num) for num in __psutil_version.split('.')]) # First log with Glances and PSUtil version logger.info('Start Glances {0}'.format(__version__)) logger.info('{0} {1} and PSutil {2} detected'.format(platform.python_implementation(), platform.python_version(), __psutil_version)) # Check PSutil version if psutil_version < psutil_min_version: logger.critical('PSutil 2.0 or higher is needed. Glances cannot start.') sys.exit(1) def __signal_handler(signal, frame): """Callback for CTRL-C.""" end() def end(): """Stop Glances.""" if core.is_standalone(): # Stop the standalone (CLI) standalone.end() logger.info("Stop Glances (with CTRL-C)") elif core.is_client():
def main(): """Main entry point for Glances. Select the mode (standalone, client or server) Run it... """ # Log Glances and PSutil version logger.info('Start Glances {0}'.format(__version__)) logger.info('{0} {1} and PSutil {2} detected'.format( platform.python_implementation(), platform.python_version(), __psutil_version)) # Share global var global core, standalone, client, server, webserver # Create the Glances main instance core = GlancesMain() prctl.prctl(prctl.PDEATHSIG, signal.SIGTERM) # Catch the CTRL-C signal signal.signal(signal.SIGINT, __signal_handler) # Glances can be ran in standalone, client or server mode if core.is_standalone(): logger.info("Start standalone mode") # Import the Glances standalone module from glances.core.glances_standalone import GlancesStandalone # Init the standalone mode standalone = GlancesStandalone(config=core.get_config(), args=core.get_args()) # Start the standalone (CLI) loop standalone.serve_forever() elif core.is_client(): if core.is_client_browser(): logger.info("Start client mode (browser)") # Import the Glances client browser module from glances.core.glances_client_browser import GlancesClientBrowser # Init the client client = GlancesClientBrowser(config=core.get_config(), args=core.get_args()) else: logger.info("Start client mode") # Import the Glances client module from glances.core.glances_client import GlancesClient # Init the client client = GlancesClient(config=core.get_config(), args=core.get_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() # Shutdown the client client.end() elif core.is_server(): logger.info("Start server mode") # Import the Glances server module from glances.core.glances_server import GlancesServer args = core.get_args() server = GlancesServer(cached_time=core.cached_time, config=core.get_config(), args=args) print('Glances server is running on {0}:{1}'.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() elif core.is_webserver(): logger.info("Start web server mode") # Import the Glances web server module from glances.core.glances_webserver import GlancesWebServer # Init the web server mode webserver = GlancesWebServer(config=core.get_config(), args=core.get_args()) # Start the web server loop webserver.serve_forever()
def parse_args(self): """Parse command line arguments.""" args = self.init_args().parse_args() # Load the configuration file, if it exists self.config = Config(args.conf_file) # Debug mode if args.debug: from logging import DEBUG logger.setLevel(DEBUG) # Client/server Port if args.port is None: if args.webserver: args.port = self.web_server_port else: args.port = self.server_port # Autodiscover if args.disable_autodiscover: logger.info("Auto discover mode is disabled") # In web server mode, defaul refresh time: 5 sec if args.webserver: args.time = 5 args.process_short_name = True # Server or client login/password args.username = self.username if args.password_arg is not None: from hashlib import sha256 # Password is given as an argument # Hash with SHA256 # Only the SHA will be transmit on the network args.password = sha256(args.password_arg).hexdigest() elif args.password_prompt: # Interactive or file password if args.server: args.password = self.__get_password( description=_( "Define the password for the Glances server"), confirm=True) elif args.client: args.password = self.__get_password( description=_("Enter the Glances server password"), clear=True) else: # Default is no password args.password = self.password # By default help is hidden args.help_tag = False # Display Rx and Tx, not the sum for the network args.network_sum = False args.network_cumul = False # Control parameter and exit if it is not OK self.args = args # Filter is only available in standalone mode if args.process_filter is not None and not self.is_standalone(): logger.critical("Process filter is only available in standalone mode") sys.exit(2) # Check graph output path if args.enable_history and args.path_history is not None: if not os.access(args.path_history, os.W_OK): logger.critical("History output path {0} do not exist or is not writable".format(args.path_history)) sys.exit(2) logger.debug("History output path is set to {0}".format(args.path_history)) return args
def parse_args(self): """Parse command line arguments.""" args = self.init_args().parse_args() # Load the configuration file, if it exists self.config = Config(args.conf_file) # Debug mode if args.debug: from logging import DEBUG logger.setLevel(DEBUG) # Client/server Port if args.port is None: if args.webserver: args.port = self.web_server_port else: args.port = self.server_port # Autodiscover if args.disable_autodiscover: logger.info("Auto discover mode is disabled") # In web server mode, defaul refresh time: 5 sec if args.webserver: args.time = 5 args.process_short_name = True # Server or client login/password args.username = self.username if args.password_prompt: # Interactive or file password if args.server: args.password = self.__get_password( description='Define the password for the Glances server', confirm=True) elif args.webserver: args.password = self.__get_password( description= 'Define the password for the Glances web server\nUser name: glances', confirm=True) elif args.client: args.password = self.__get_password( description='Enter the Glances server password', clear=True) else: # Default is no password args.password = self.password # By default help is hidden args.help_tag = False # Display Rx and Tx, not the sum for the network args.network_sum = False args.network_cumul = False # Manage full quicklook option if args.full_quicklook: args.disable_quicklook = False args.disable_cpu = True args.disable_mem = True args.disable_swap = True args.disable_load = False else: args.disable_quicklook = False args.disable_cpu = False args.disable_mem = False args.disable_swap = False args.disable_load = False # Control parameter and exit if it is not OK self.args = args # Export is only available in standalone or client mode (issue #614) export_tag = args.export_csv or args.export_statsd or args.export_influxdb or args.export_opentsdb or args.export_rabbitmq if not (self.is_standalone() or self.is_client()) and export_tag: logger.critical( "Export is only available in standalone or client mode") sys.exit(2) # Filter is only available in standalone mode if args.process_filter is not None and not self.is_standalone(): logger.critical( "Process filter is only available in standalone mode") sys.exit(2) # Check graph output path if args.enable_history and args.path_history is not None: if not os.access(args.path_history, os.W_OK): logger.critical( "History output path {0} do not exist or is not writable". format(args.path_history)) sys.exit(2) logger.debug("History output path is set to {0}".format( args.path_history)) # Disable HDDTemp if sensors are disabled if args.disable_sensors: args.disable_hddtemp = True logger.debug("Sensors and HDDTemp are disabled") return args
# You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Web interface class.""" import json import os import sys # Import Glances libs from glances.core.glances_logging import logger # Import mandatory Bottle lib try: from bottle import Bottle, template, static_file, TEMPLATE_PATH, abort, response except ImportError: logger.critical( 'Bottle module not found. Glances cannot start in web server mode.') sys.exit(2) class GlancesBottle(object): """This class manages the Bottle Web server.""" def __init__(self, args=None): # Init args self.args = args # Init stats # Will be updated within Bottle route self.stats = None # Init Bottle self._app = Bottle()