INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Display the right sidebar in the Curses interface. | def __display_right(self, stat_display):
"""Display the right sidebar in the Curses interface.
docker + processcount + amps + processlist + alert
"""
# Do not display anything if space is not available...
if self.screen.getmaxyx()[1] < self._left_sidebar_min_width:
r... |
Display a centered popup. | def display_popup(self, message,
size_x=None, size_y=None,
duration=3,
is_input=False,
input_size=30,
input_value=None):
"""
Display a centered popup.
If is_input is False:
Dis... |
Display the plugin_stats on the screen. | def display_plugin(self, plugin_stats,
display_optional=True,
display_additional=True,
max_y=65535,
add_space=0):
"""Display the plugin_stats on the screen.
If display_optional=True display the optional stats
... |
Clear and update the screen. | def flush(self, stats, cs_status=None):
"""Clear and update the screen.
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
... |
Update the screen. | 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 serv... |
Return the width of the formatted curses message. | def get_stats_display_width(self, curse_msg, without_option=False):
"""Return the width of the formatted curses message."""
try:
if without_option:
# Size without options
c = len(max(''.join([(u(u(nativestr(i['msg'])).encode('ascii', 'replace')) if not i['opti... |
r Return the height of the formatted curses message. | def get_stats_display_height(self, curse_msg):
r"""Return the height of the formatted curses message.
The height is defined by the number of '\n' (new line).
"""
try:
c = [i['msg'] for i in curse_msg['msgdict']].count('\n')
except Exception as e:
logger.d... |
Build the results. | def __buid_result(self, varBinds):
"""Build the results."""
ret = {}
for name, val in varBinds:
if str(val) == '':
ret[name.prettyPrint()] = ''
else:
ret[name.prettyPrint()] = val.prettyPrint()
# In Python 3, prettyPrint() r... |
SNMP simple request ( list of OID ). | def get_by_oid(self, *oid):
"""SNMP simple request (list of OID).
One request per OID list.
* oid: oid list
> Return a dict
"""
if self.version == '3':
errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
cmdgen.UsmUserDat... |
SNMP getbulk request. | def getbulk_by_oid(self, non_repeaters, max_repetitions, *oid):
"""SNMP getbulk request.
In contrast to snmpwalk, this information will typically be gathered in
a single transaction with the agent, rather than one transaction per
variable found.
* non_repeaters: This specifies ... |
Load the server list from the configuration file. | def load(self, config):
"""Load the server list from the configuration file."""
server_list = []
if config is None:
logger.debug("No configuration file available. Cannot load server list.")
elif not config.has_section(self._section):
logger.warning("No [%s] secti... |
Set the key to the value for the server_pos ( position in the list ). | def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
self._server_list[server_pos][key] = value |
Add a new server to the list. | def add_server(self, name, ip, port):
"""Add a new server to the list."""
new_server = {
'key': name, # Zeroconf name with both hostname and port
'name': name.split(':')[0], # Short name
'ip': ip, # IP address seen by the client
'port': port, # TCP por... |
Remove a server from the dict. | def remove_server(self, name):
"""Remove a server from the dict."""
for i in self._server_list:
if i['key'] == name:
try:
self._server_list.remove(i)
logger.debug("Remove server %s from the list" % name)
logger.debug... |
Set the key to the value for the server_pos ( position in the list ). | def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
self.servers.set_server(server_pos, key, value) |
Method called when a new Zeroconf client is detected. | def add_service(self, zeroconf, srv_type, srv_name):
"""Method called when a new Zeroconf client is detected.
Return True if the zeroconf client is a Glances server
Note: the return code will never be used
"""
if srv_type != zeroconf_type:
return False
logger... |
Remove the server from the list. | def remove_service(self, zeroconf, srv_type, srv_name):
"""Remove the server from the list."""
self.servers.remove_server(srv_name)
logger.info(
"Glances server %s removed from the autodetect list" % srv_name) |
Set the key to the value for the server_pos ( position in the list ). | def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""
if zeroconf_tag and self.zeroconf_enable_tag:
self.listener.set_server(server_pos, key, value) |
Try to find the active IP addresses. | def find_active_ip_address():
"""Try to find the active IP addresses."""
import netifaces
# Interface of the default gateway
gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1]
# IP address for the interface
return netifaces.ifaddresses(gateway_itf)[netifa... |
Compress result with deflate algorithm if the client ask for it. | def compress(func):
"""Compress result with deflate algorithm if the client ask for it."""
def wrapper(*args, **kwargs):
"""Wrapper that take one function and return the compressed result."""
ret = func(*args, **kwargs)
logger.debug('Receive {} {} request with header: {}'.format(
... |
Load the outputs section of the configuration file. | 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 = c... |
Check if a username/ password combination is valid. | 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(pas... |
Define route. | 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_conf... |
Start the bottle. | def start(self, stats):
"""Start the bottle."""
# Init stats
self.stats = stats
# Init plugin list
self.plugins_list = self.stats.getPluginsList()
# Bind the Bottle TCP address/port
if self.args.open_web_browser:
# Implementation of the issue #946
... |
Bottle callback for index. html (/ ) file. | def _index(self, refresh_time=None):
"""Bottle callback for index.html (/) file."""
if refresh_time is None or refresh_time < 1:
refresh_time = self.args.time
# Update the stat
self.__update__()
# Display
return template("index.html", refresh_time=refresh_t... |
Glances API RESTful implementation. | def _api_help(self):
"""Glances API RESTful implementation.
Return the help data or 404 error.
"""
response.content_type = 'application/json; charset=utf-8'
# Update the stat
view_data = self.stats.get_plugin("help").get_view_data()
try:
plist = json... |
Glances API RESTFul implementation. | def _api_plugins(self):
"""Glances API RESTFul implementation.
@api {get} /api/%s/pluginslist Get plugins list
@apiVersion 2.0
@apiName pluginslist
@apiGroup plugin
@apiSuccess {String[]} Plugins list.
@apiSuccessExample Success-Response:
HTTP/1.1 2... |
Glances API RESTful implementation. | def _api_all(self):
"""Glances API RESTful implementation.
Return the JSON representation of all the plugins
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
if self.arg... |
Glances API RESTful implementation. | def _api_all_limits(self):
"""Glances API RESTful implementation.
Return the JSON representation of all the plugins limits
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
... |
Glances API RESTful implementation. | def _api_all_views(self):
"""Glances API RESTful implementation.
Return the JSON representation of all the plugins views
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
... |
Glances API RESTful implementation. | def _api(self, plugin):
"""Glances API RESTful implementation.
Return the JSON representation of a given plugin
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
if plugi... |
Glances API RESTful implementation. | def _api_history(self, plugin, nb=0):
"""Glances API RESTful implementation.
Return the JSON representation of a given plugin history
Limit to the last nb items (all if nb=0)
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
resp... |
Glances API RESTful implementation. | def _api_limits(self, plugin):
"""Glances API RESTful implementation.
Return the JSON limits of a given plugin
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
if plugin... |
Glances API RESTful implementation. | def _api_views(self, plugin):
"""Glances API RESTful implementation.
Return the JSON views of a given plugin
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
if plugin n... |
Father method for _api_item and _api_value. | def _api_itemvalue(self, plugin, item, value=None, history=False, nb=0):
"""Father method for _api_item and _api_value."""
response.content_type = 'application/json; charset=utf-8'
if plugin not in self.plugins_list:
abort(400, "Unknown plugin %s (available plugins: %s)" % (plugin, ... |
Glances API RESTful implementation. | def _api_item_history(self, plugin, item, nb=0):
"""Glances API RESTful implementation.
Return the JSON representation of the couple plugin/history of item
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
return self._api_itemvalue(plu... |
Glances API RESTful implementation. | def _api_value(self, plugin, item, value):
"""Glances API RESTful implementation.
Return the process stats (dict) for the given item=value
HTTP/200 if OK
HTTP/400 if plugin is not found
HTTP/404 if others error
"""
return self._api_itemvalue(plugin, item, value) |
Glances API RESTful implementation. | def _api_config(self):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances configuration file
HTTP/200 if OK
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
try:
# Get the JSON v... |
Glances API RESTful implementation. | def _api_config_item(self, item):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances configuration item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=... |
Glances API RESTful implementation. | def _api_args(self):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments
HTTP/200 if OK
HTTP/404 if others error
"""
response.content_type = 'application/json; charset=utf-8'
try:
# Get the JSON... |
Glances API RESTful implementation. | def _api_args_item(self, item):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; c... |
Update disk I/ O stats using the input method. | def update(self):
"""Update disk I/O stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# Grab the stat using the psutil disk_io_counters method
... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if not self.stats or self.is_disable():
return ret
# Max si... |
Start Glances. | def start(config, args):
"""Start Glances."""
# Load mode
global mode
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 ... |
Main entry point for Glances. | def main():
"""Main entry point for Glances.
Select the mode (standalone, client or server)
Run it...
"""
# Catch the CTRL-C signal
signal.signal(signal.SIGINT, __signal_handler)
# Log Glances and psutil version
logger.info('Start Glances {}'.format(__version__))
logger.info('{} {}... |
r Return the per - user config dir ( full path ). | def user_config_dir():
r"""Return the per-user config dir (full path).
- Linux, *BSD, SunOS: ~/.config/glances
- macOS: ~/Library/Application Support/glances
- Windows: %APPDATA%\glances
"""
if WINDOWS:
path = os.environ.get('APPDATA')
elif MACOS:
path = os.path.expanduser('... |
r Return the per - user cache dir ( full path ). | def user_cache_dir():
r"""Return the per-user cache dir (full path).
- Linux, *BSD, SunOS: ~/.cache/glances
- macOS: ~/Library/Caches/glances
- Windows: {%LOCALAPPDATA%,%APPDATA%}\glances\cache
"""
if WINDOWS:
path = os.path.join(os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA... |
r Return the system - wide config dir ( full path ). | def system_config_dir():
r"""Return the system-wide config dir (full path).
- Linux, SunOS: /etc/glances
- *BSD, macOS: /usr/local/etc/glances
- Windows: %APPDATA%\glances
"""
if LINUX or SUNOS:
path = '/etc'
elif BSD or MACOS:
path = '/usr/local/etc'
else:
path ... |
r Get a list of config file paths. | def config_file_paths(self):
r"""Get a list of config file paths.
The list is built taking into account of the OS, priority and location.
* custom path: /path/to/glances
* Linux, SunOS: ~/.config/glances, /etc/glances
* *BSD: ~/.config/glances, /usr/local/etc/glances
* ... |
Read the config file if it exists. Using defaults otherwise. | def read(self):
"""Read the config file, if it exists. Using defaults otherwise."""
for config_file in self.config_file_paths():
logger.info('Search glances.conf file in {}'.format(config_file))
if os.path.exists(config_file):
try:
with open(co... |
Return the configuration as a dict | def as_dict(self):
"""Return the configuration as a dict"""
dictionary = {}
for section in self.parser.sections():
dictionary[section] = {}
for option in self.parser.options(section):
dictionary[section][option] = self.parser.get(section, option)
r... |
Set default values for careful warning and critical. | def set_default_cwc(self, section,
option_header=None,
cwc=['50', '70', '90']):
"""Set default values for careful, warning and critical."""
if option_header is None:
header = ''
else:
header = option_header + '_'
sel... |
If the option did not exist create a default value. | def set_default(self, section, option,
default):
"""If the option did not exist, create a default value."""
if not self.parser.has_option(section, option):
self.parser.set(section, option, default) |
Get the value of an option if it exists. | def get_value(self, section, option,
default=None):
"""Get the value of an option, if it exists.
If it did not exist, then return the default value.
It allows user to define dynamic configuration key (see issue#1204)
Dynamic vlaue should starts and end with the ` char... |
Get the int value of an option if it exists. | def get_int_value(self, section, option, default=0):
"""Get the int value of an option, if it exists."""
try:
return self.parser.getint(section, option)
except NoOptionError:
return int(default) |
Get the float value of an option if it exists. | def get_float_value(self, section, option, default=0.0):
"""Get the float value of an option, if it exists."""
try:
return self.parser.getfloat(section, option)
except NoOptionError:
return float(default) |
Get the bool value of an option if it exists. | def get_bool_value(self, section, option, default=True):
"""Get the bool value of an option, if it exists."""
try:
return self.parser.getboolean(section, option)
except NoOptionError:
return bool(default) |
Return the event position if it exists. | def __event_exist(self, event_type):
"""Return the event position, if it exists.
An event exist if:
* end is < 0
* event_type is matching
Return -1 if the item is not found.
"""
for i in range(self.len()):
if self.events_list[i][1] < 0 and self.events... |
Return the process sort key | def get_event_sort_key(self, event_type):
"""Return the process sort key"""
# Process sort depending on alert type
if event_type.startswith("MEM"):
# Sort TOP process by memory_percent
ret = 'memory_percent'
elif event_type.startswith("CPU_IOWAIT"):
# ... |
Define the process auto sort key from the alert type. | def set_process_sort(self, event_type):
"""Define the process auto sort key from the alert type."""
if glances_processes.auto_sort:
glances_processes.sort_key = self.get_event_sort_key(event_type) |
Add a new item to the logs list. | def add(self, event_state, event_type, event_value,
proc_list=None, proc_desc="", peak_time=6):
"""Add a new item to the logs list.
If 'event' is a 'new one', add it at the beginning of the list.
If 'event' is not a 'new one', update the list .
If event < peak_time then the ... |
Add a new item in the log list. | def _create_event(self, event_state, event_type, event_value,
proc_list, proc_desc, peak_time):
"""Add a new item in the log list.
Item is added only if the criticity (event_state) is WARNING or CRITICAL.
"""
if event_state == "WARNING" or event_state == "CRITICAL"... |
Update an event in the list | def _update_event(self, event_index, event_state, event_type, event_value,
proc_list, proc_desc, peak_time):
"""Update an event in the list"""
if event_state == "OK" or event_state == "CAREFUL":
# Reset the automatic process sort key
self.reset_process_sort(... |
Clean the logs list by deleting finished items. | def clean(self, critical=False):
"""Clean the logs list by deleting finished items.
By default, only delete WARNING message.
If critical = True, also delete CRITICAL message.
"""
# Create a new clean list
clean_events_list = []
while self.len() > 0:
i... |
Chek if SNMP is available on the server. | def check_snmp(self):
"""Chek if SNMP is available on the server."""
# Import the SNMP client class
from glances.snmp import GlancesSNMPClient
# Create an instance of the SNMP client
clientsnmp = GlancesSNMPClient(host=self.args.client,
por... |
Get the short os name from the OS name OID string. | def get_system_name(self, oid_system_name):
"""Get the short os name from the OS name OID string."""
short_system_name = None
if oid_system_name == '':
return short_system_name
# Find the short name in the oid_to_short_os_name dict
for r, v in iteritems(oid_to_short... |
Update the stats using SNMP. | def update(self):
"""Update the stats using SNMP."""
# 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
... |
Update RAID stats using the input method. | def update(self):
"""Update RAID stats using the input method."""
# Init new stats
stats = self.get_init_value()
if import_error_tag:
return self.stats
if self.input_method == 'local':
# Update stats using the PyMDstat lib (https://github.com/nicolargo/p... |
Return the dict to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist...
if not self.stats:
return ret
# Max size for the interface name
name_max_widt... |
RAID alert messages. | def raid_alert(self, status, used, available, type):
"""RAID alert messages.
[available/used] means that ideally the array may have _available_
devices however, _used_ devices are in use.
Obviously when used >= available then things are good.
"""
if type == 'raid0':
... |
Update uptime stat using the input method. | def update(self):
"""Update uptime stat using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
self.uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time(... |
Update the cloud stats. | def update(self):
"""Update the cloud stats.
Return the stats (dict)
"""
# Init new stats
stats = self.get_init_value()
# Requests lib is needed to get stats from the Cloud API
if import_error_tag:
return stats
# Update the stats
if ... |
Return the string to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the string to display in the curse interface."""
# Init the return message
ret = []
if not self.stats or self.stats == {} or self.is_disable():
return ret
# Generate the output
if 'instance-type' in s... |
Grab plugin s stats. | def run(self):
"""Grab plugin's stats.
Infinite loop, should be stopped by calling the stop() method
"""
if import_error_tag:
self.stop()
return False
for k, v in iteritems(self.OPENSTACK_API_METADATA):
r_url = '{}/{}'.format(self.OPENSTACK_A... |
Generate the views. | def generate_view_data(self):
"""Generate the views."""
self.view_data['version'] = '{} {}'.format('Glances', __version__)
self.view_data['psutil_version'] = ' with psutil {}'.format(psutil_version)
try:
self.view_data['configuration_file'] = 'Configuration file: {}'.format(... |
Return the list to display in the curse interface. | def msg_curse(self, args=None, max_width=None):
"""Return the list to display in the curse interface."""
# Init the return message
ret = []
# Build the string message
# Header
ret.append(self.curse_add_line(self.view_data['version'], 'TITLE'))
ret.append(self.cur... |
Set a value. Value is a tuple: ( <timestamp > <new_value > ) | def value(self, new_value):
"""Set a value.
Value is a tuple: (<timestamp>, <new_value>)
"""
self._value = (datetime.now(), new_value)
self.history_add(self._value) |
Add a value in the history | def history_add(self, value):
"""Add a value in the history
"""
if self._history_max_size is None or self.history_len() < self._history_max_size:
self._history.append(value)
else:
self._history = self._history[1:] + [value] |
Return the history in ISO JSON format | def history_json(self, nb=0):
"""Return the history in ISO JSON format"""
return [(i[0].isoformat(), i[1]) for i in self._history[-nb:]] |
Return the mean on the <nb > values in the history. | def history_mean(self, nb=5):
"""Return the mean on the <nb> values in the history.
"""
_, v = zip(*self._history)
return sum(v[-nb:]) / float(v[-1] - v[-nb]) |
Load the AMP configuration files. | def load_configs(self):
"""Load the AMP configuration files."""
if self.config is None:
return False
# Display a warning (deprecated) message if the monitor section exist
if "monitor" in self.config.sections():
logger.warning("A deprecated [monitor] section exist... |
Update the command result attributed. | def update(self):
"""Update the command result attributed."""
# Get the current processes list (once)
processlist = glances_processes.getlist()
# Iter upon the AMPs dict
for k, v in iteritems(self.get()):
if not v.enable():
# Do not update if the enab... |
Return the AMPS process list according to the amp_value | def _build_amps_list(self, amp_value, processlist):
"""Return the AMPS process list according to the amp_value
Search application monitored processes by a regular expression
"""
ret = []
try:
# Search in both cmdline and name (for kernel thread, see #1261)
... |
Update stats in the CSV output file. | def update(self, stats):
"""Update stats in the CSV output file."""
# Get the stats
all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export())
# Init data with timestamp (issue#708)
if self.first_line:
csv_header = ['timestamp']
csv_data = [t... |
Update and/ or return the CPU using the psutil library. | 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(s... |
Update and/ or return the per CPU list using the psutil library. | 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=... |
Display modules list | def display_modules_list(self):
"""Display modules list"""
print("Plugins list: {}".format(
', '.join(sorted(self.stats.getPluginsList(enable=False)))))
print("Exporters list: {}".format(
', '.join(sorted(self.stats.getExportsList(enable=False))))) |
Main loop for the CLI. | 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.up... |
Wrapper to the serve_forever function. | def serve_forever(self):
"""Wrapper to the serve_forever function."""
loop = True
while loop:
loop = self.__serve_forever()
self.end() |
End of the standalone CLI. | def end(self):
"""End of the standalone CLI."""
if not self.quiet:
self.screen.end()
# Exit from export modules
self.stats.end()
# Check Glances version versus PyPI one
if self.outdated.is_outdated():
print("You are using Glances version {}, howe... |
Return the hashed password salt + SHA - 256. | def get_hash(self, salt, plain_password):
"""Return the hashed password, salt + SHA-256."""
return hashlib.sha256(salt.encode() + plain_password.encode()).hexdigest() |
Hash password with a salt based on UUID ( universally unique identifier ). | def hash_password(self, plain_password):
"""Hash password with a salt based on UUID (universally unique identifier)."""
salt = uuid.uuid4().hex
encrypted_password = self.get_hash(salt, plain_password)
return salt + '$' + encrypted_password |
Encode the plain_password with the salt of the hashed_password. | def check_password(self, hashed_password, plain_password):
"""Encode the plain_password with the salt of the hashed_password.
Return the comparison with the encrypted_password.
"""
salt, encrypted_password = hashed_password.split('$')
re_encrypted_password = self.get_hash(salt, ... |
Get the password from a Glances client or server. | 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 passwo... |
Save the hashed password to the Glances folder. | def save_password(self, hashed_password):
"""Save the hashed password to the Glances folder."""
# Create the glances directory
safe_makedirs(self.password_dir)
# Create/overwrite the password file
with open(self.password_file, 'wb') as file_pwd:
file_pwd.write(b(hash... |
Load the hashed password from the Glances folder. | def load_password(self):
"""Load the hashed password from the Glances folder."""
# Read the password file, if it exists
with open(self.password_file, 'r') as file_pwd:
hashed_password = file_pwd.read()
return hashed_password |
Return the sparkline. | def get(self):
"""Return the sparkline."""
ret = sparklines(self.percents)[0]
if self.__with_text:
percents_without_none = [x for x in self.percents if x is not None]
if len(percents_without_none) > 0:
ret = '{}{:5.1f}%'.format(ret, percents_without_none[-... |
Update CPU stats using the input method. | def update(self):
"""Update CPU stats using the input method."""
# Grab stats into self.stats
if self.input_method == 'local':
stats = self.update_local()
elif self.input_method == 'snmp':
stats = self.update_snmp()
else:
stats = self.get_init... |
Update CPU stats using psutil. | def update_local(self):
"""Update CPU stats using psutil."""
# Grab CPU stats using psutil's cpu_percent and cpu_times_percent
# Get all possible values for CPU stats: user, system, idle,
# nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
# The following s... |
Update CPU stats using SNMP. | def update_snmp(self):
"""Update CPU stats using SNMP."""
# Init new stats
stats = self.get_init_value()
# Update stats using SNMP
if self.short_system_name in ('windows', 'esxi'):
# Windows or VMWare ESXi
# You can find the CPU utilization of windows sy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.