本文整理汇总了Python中glances.timer.Timer.finished方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.finished方法的具体用法?Python Timer.finished怎么用?Python Timer.finished使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类glances.timer.Timer
的用法示例。
在下文中一共展示了Timer.finished方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def update(self, servers_list):
"""Update the servers' list screen.
Wait for __refresh_time sec / catch key every 100 ms.
servers_list: Dict of dict with servers stats
"""
# Flush display
logger.debug("Servers list: {}".format(servers_list))
self.flush(servers_list)
# Wait
exitkey = False
countdown = Timer(self.__refresh_time)
while not countdown.finished() and not exitkey:
# Getkey
pressedkey = self.__catch_key(servers_list)
# Is it an exit or select server key ?
exitkey = pressedkey == ord("\x1b") or pressedkey == ord("q") or pressedkey == 10
if not exitkey and pressedkey > -1:
# Redraw display
self.flush(servers_list)
# Wait 100ms...
self.wait()
return self.active_server
示例2: update
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def update(self,
stats,
duration=3,
cs_status=None,
return_to_browser=False):
"""Update the servers' list screen.
Wait for __refresh_time sec / catch key every 100 ms.
stats: Dict of dict with servers stats
"""
# Flush display
logger.debug('Servers list: {}'.format(stats))
self.flush(stats)
# Wait
exitkey = False
countdown = Timer(self.__refresh_time)
while not countdown.finished() and not exitkey:
# Getkey
pressedkey = self.__catch_key(stats)
# Is it an exit or select server key ?
exitkey = (
pressedkey == ord('\x1b') or pressedkey == ord('q') or pressedkey == 10)
if not exitkey and pressedkey > -1:
# Redraw display
self.flush(stats)
# Wait 100ms...
self.wait()
return self.active_server
示例3: update
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def update(self,
stats,
duration=3,
cs_status=None,
return_to_browser=False):
"""Update the screen.
INPUT
stats: Stats database to display
duration: duration of the loop
cs_status:
"None": standalone or server mode
"Connected": Client is connected to the server
"Disconnected": Client is disconnected from the server
return_to_browser:
True: Do not exist, return to the browser list
False: Exit and return to the shell
OUTPUT
True: Exit key has been pressed
False: Others cases...
"""
# Flush display
self.flush(stats, cs_status=cs_status)
# If the duration is < 0 (update + export time > refresh_time)
# Then display the interface and log a message
if duration <= 0:
logger.warning('Update and export time higher than refresh_time.')
duration = 0.1
# Wait duration (in s) time
exitkey = False
countdown = Timer(duration)
# Set the default timeout (in ms) for the getch method
self.term_window.timeout(int(duration * 1000))
while not countdown.finished() and not exitkey:
# Getkey
pressedkey = self.__catch_key(return_to_browser=return_to_browser)
# Is it an exit key ?
exitkey = (pressedkey == ord('\x1b') or pressedkey == ord('q'))
if not exitkey and pressedkey > -1:
# Redraw display
self.flush(stats, cs_status=cs_status)
# Overwrite the timeout with the countdown
self.term_window.timeout(int(countdown.get() * 1000))
return exitkey
示例4: update
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def update(self,
stats,
duration=3,
cs_status=None,
return_to_browser=False):
"""Update the screen.
Catch key every 100 ms.
INPUT
stats: Stats database to display
duration: duration of the loop
cs_status:
"None": standalone or server mode
"Connected": Client is connected to the server
"Disconnected": Client is disconnected from the server
return_to_browser:
True: Do not exist, return to the browser list
False: Exit and return to the shell
OUPUT
True: Exit key has been pressed
False: Others cases...
"""
# Flush display
self.flush(stats, cs_status=cs_status)
# If the duration is < 0 (update + export time > refresh_time)
# Then display the interface and log a message
if duration <= 0:
logger.debug('Update and export time higher than refresh_time.')
duration = 0.1
# Wait
exitkey = False
countdown = Timer(duration)
while not countdown.finished() and not exitkey:
# Getkey
pressedkey = self.__catch_key(return_to_browser=return_to_browser)
# Is it an exit key ?
exitkey = (pressedkey == ord('\x1b') or pressedkey == ord('q'))
if not exitkey and pressedkey > -1:
# Redraw display
self.flush(stats, cs_status=cs_status)
# Wait 100ms...
self.wait()
return exitkey
示例5: get
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def get(self):
"""Get the first public IP address returned by one of the online services"""
q = queue.Queue()
for u, j, k in urls:
t = threading.Thread(target=self._get_ip_public, args=(q, u, j, k))
t.daemon = True
t.start()
timer = Timer(self.timeout)
ip = None
while not timer.finished() and ip is None:
if q.qsize() > 0:
ip = q.get()
return ip
示例6: update
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
def update(self, stats, cs_status=None, return_to_browser=False):
"""Update the screen.
Wait for __refresh_time sec / catch key every 100 ms.
INPUT
stats: Stats database to display
cs_status:
"None": standalone or server mode
"Connected": Client is connected to the server
"Disconnected": Client is disconnected from the server
return_to_browser:
True: Do not exist, return to the browser list
False: Exit and return to the shell
OUPUT
True: Exit key has been pressed
False: Others cases...
"""
# Flush display
self.flush(stats, cs_status=cs_status)
# Wait
exitkey = False
countdown = Timer(self.__refresh_time)
while not countdown.finished() and not exitkey:
# Getkey
pressedkey = self.__catch_key(return_to_browser=return_to_browser)
# Is it an exit key ?
exitkey = (pressedkey == ord('\x1b') or pressedkey == ord('q'))
if not exitkey and pressedkey > -1:
# Redraw display
self.flush(stats, cs_status=cs_status)
# Wait 100ms...
self.wait()
return exitkey
示例7: GlancesInstance
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class GlancesInstance(object):
"""All the methods of this class are published as XML-RPC methods."""
def __init__(self, cached_time=1, config=None):
# Init stats
self.stats = GlancesStatsServer(config)
# Initial update
self.stats.update()
# cached_time is the minimum time interval between stats updates
# i.e. XML/RPC calls will not retrieve updated info until the time
# since last update is passed (will retrieve old cached info instead)
self.timer = Timer(0)
self.cached_time = cached_time
def __update__(self):
# Never update more than 1 time per cached_time
if self.timer.finished():
self.stats.update()
self.timer = Timer(self.cached_time)
def init(self):
# Return the Glances version
return __version__
def getAll(self):
# Update and return all the stats
self.__update__()
return json.dumps(self.stats.getAll())
def getAllPlugins(self):
# Return the plugins list
return json.dumps(self.stats.getAllPlugins())
def getAllLimits(self):
# Return all the plugins limits
return json.dumps(self.stats.getAllLimitsAsDict())
def getAllViews(self):
# Return all the plugins views
return json.dumps(self.stats.getAllViewsAsDict())
def __getattr__(self, item):
"""Overwrite the getattr method in case of attribute is not found.
The goal is to dynamically generate the API get'Stats'() methods.
"""
header = 'get'
# Check if the attribute starts with 'get'
if item.startswith(header):
try:
# Update the stat
self.__update__()
# Return the attribute
return getattr(self.stats, item)
except Exception:
# The method is not found for the plugin
raise AttributeError(item)
else:
# Default behavior
raise AttributeError(item)
示例8: GlancesActions
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class GlancesActions(object):
"""This class manage action if an alert is reached."""
def __init__(self, args=None):
"""Init GlancesActions class."""
# Dict with the criticity status
# - key: stat_name
# - value: criticity
# Goal: avoid to execute the same command twice
self.status = {}
# Add a timer to avoid any trigger when Glances is started (issue#732)
# Action can be triggered after refresh * 2 seconds
if hasattr(args, 'time'):
self.start_timer = Timer(args.time * 2)
else:
self.start_timer = Timer(3)
def get(self, stat_name):
"""Get the stat_name criticity."""
try:
return self.status[stat_name]
except KeyError:
return None
def set(self, stat_name, criticity):
"""Set the stat_name to criticity."""
self.status[stat_name] = criticity
def run(self, stat_name, criticity, commands, repeat, mustache_dict=None):
"""Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the action
- mustache_dict: Plugin stats (can be use within {{mustache}})
Return True if the commands have been ran.
"""
if (self.get(stat_name) == criticity and not repeat) or \
not self.start_timer.finished():
# Action already executed => Exit
return False
logger.debug("{} action {} for {} ({}) with stats {}".format(
"Repeat" if repeat else "Run",
commands, stat_name, criticity, mustache_dict))
# Run all actions in background
for cmd in commands:
# Replace {{arg}} by the dict one (Thk to {Mustache})
if pystache_tag:
cmd_full = pystache.render(cmd, mustache_dict)
else:
cmd_full = cmd
# Execute the action
logger.info("Action triggered for {} ({}): {}".format(stat_name, criticity, cmd_full))
logger.debug("Stats value for the trigger: {}".format(mustache_dict))
try:
Popen(cmd_full, shell=True)
except OSError as e:
logger.error("Can't execute the action ({})".format(e))
self.set(stat_name, criticity)
return True
示例9: GlancesAmp
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
#.........这里部分代码省略.........
if self.enable():
for k in ['regex', 'refresh']:
if k not in self.configs:
logger.warning("AMP - {}: Can not find configuration key {} in section {}".format(self.NAME, k, self.amp_name))
self.configs['enable'] = 'false'
else:
logger.debug("AMP - {} is disabled".format(self.NAME))
# Init the count to 0
self.configs['count'] = 0
return self.enable()
def get(self, key):
"""Generic method to get the item in the AMP configuration"""
if key in self.configs:
return self.configs[key]
else:
return None
def enable(self):
"""Return True|False if the AMP is enabled in the configuration file (enable=true|false)."""
ret = self.get('enable')
if ret is None:
return False
else:
return ret.lower().startswith('true')
def regex(self):
"""Return regular expression used to identified the current application."""
return self.get('regex')
def refresh(self):
"""Return refresh time in seconds for the current application monitoring process."""
return self.get('refresh')
def one_line(self):
"""Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false)."""
ret = self.get('one_line')
if ret is None:
return False
else:
return ret.lower().startswith('true')
def time_until_refresh(self):
"""Return time in seconds until refresh."""
return self.timer.get()
def should_update(self):
"""Return True is the AMP should be updated:
- AMP is enable
- only update every 'refresh' seconds
"""
if self.timer.finished():
self.timer.set(self.refresh())
self.timer.reset()
return self.enable()
return False
def set_count(self, count):
"""Set the number of processes matching the regex"""
self.configs['count'] = count
def count(self):
"""Get the number of processes matching the regex"""
return self.get('count')
def count_min(self):
"""Get the minimum number of processes"""
return self.get('countmin')
def count_max(self):
"""Get the maximum number of processes"""
return self.get('countmax')
def set_result(self, result, separator=''):
"""Store the result (string) into the result key of the AMP
if one_line is true then replace \n by separator
"""
if self.one_line():
self.configs['result'] = str(result).replace('\n', separator)
else:
self.configs['result'] = str(result)
def result(self):
""" Return the result of the AMP (as a string)"""
ret = self.get('result')
if ret is not None:
ret = u(ret)
return ret
def update_wrapper(self, process_list):
"""Wrapper for the children update"""
# Set the number of running process
self.set_count(len(process_list))
# Call the children update method
if self.should_update():
return self.update(process_list)
else:
return self.result()
示例10: CpuPercent
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class CpuPercent(object):
"""Get and store the CPU percent."""
def __init__(self, cached_time=1):
self.cpu_percent = 0
self.percpu_percent = []
# cached_time is the minimum time interval between stats updates
# since last update is passed (will retrieve old cached info instead)
self.timer_cpu = Timer(0)
self.timer_percpu = Timer(0)
self.cached_time = cached_time
def get_key(self):
"""Return the key of the per CPU list."""
return 'cpu_number'
def get(self, percpu=False):
"""Update and/or return the CPU using the psutil library.
If percpu, return the percpu stats"""
if percpu:
return self.__get_percpu()
else:
return self.__get_cpu()
def __get_cpu(self):
"""Update and/or return the CPU using the psutil library."""
# Never update more than 1 time per cached_time
if self.timer_cpu.finished():
self.cpu_percent = psutil.cpu_percent(interval=0.0)
# Reset timer for cache
self.timer_cpu = Timer(self.cached_time)
return self.cpu_percent
def __get_percpu(self):
"""Update and/or return the per CPU list using the psutil library."""
# Never update more than 1 time per cached_time
if self.timer_percpu.finished():
self.percpu_percent = []
for cpu_number, cputimes in enumerate(psutil.cpu_times_percent(interval=0.0, percpu=True)):
cpu = {'key': self.get_key(),
'cpu_number': cpu_number,
'total': round(100 - cputimes.idle, 1),
'user': cputimes.user,
'system': cputimes.system,
'idle': cputimes.idle}
# The following stats are for API purposes only
if hasattr(cputimes, 'nice'):
cpu['nice'] = cputimes.nice
if hasattr(cputimes, 'iowait'):
cpu['iowait'] = cputimes.iowait
if hasattr(cputimes, 'irq'):
cpu['irq'] = cputimes.irq
if hasattr(cputimes, 'softirq'):
cpu['softirq'] = cputimes.softirq
if hasattr(cputimes, 'steal'):
cpu['steal'] = cputimes.steal
if hasattr(cputimes, 'guest'):
cpu['guest'] = cputimes.guest
if hasattr(cputimes, 'guest_nice'):
cpu['guest_nice'] = cputimes.guest_nice
# Append new CPU to the list
self.percpu_percent.append(cpu)
# Reset timer for cache
self.timer_percpu = Timer(self.cached_time)
return self.percpu_percent
示例11: GlancesProcesses
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
#.........这里部分代码省略.........
self.sort_key,
self.sort_reverse,
self.no_kernel_threads,
excluded_processes)
for i, node in enumerate(self.process_tree):
# Only retreive stats for visible processes (max_processes)
if self.max_processes is not None and i >= self.max_processes:
break
# add standard stats
new_stats = self.__get_process_stats(node.process,
mandatory_stats=False,
standard_stats=True,
extended_stats=False)
if new_stats is not None:
node.stats.update(new_stats)
# Add a specific time_since_update stats for bitrate
node.stats['time_since_update'] = time_since_update
else:
# Process optimization
# Only retreive stats for visible processes (max_processes)
if self.max_processes is not None:
# Sort the internal dict and cut the top N (Return a list of tuple)
# tuple=key (proc), dict (returned by __get_process_stats)
try:
processiter = sorted(iteritems(processdict),
key=lambda x: x[1][self.sort_key],
reverse=self.sort_reverse)
except (KeyError, TypeError) as e:
logger.error("Cannot sort process list by {0}: {1}".format(self.sort_key, e))
logger.error('{0}'.format(listitems(processdict)[0]))
# Fallback to all process (issue #423)
processloop = iteritems(processdict)
first = False
else:
processloop = processiter[0:self.max_processes]
first = True
else:
# Get all processes stats
processloop = iteritems(processdict)
first = False
for i in processloop:
# Already existing mandatory stats
procstat = i[1]
if self.max_processes is not None:
# Update with standard stats
# and extended stats but only for TOP (first) process
s = self.__get_process_stats(i[0],
mandatory_stats=False,
standard_stats=True,
extended_stats=first)
if s is None:
continue
procstat.update(s)
# Add a specific time_since_update stats for bitrate
procstat['time_since_update'] = time_since_update
# Update process list
self.processlist.append(procstat)
# Next...
first = False
# Build the all processes list used by the monitored list
self.allprocesslist = itervalues(processdict)
# Clean internals caches if timeout is reached
if self.cache_timer.finished():
self.username_cache = {}
self.cmdline_cache = {}
# Restart the timer
self.cache_timer.reset()
def getcount(self):
"""Get the number of processes."""
return self.processcount
def getalllist(self):
"""Get the allprocesslist."""
return self.allprocesslist
def getlist(self, sortedby=None):
"""Get the processlist."""
return self.processlist
def gettree(self):
"""Get the process tree."""
return self.process_tree
@property
def sort_key(self):
"""Get the current sort key."""
return self._sort_key
@sort_key.setter
def sort_key(self, key):
"""Set the current sort key."""
self._sort_key = key
示例12: Plugin
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class Plugin(GlancesPlugin):
"""Glances ports scanner plugin."""
def __init__(self, args=None, config=None):
"""Init the plugin."""
super(Plugin, self).__init__(args=args)
self.args = args
self.config = config
# We want to display the stat in the curse interface
self.display_curse = True
# Init stats
self.stats = GlancesPortsList(config=config, args=args).get_ports_list()
# Init global Timer
self.timer_ports = Timer(0)
# Global Thread running all the scans
self._thread = None
def exit(self):
"""Overwrite the exit method to close threads"""
if self._thread is not None:
self._thread.stop()
# Call the father class
super(Plugin, self).exit()
@GlancesPlugin._log_result_decorator
def update(self):
"""Update the ports list."""
if self.input_method == 'local':
# Only refresh:
# * if there is not other scanning thread
# * every refresh seconds (define in the configuration file)
if self._thread is None:
thread_is_running = False
else:
thread_is_running = self._thread.isAlive()
if self.timer_ports.finished() and not thread_is_running:
# Run ports scanner
self._thread = ThreadScanner(self.stats)
self._thread.start()
# Restart timer
if len(self.stats) > 0:
self.timer_ports = Timer(self.stats[0]['refresh'])
else:
self.timer_ports = Timer(0)
else:
# Not available in SNMP mode
pass
return self.stats
def get_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
if port['status'] is None:
return 'CAREFUL'
elif port['status'] == 0:
return 'CRITICAL'
elif isinstance(port['status'], (float, int)) and \
port['rtt_warning'] is not None and \
port['status'] > port['rtt_warning']:
return 'WARNING'
return 'OK'
def msg_curse(self, args=None):
"""Return the dict to display in the curse interface."""
# Init the return message
# Only process if stats exist and display plugin enable...
ret = []
if not self.stats or args.disable_ports:
return ret
# Build the string message
for p in self.stats:
if p['status'] is None:
status = 'Scanning'
elif isinstance(p['status'], bool_type) and p['status'] is True:
status = 'Open'
elif p['status'] == 0:
status = 'Timeout'
else:
# Convert second to ms
status = '{0:.0f}ms'.format(p['status'] * 1000.0)
msg = '{:14.14} '.format(p['description'])
ret.append(self.curse_add_line(msg))
msg = '{:>8}'.format(status)
ret.append(self.curse_add_line(msg, self.get_alert(p)))
ret.append(self.curse_new_line())
# Delete the last empty line
try:
ret.pop()
#.........这里部分代码省略.........
示例13: GlancesBottle
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class GlancesBottle(object):
"""This class manages the Bottle Web server."""
API_VERSION = '3'
def __init__(self, config=None, args=None):
# Init config
self.config = config
# Init args
self.args = args
# Init stats
# Will be updated within Bottle route
self.stats = None
# cached_time is the minimum time interval between stats updates
# i.e. HTTP/RESTful calls will not retrieve updated info until the time
# since last update is passed (will retrieve old cached info instead)
self.timer = Timer(0)
# Load configuration file
self.load_config(config)
# Set the bind URL
self.bind_url = 'http://{}:{}/'.format(self.args.bind_address,
self.args.port)
# Init Bottle
self._app = Bottle()
# Enable CORS (issue #479)
self._app.install(EnableCors())
# Password
if args.password != '':
self._app.install(auth_basic(self.check_auth))
# Define routes
self._route()
# Path where the statics files are stored
self.STATIC_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static/public')
# Paths for templates
TEMPLATE_PATH.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static/templates'))
def load_config(self, config):
"""Load the outputs section of the configuration file."""
# Limit the number of processes to display in the WebUI
if config is not None and config.has_section('outputs'):
logger.debug('Read number of processes to display in the WebUI')
n = config.get_value('outputs', 'max_processes_display', default=None)
logger.debug('Number of processes to display in the WebUI: {}'.format(n))
def __update__(self):
# Never update more than 1 time per cached_time
if self.timer.finished():
self.stats.update()
self.timer = Timer(self.args.cached_time)
def app(self):
return self._app()
def check_auth(self, username, password):
"""Check if a username/password combination is valid."""
if username == self.args.username:
from glances.password import GlancesPassword
pwd = GlancesPassword()
return pwd.check_password(self.args.password, pwd.sha256_hash(password))
else:
return False
def _route(self):
"""Define route."""
# REST API
self._app.route('/api/%s/config' % self.API_VERSION, method="GET",
callback=self._api_config)
self._app.route('/api/%s/config/<item>' % self.API_VERSION, method="GET",
callback=self._api_config_item)
self._app.route('/api/%s/args' % self.API_VERSION, method="GET",
callback=self._api_args)
self._app.route('/api/%s/args/<item>' % self.API_VERSION, method="GET",
callback=self._api_args_item)
self._app.route('/api/%s/help' % self.API_VERSION, method="GET",
callback=self._api_help)
self._app.route('/api/%s/pluginslist' % self.API_VERSION, method="GET",
callback=self._api_plugins)
self._app.route('/api/%s/all' % self.API_VERSION, method="GET",
callback=self._api_all)
self._app.route('/api/%s/all/limits' % self.API_VERSION, method="GET",
callback=self._api_all_limits)
self._app.route('/api/%s/all/views' % self.API_VERSION, method="GET",
callback=self._api_all_views)
self._app.route('/api/%s/<plugin>' % self.API_VERSION, method="GET",
callback=self._api)
self._app.route('/api/%s/<plugin>/history' % self.API_VERSION, method="GET",
callback=self._api_history)
self._app.route('/api/%s/<plugin>/history/<nb:int>' % self.API_VERSION, method="GET",
callback=self._api_history)
self._app.route('/api/%s/<plugin>/limits' % self.API_VERSION, method="GET",
callback=self._api_limits)
self._app.route('/api/%s/<plugin>/views' % self.API_VERSION, method="GET",
#.........这里部分代码省略.........
示例14: Plugin
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class Plugin(GlancesPlugin):
"""Glances ports scanner plugin."""
def __init__(self, args=None, config=None):
"""Init the plugin."""
super(Plugin, self).__init__(args=args,
stats_init_value=[])
self.args = args
self.config = config
# We want to display the stat in the curse interface
self.display_curse = True
# Init stats
self.stats = GlancesPortsList(config=config, args=args).get_ports_list() + GlancesWebList(config=config, args=args).get_web_list()
# Init global Timer
self.timer_ports = Timer(0)
# Global Thread running all the scans
self._thread = None
def exit(self):
"""Overwrite the exit method to close threads."""
if self._thread is not None:
self._thread.stop()
# Call the father class
super(Plugin, self).exit()
@GlancesPlugin._log_result_decorator
def update(self):
"""Update the ports list."""
if self.input_method == 'local':
# Only refresh:
# * if there is not other scanning thread
# * every refresh seconds (define in the configuration file)
if self._thread is None:
thread_is_running = False
else:
thread_is_running = self._thread.isAlive()
if self.timer_ports.finished() and not thread_is_running:
# Run ports scanner
self._thread = ThreadScanner(self.stats)
self._thread.start()
# Restart timer
if len(self.stats) > 0:
self.timer_ports = Timer(self.stats[0]['refresh'])
else:
self.timer_ports = Timer(0)
else:
# Not available in SNMP mode
pass
return self.stats
def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value."""
if port['status'] is None:
return 'CAREFUL'
elif port['status'] == 0:
return 'CRITICAL'
elif (isinstance(port['status'], (float, int)) and
port['rtt_warning'] is not None and
port['status'] > port['rtt_warning']):
return 'WARNING'
return 'OK'
def get_web_alert(self, web, header="", log=False):
"""Return the alert status relative to the web/url scan return value."""
if web['status'] is None:
return 'CAREFUL'
elif web['status'] not in [200, 301, 302]:
return 'CRITICAL'
elif web['rtt_warning'] is not None and web['elapsed'] > web['rtt_warning']:
return 'WARNING'
return 'OK'
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
# Only process if stats exist and display plugin enable...
ret = []
if not self.stats or args.disable_ports:
return ret
# Max size for the interface name
name_max_width = max_width - 7
# Build the string message
for p in self.stats:
if 'host' in p:
if p['host'] is None:
status = 'None'
elif p['status'] is None:
status = 'Scanning'
elif isinstance(p['status'], bool_type) and p['status'] is True:
status = 'Open'
#.........这里部分代码省略.........
示例15: Export
# 需要导入模块: from glances.timer import Timer [as 别名]
# 或者: from glances.timer.Timer import finished [as 别名]
class Export(GlancesExport):
"""This class manages the Graph export module."""
def __init__(self, config=None, args=None):
"""Init the export IF."""
super(Export, self).__init__(config=config, args=args)
# Load the Graph configuration file section (is exists)
self.export_enable = self.load_conf('graph',
options=['path',
'generate_every',
'width',
'height',
'style'])
# Manage options (command line arguments overwrite configuration file)
self.path = args.export_graph_path or self.path
self.generate_every = int(getattr(self, 'generate_every', 0))
self.width = int(getattr(self, 'width', 800))
self.height = int(getattr(self, 'height', 600))
self.style = getattr(pygal.style,
getattr(self, 'style', 'DarkStyle'),
pygal.style.DarkStyle)
# Create export folder
try:
os.makedirs(self.path)
except OSError as e:
if e.errno != errno.EEXIST:
logger.critical("Cannot create the Graph output folder {} ({})".format(self.path, e))
sys.exit(2)
# Check if output folder is writeable
try:
tempfile.TemporaryFile(dir=self.path)
except OSError as e:
logger.critical("Graph output folder {} is not writeable".format(self.path))
sys.exit(2)
logger.info("Graphs will be created in the {} folder".format(self.path))
logger.info("Graphs will be created when 'g' key is pressed (in the CLI interface)")
if self.generate_every != 0:
logger.info("Graphs will be created automatically every {} seconds".format(self.generate_every))
# Start the timer
self._timer = Timer(self.generate_every)
else:
self._timer = None
def exit(self):
"""Close the files."""
logger.debug("Finalise export interface %s" % self.export_name)
def update(self, stats):
"""Generate Graph file in the output folder."""
if self.generate_every != 0 and self._timer.finished():
self.args.generate_graph = True
self._timer.reset()
if not self.args.generate_graph:
return
plugins = stats.getPluginsList()
for plugin_name in plugins:
plugin = stats._plugins[plugin_name]
if plugin_name in self.plugins_to_export():
self.export(plugin_name, plugin.get_export_history())
logger.info("Graphs created in the folder {}".format(self.path))
self.args.generate_graph = False
def export(self, title, data):
"""Generate graph from the data.
Example for the mem plugin:
{'percent': [
(datetime.datetime(2018, 3, 24, 16, 27, 47, 282070), 51.8),
(datetime.datetime(2018, 3, 24, 16, 27, 47, 540999), 51.9),
(datetime.datetime(2018, 3, 24, 16, 27, 50, 653390), 52.0),
(datetime.datetime(2018, 3, 24, 16, 27, 53, 749702), 52.0),
(datetime.datetime(2018, 3, 24, 16, 27, 56, 825660), 52.0),
...
]
}
Return:
* True if the graph have been generated
* False if the graph have not been generated
"""
if data == {}:
return False
chart = DateTimeLine(title=title.capitalize(),
width=self.width,
height=self.height,
style=self.style,
show_dots=False,
legend_at_bottom=True,
x_label_rotation=20,
#.........这里部分代码省略.........