Ejemplo n.º 1
0
    def _port_scan_tcp(self, port):
        """Scan the (TCP) port structure (dict) and update the status key."""
        ret = None

        # Create and configure the scanning socket
        try:
            socket.setdefaulttimeout(port['timeout'])
            _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except Exception as e:
            logger.debug("{}: Error while creating scanning socket".format(
                self.plugin_name))

        # Scan port
        ip = self._resolv_name(port['host'])
        counter = Counter()
        try:
            ret = _socket.connect_ex((ip, int(port['port'])))
        except Exception as e:
            logger.debug("{}: Error while scanning port {} ({})".format(
                self.plugin_name, port, e))
        else:
            if ret == 0:
                port['status'] = counter.get()
            else:
                port['status'] = False
        finally:
            _socket.close()

        return ret
Ejemplo n.º 2
0
    def _port_scan_icmp(self, port):
        """Scan the (ICMP) port structure (dict) and update the status key"""
        ret = None

        # Create the ping command
        # Use the system ping command because it already have the steacky bit set
        # Python can not create ICMP packet with non root right
        cmd = [
            'ping', '-n' if WINDOWS else '-c', '1',
            self._resolv_name(port['host'])
        ]
        fnull = open(os.devnull, 'w')

        try:
            counter = Counter()
            ret = subprocess.check_call(cmd,
                                        stdout=fnull,
                                        stderr=fnull,
                                        close_fds=True)
            if ret == 0:
                port['status'] = counter.get()
            else:
                port['status'] = False
        except Exception as e:
            logger.debug("{}: Error while pinging host {} ({})".format(
                self.plugin_name, port['host'], e))

        return ret
Ejemplo n.º 3
0
def start(config, args):
    """Start Glances."""

    # Load mode
    global mode

    start_duration = Counter()

    if core.is_standalone():
        from glances.standalone import GlancesStandalone as GlancesMode
    elif core.is_client():
        if core.is_client_browser():
            from glances.client_browser import GlancesClientBrowser as GlancesMode
        else:
            from glances.client import GlancesClient as GlancesMode
    elif core.is_server():
        from glances.server import GlancesServer as GlancesMode
    elif core.is_webserver():
        from glances.webserver import GlancesWebServer as GlancesMode

    # Init the mode
    logger.info("Start {} mode".format(GlancesMode.__name__))
    mode = GlancesMode(config=config, args=args)

    # Start the main loop
    logger.debug("Glances started in {} seconds".format(start_duration.get()))
    mode.serve_forever()

    # Shutdown
    mode.end()
Ejemplo n.º 4
0
    def __init__(self, args=None, config=None):
        """Init the plugin."""
        super(Plugin, self).__init__(args=args,
                                     config=config,
                                     stats_init_value=[])

        start_duration = Counter()

        # Init the sensor class
        start_duration.reset()
        self.glancesgrabsensors = GlancesGrabSensors()
        logger.debug("Generic sensor plugin init duration: {} seconds".format(
            start_duration.get()))

        # Instance for the HDDTemp Plugin in order to display the hard disks
        # temperatures
        start_duration.reset()
        self.hddtemp_plugin = HddTempPlugin(args=args, config=config)
        logger.debug("HDDTemp sensor plugin init duration: {} seconds".format(
            start_duration.get()))

        # Instance for the BatPercent in order to display the batteries
        # capacities
        start_duration.reset()
        self.batpercent_plugin = BatPercentPlugin(args=args, config=config)
        logger.debug("Battery sensor plugin init duration: {} seconds".format(
            start_duration.get()))

        # We want to display the stat in the curse interface
        self.display_curse = True
Ejemplo n.º 5
0
 def wrapper(*args, **kw):
     counter = Counter()
     ret = fct(*args, **kw)
     duration = counter.get()
     logger.debug("%s %s %s return %s in %s seconds" %
                  (args[0].__class__.__name__,
                   args[0].__class__.__module__[len('glances_'):],
                   fct.__name__, ret, duration))
     return ret
Ejemplo n.º 6
0
    def __serve_forever(self):
        """Main loop for the CLI.

        return True if we should continue (no exit key has been pressed)
        """
        # Start a counter used to compute the time needed for
        # update and export the stats
        counter = Counter()

        # Update stats
        self.stats.update()
        logger.debug('Stats updated duration: {} seconds'.format(
            counter.get()))

        # Export stats
        counter_export = Counter()
        self.stats.export(self.stats)
        logger.debug('Stats exported duration: {} seconds'.format(
            counter_export.get()))

        # Patch for issue1326 to avoid < 0 refresh
        adapted_refresh = self.refresh_time - counter.get()
        adapted_refresh = adapted_refresh if adapted_refresh > 0 else 0

        # Display stats
        # and wait refresh_time - counter
        if not self.quiet:
            # The update function return True if an exit key 'q' or 'ESC'
            # has been pressed.
            ret = not self.screen.update(self.stats, duration=adapted_refresh)
        else:
            # Nothing is displayed
            # Break should be done via a signal (CTRL-C)
            time.sleep(adapted_refresh)
            ret = True

        return ret
Ejemplo n.º 7
0
 def update(self):
     """Wrapper method to update the stats."""
     # For standalone and server modes
     # For each plugins, call the update method
     for p in self._plugins:
         if self._plugins[p].is_disable():
             # If current plugin is disable
             # then continue to next plugin
             continue
         start_duration = Counter()
         # Update the stats...
         self._plugins[p].update()
         # ... the history
         self._plugins[p].update_stats_history()
         # ... and the views
         self._plugins[p].update_views()
Ejemplo n.º 8
0
    def load_plugins(self, args=None):
        """Load all plugins in the 'plugins' folder."""
        start_duration = Counter()
        for item in os.listdir(plugins_path):
            if (item.startswith(self.header) and
                    item.endswith(".py") and
                    item != (self.header + "plugin.py")):
                # Load the plugin
                start_duration.reset()
                self._load_plugin(os.path.basename(item),
                                  args=args, config=self.config)
                logger.debug("Plugin {} started in {} seconds".format(item,
                                                                      start_duration.get()))

        # Log plugins list
        logger.debug("Active plugins list: {}".format(self.getPluginsList()))
Ejemplo n.º 9
0
    def _port_scan_icmp(self, port):
        """Scan the (ICMP) port structure (dict) and update the status key."""
        ret = None

        # Create the ping command
        # Use the system ping command because it already have the steacky bit set
        # Python can not create ICMP packet with non root right
        if WINDOWS:
            timeout_opt = '-w'
            count_opt = '-n'
        elif MACOS or BSD:
            timeout_opt = '-t'
            count_opt = '-c'
        else:
            # Linux and co...
            timeout_opt = '-W'
            count_opt = '-c'
        # Build the command line
        # Note: Only string are allowed
        cmd = [
            'ping', count_opt, '1', timeout_opt,
            str(self._resolv_name(port['timeout'])),
            self._resolv_name(port['host'])
        ]
        fnull = open(os.devnull, 'w')

        try:
            counter = Counter()
            ret = subprocess.check_call(cmd,
                                        stdout=fnull,
                                        stderr=fnull,
                                        close_fds=True)
            if ret == 0:
                port['status'] = counter.get()
            else:
                port['status'] = False
        except subprocess.CalledProcessError as e:
            # Correct issue #1084: No Offline status for timeouted ports
            port['status'] = False
        except Exception as e:
            logger.debug("{}: Error while pinging host {} ({})".format(
                self.plugin_name, port['host'], e))

        return ret
Ejemplo n.º 10
0
    def update(self, stats, duration=3):
        """Display issue
        """
        self.print_version()
        for plugin in sorted(stats._plugins):
            if stats._plugins[plugin].is_disable():
                # If current plugin is disable
                # then continue to next plugin
                result = colors.ORANGE + '[N/A]'.rjust(19 - len(plugin))
                message = colors.NO
                self.print_issue(plugin, result, message)
                continue
            # Start the counter
            counter = Counter()
            counter.reset()
            stat = None
            stat_error = None
            try:
                # Update the stats
                stats._plugins[plugin].update()
                # Get the stats
                stat = stats.get_plugin(plugin).get_export()
            except Exception as e:
                stat_error = e
            if stat_error is None:
                result = (colors.GREEN + '[OK]   ' + colors.BLUE +
                          ' {:.4f}s '.format(counter.get())).rjust(40 -
                                                                   len(plugin))
                message = colors.NO + str(stat)[0:TERMINAL_WIDTH - 40]
            else:
                result = (colors.RED + '[ERROR]' + colors.BLUE +
                          ' {:.4f}s '.format(counter.get())).rjust(40 -
                                                                   len(plugin))
                message = colors.NO + str(stat_error)[0:TERMINAL_WIDTH - 40]
            self.print_issue(plugin, result, message)

        # Return True to exit directly (no refresh)
        return True
Ejemplo n.º 11
0
    def __init__(self, config=None, args=None):
        self.config = config
        self.args = args

        # Quiet mode
        self._quiet = args.quiet
        self.refresh_time = args.time

        # Init stats
        start_duration = Counter()
        start_duration.reset()
        self.stats = GlancesStats(config=config, args=args)
        logger.debug("Plugins initialisation duration: {} seconds".format(
            start_duration.get()))

        # Modules (plugins and exporters) are loaded at this point
        # Glances can display the list if asked...
        if args.modules_list:
            self.display_modules_list()
            sys.exit(0)

        # If process extended stats is disabled by user
        if not args.enable_process_extended:
            logger.debug("Extended stats for top process are disabled")
            glances_processes.disable_extended()
        else:
            logger.debug("Extended stats for top process are enabled")
            glances_processes.enable_extended()

        # Manage optionnal process filter
        if args.process_filter is not None:
            glances_processes.process_filter = args.process_filter

        if (not WINDOWS) and args.no_kernel_threads:
            # Ignore kernel threads in process list
            glances_processes.disable_kernel_threads()

        # Initial system informations update
        start_duration.reset()
        self.stats.update()
        logger.debug("First stats update duration: {} seconds".format(
            start_duration.get()))

        if self.quiet:
            logger.info("Quiet mode is ON, nothing will be displayed")
            # In quiet mode, nothing is displayed
            glances_processes.max_processes = 0
        elif args.stdout:
            logger.info(
                "Stdout mode is ON, following stats will be displayed: {}".
                format(args.stdout))
            # Init screen
            self.screen = GlancesStdout(config=config, args=args)
        elif args.stdout_csv:
            logger.info(
                "Stdout CSV mode is ON, following stats will be displayed: {}".
                format(args.stdout))
            # Init screen
            self.screen = GlancesStdoutCsv(config=config, args=args)
        else:
            # Default number of processes to displayed is set to 50
            glances_processes.max_processes = 50

            # Init screen
            self.screen = GlancesCursesStandalone(config=config, args=args)

        # Check the latest Glances version
        self.outdated = Outdated(config=config, args=args)