class GlancesClient(object): """This class creates and manages the TCP client.""" def __init__(self, config=None, args=None): # Store the arg/config self.args = args self.config = config # Client mode: self.set_mode() # Build the URI if args.password != "": uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, args.client, args.port) else: uri = 'http://{0}:{1}'.format(args.client, args.port) # Try to connect to the URI transport = GlancesClientTransport() # Configure the server timeout to 7 seconds transport.set_timeout(7) try: self.client = ServerProxy(uri, transport=transport) except Exception as e: logger.error(_("Couldn't create socket {0}: {1}").format(uri, e)) sys.exit(2) def set_mode(self, mode='glances'): """Set the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ self.mode = mode return self.mode def get_mode(self): """Get the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ return self.mode def login(self): """Logon to the server.""" ret = True if not self.args.snmp_force: # First of all, trying to connect to a Glances server self.set_mode('glances') client_version = None try: client_version = self.client.init() except socket.error as err: # Fallback to SNMP logger.error(_("Connection to Glances server failed")) self.set_mode('snmp') fallbackmsg = _("Trying fallback to SNMP...") print(fallbackmsg) except ProtocolError as err: # Others errors if str(err).find(" 401 ") > 0: logger.error( _("Connection to server failed (Bad password)")) else: logger.error( _("Connection to server failed ({0})").format(err)) sys.exit(2) if self.get_mode( ) == 'glances' and version[:3] == client_version[:3]: # Init stats self.stats = GlancesStatsClient() self.stats.set_plugins(json.loads(self.client.getAllPlugins())) else: logger.error("Client version: %s / Server version: %s" % (version, client_version)) else: self.set_mode('snmp') if self.get_mode() == 'snmp': logger.info(_("Trying to grab stats by SNMP...")) # Fallback to SNMP if needed from glances.core.glances_stats import GlancesStatsClientSNMP # Init stats self.stats = GlancesStatsClientSNMP(args=self.args) if not self.stats.check_snmp(): logger.error(_("Connection to SNMP server failed")) sys.exit(2) if ret: # Load limits from the configuration file # Each client can choose its owns limits self.stats.load_limits(self.config) # Init screen self.screen = GlancesCurses(args=self.args) # Return result return ret 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 update_glances(self): """Get stats from Glances server. Return the client/server connection status: - Connected: Connection OK - Disconnected: Connection NOK """ # Update the stats try: server_stats = json.loads(self.client.getAll()) server_stats['monitor'] = json.loads(self.client.getAllMonitored()) except socket.error: # Client cannot get server stats return "Disconnected" except Fault: # Client cannot get server stats (issue #375) return "Disconnected" else: # Put it in the internal dict self.stats.update(server_stats) return "Connected" def update_snmp(self): """Get stats from SNMP server. Return the client/server connection status: - SNMP: Connection with SNMP server OK - Disconnected: Connection NOK """ # Update the stats try: self.stats.update() except: # Client can not get SNMP server stats return "Disconnected" else: # Grab success return "SNMP" def serve_forever(self): """Main client loop.""" while True: # Update the stats cs_status = self.update() # Update the screen self.screen.update(self.stats, cs_status=cs_status) def end(self): """End of the client session.""" self.screen.end()
class GlancesClient(object): """This class creates and manages the TCP client.""" def __init__(self, config=None, args=None, timeout=7, return_to_browser=False): # Store the arg/config self.args = args self.config = config # Client mode: self.set_mode() # Build the URI if args.password != "": uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, args.client, args.port) else: uri = 'http://{0}:{1}'.format(args.client, args.port) logger.debug("Try to connect to {0}".format(uri)) # Try to connect to the URI transport = GlancesClientTransport() # Configure the server timeout transport.set_timeout(timeout) try: self.client = ServerProxy(uri, transport=transport) except Exception as e: msg = "Client couldn't create socket {0}: {1}".format(uri, e) if not return_to_browser: logger.critical(msg) sys.exit(2) else: logger.error(msg) def set_mode(self, mode='glances'): """Set the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ self.mode = mode return self.mode def get_mode(self): """Get the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ return self.mode def login(self, return_to_browser=False): """Logon to the server.""" ret = True if not self.args.snmp_force: # First of all, trying to connect to a Glances server self.set_mode('glances') client_version = None try: client_version = self.client.init() except socket.error as err: # Fallback to SNMP logger.error("Connection to Glances server failed (%s)" % err) self.set_mode('snmp') fallbackmsg = _("Trying fallback to SNMP...") if not return_to_browser: print(fallbackmsg) else: logger.info(fallbackmsg) except ProtocolError as err: # Others errors if str(err).find(" 401 ") > 0: msg = "Connection to server failed (bad password)" else: msg = "Connection to server failed ({0})".format(err) if not return_to_browser: logger.critical(msg) sys.exit(2) else: logger.error(msg) return False if self.get_mode() == 'glances' and version[:3] == client_version[:3]: # Init stats self.stats = GlancesStatsClient() self.stats.set_plugins(json.loads(self.client.getAllPlugins())) logger.debug( "Client version: %s / Server version: %s" % (version, client_version)) else: logger.error( "Client and server not compatible: Client version: %s / Server version: %s" % (version, client_version)) else: self.set_mode('snmp') if self.get_mode() == 'snmp': logger.info("Trying to grab stats by SNMP...") # Fallback to SNMP if needed from glances.core.glances_stats import GlancesStatsClientSNMP # Init stats self.stats = GlancesStatsClientSNMP(args=self.args) if not self.stats.check_snmp(): logger.error("Connection to SNMP server failed") if not return_to_browser: sys.exit(2) else: return False if ret: # Load limits from the configuration file # Each client can choose its owns limits self.stats.load_limits(self.config) # Init screen self.screen = GlancesCursesClient(args=self.args) # Return result return ret 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 update_glances(self): """Get stats from Glances server. Return the client/server connection status: - Connected: Connection OK - Disconnected: Connection NOK """ # Update the stats try: server_stats = json.loads(self.client.getAll()) server_stats['monitor'] = json.loads(self.client.getAllMonitored()) except socket.error: # Client cannot get server stats return "Disconnected" except Fault: # Client cannot get server stats (issue #375) return "Disconnected" else: # Put it in the internal dict self.stats.update(server_stats) return "Connected" def update_snmp(self): """Get stats from SNMP server. Return the client/server connection status: - SNMP: Connection with SNMP server OK - Disconnected: Connection NOK """ # Update the stats try: self.stats.update() except Exception: # Client cannot get SNMP server stats return "Disconnected" else: # Grab success return "SNMP" def serve_forever(self, return_to_browser=False): """Main client loop.""" exitkey = False 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=return_to_browser) return self.get_mode() def end(self): """End of the client session.""" self.screen.end()
class GlancesClient(object): """This class creates and manages the TCP client.""" def __init__(self, config=None, args=None): # Store the arg/config self.args = args self.config = config # Client mode: self.set_mode() # Build the URI if args.password != "": uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, args.client, args.port) else: uri = 'http://{0}:{1}'.format(args.client, args.port) # Try to connect to the URI try: self.client = ServerProxy(uri) except Exception as e: print(_("Error: Couldn't create socket {0}: {1}").format(uri, e)) sys.exit(2) def set_mode(self, mode='glances'): """Set the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ self.mode = mode return self.mode def get_mode(self): """Get the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ return self.mode def login(self): """Logon to the server.""" ret = True # First of all, trying to connect to a Glances server try: client_version = self.client.init() self.set_mode('glances') except socket.error as err: # print(_("Error: Connection to {0} server failed").format(self.get_mode())) # Fallback to SNMP self.set_mode('snmp') except ProtocolError as err: # Others errors if str(err).find(" 401 ") > 0: print(_("Error: Connection to server failed: Bad password")) else: print(_("Error: Connection to server failed: {0}").format(err)) sys.exit(2) if self.get_mode() == 'glances' and version[:3] == client_version[:3]: # Init stats self.stats = GlancesStatsClient() self.stats.set_plugins(json.loads(self.client.getAllPlugins())) elif self.get_mode() == 'snmp': print (_("Info: Connection to Glances server failed. Trying fallback to SNMP...")) # Then fallback to SNMP if needed from glances.core.glances_stats import GlancesStatsClientSNMP # Init stats self.stats = GlancesStatsClientSNMP(args=self.args) if not self.stats.check_snmp(): print(_("Error: Connection to SNMP server failed")) sys.exit(2) else: ret = False if ret: # Load limits from the configuration file # Each client can choose its owns limits self.stats.load_limits(self.config) # Init screen self.screen = GlancesCurses(args=self.args) # Return result return ret 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: print(_("Error: Unknown server mode: {0}").format(self.get_mode())) sys.exit(2) def update_glances(self): """Get stats from Glances server. Return the client/server connection status: - Connected: Connection OK - Disconnected: Connection NOK """ # Update the stats try: server_stats = json.loads(self.client.getAll()) server_stats['monitor'] = json.loads(self.client.getAllMonitored()) except socket.error: # Client cannot get server stats return "Disconnected" except Fault: # Client cannot get server stats (issue #375) return "Disconnected" else: # Put it in the internal dict self.stats.update(server_stats) return "Connected" def update_snmp(self): """Get stats from SNMP server. Return the client/server connection status: - SNMP: Connection with SNMP server OK - Disconnected: Connection NOK """ # Update the stats try: self.stats.update() except: # Client can not get SNMP server stats return "Disconnected" else: # Grab success return "SNMP" def serve_forever(self): """Main client loop.""" while True: # Update the stats cs_status = self.update() # Update the screen self.screen.update(self.stats, cs_status=cs_status) # print self.stats # print self.stats.getAll() def end(self): """End of the client session.""" self.screen.end()
class GlancesClient(object): """This class creates and manages the TCP client.""" def __init__(self, config=None, args=None, timeout=7, return_to_browser=False): # Store the arg/config self.args = args self.config = config # Default client mode self._client_mode = 'glances' # Return to browser or exit self.return_to_browser = return_to_browser # Build the URI if args.password != "": uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, args.client, args.port) else: uri = 'http://{0}:{1}'.format(args.client, args.port) logger.debug("Try to connect to {0}".format(uri)) # Try to connect to the URI transport = GlancesClientTransport() # Configure the server timeout transport.set_timeout(timeout) try: self.client = ServerProxy(uri, transport=transport) except Exception as e: self.log_and_exit("Client couldn't create socket {0}: {1}".format( uri, e)) 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) @property def client_mode(self): """Get the client mode.""" return self._client_mode @client_mode.setter def client_mode(self, mode): """Set the client mode. - 'glances' = Glances server (default) - 'snmp' = SNMP (fallback) """ self._client_mode = mode def login(self): """Logon to the server.""" ret = True if not self.args.snmp_force: # First of all, trying to connect to a Glances server client_version = None try: client_version = self.client.init() except socket.error as err: # Fallback to SNMP self.client_mode = 'snmp' logger.error( "Connection to Glances server failed: {0}".format(err)) fallbackmsg = 'No Glances server found. Trying fallback to SNMP...' if not self.return_to_browser: print(fallbackmsg) else: logger.info(fallbackmsg) except ProtocolError as err: # Others errors if str(err).find(" 401 ") > 0: msg = "Connection to server failed (bad password)" else: msg = "Connection to server failed ({0})".format(err) self.log_and_exit(msg) return False if self.client_mode == 'glances': # Check that both client and server are in the same major version if version.split('.')[0] == client_version.split('.')[0]: # Init stats self.stats = GlancesStatsClient(config=self.config, args=self.args) self.stats.set_plugins( json.loads(self.client.getAllPlugins())) logger.debug( "Client version: {0} / Server version: {1}".format( version, client_version)) else: self.log_and_exit("Client and server not compatible: \ Client version: {0} / Server version: {1}" .format(version, client_version)) return False else: self.client_mode = 'snmp' # SNMP mode if self.client_mode == 'snmp': logger.info("Trying to grab stats by SNMP...") from glances.core.glances_stats import GlancesStatsClientSNMP # Init stats self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) if not self.stats.check_snmp(): self.log_and_exit("Connection to SNMP server failed") return False if ret: # Load limits from the configuration file # Each client can choose its owns limits self.stats.load_limits(self.config) # Init screen self.screen = GlancesCursesClient(args=self.args) # Return result return ret 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_glances(self): """Get stats from Glances server. Return the client/server connection status: - Connected: Connection OK - Disconnected: Connection NOK """ # Update the stats try: server_stats = json.loads(self.client.getAll()) server_stats['monitor'] = json.loads(self.client.getAllMonitored()) except socket.error: # Client cannot get server stats return "Disconnected" except Fault: # Client cannot get server stats (issue #375) return "Disconnected" else: # Put it in the internal dict self.stats.update(server_stats) return "Connected" def update_snmp(self): """Get stats from SNMP server. Return the client/server connection status: - SNMP: Connection with SNMP server OK - Disconnected: Connection NOK """ # Update the stats try: self.stats.update() except Exception: # Client cannot get SNMP server stats return "Disconnected" else: # Grab success return "SNMP" 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 end(self): """End of the client session.""" self.screen.end()