Example #1
0
    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)
Example #2
0
 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)
Example #3
0
 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)
Example #4
0
    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, but passwords did not match..."))
                    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
Example #5
0
    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_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
Example #7
0
    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(
                _("Error: Cannot create the CSV file: {0}").format(e))
            sys.exit(2)

        logger.info(
            _("Stats dumped to CSV file: {0}").format(self.csv_filename))
Example #8
0
# 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

from glances.core.glances_globals import logger

import msvcrt
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()
Example #9
0
    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
Example #10
0
# 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 os
import sys

# Import Glances libs
from glances.core.glances_globals 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.')
    print(_("Install it using pip: # pip install bottle"))
    sys.exit(2)
import json


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
Example #11
0
# 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_globals import logger

# Import mandatory PySNMP lib
try:
    from pysnmp.entity.rfc3413.oneliner import cmdgen
except ImportError:
    logger.critical(_("PySNMP library not found."))
    print(_("Install it using pip: # 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__()
Example #12
0
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():
        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.close()

    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()
Example #13
0
from glances.core.glances_globals import gettext_domain, locale_dir, 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():
Example #14
0
    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(_("Error: 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:
                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:
                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')
            from glances.outputs.glances_history import GlancesHistory
            self.glances_history = GlancesHistory()
            if not self.glances_history.graph_enabled():
                args.enable_history = False
                logger.error(
                    'Stats history disabled because graph lib is not available'
                )
Example #15
0
# Import system lib
import sys

# Import Glances lib
from glances.core.glances_globals import glances_logs, glances_processes, is_linux, is_bsd, is_mac, is_windows, logger
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, rectangle
    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)."""
    def __init__(self, args=None):
        # Init args
        self.args = args

        # Init windows positions
        self.term_w = 80
Example #16
0
# 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_globals import logger

# Import mandatory PySNMP lib
try:
    from pysnmp.entity.rfc3413.oneliner import cmdgen
except ImportError:
    logger.critical(_("PySNMP library not found."))
    print(_("Install it using pip: # 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
Example #17
0
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():
        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.close()

    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
    )
    zeroconf_tag = True
except ImportError:
    zeroconf_tag = False

# Import Glances libs
from glances.core.glances_globals import appname, 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 = []
Example #19
0
# Import system lib
import sys

# Import Glances lib
from glances.core.glances_globals import glances_logs, glances_processes, is_mac, is_windows, logger
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
Example #20
0
from glances.core.glances_globals import gettext_domain, locale_dir, 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():
Example #21
0
    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.outputs.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')
# 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_globals 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()
Example #23
0
    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

        # 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