text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Pop the top frame from the stack. Return the new stack.
<END_TASK>
<USER_TASK:>
Description:
def pop(self):
"""
Pop the top frame from the stack. Return the new stack.
""" |
if self.next is None:
raise SimEmptyCallStackError("Cannot pop a frame from an empty call stack.")
new_list = self.next.copy({})
if self.state is not None:
self.state.register_plugin('callstack', new_list)
self.state.history.recent_stack_actions.append(CallS... |
<SYSTEM_TASK:>
Push a stack frame into the call stack. This method is called when calling a function in CFG recovery.
<END_TASK>
<USER_TASK:>
Description:
def call(self, callsite_addr, addr, retn_target=None, stack_pointer=None):
"""
Push a stack frame into the call stack. This method is called when cal... |
frame = CallStack(call_site_addr=callsite_addr, func_addr=addr, ret_addr=retn_target,
stack_ptr=stack_pointer)
return self.push(frame) |
<SYSTEM_TASK:>
Pop one or many call frames from the stack. This method is called when returning from a function in CFG
<END_TASK>
<USER_TASK:>
Description:
def ret(self, retn_target=None):
"""
Pop one or many call frames from the stack. This method is called when returning from a function in CFG
... |
if retn_target is None:
return self.pop()
# We may want to return to several levels up there, not only a
# single stack frame
return_target_index = self._find_return_target(retn_target)
if return_target_index is not None:
o = self
while re... |
<SYSTEM_TASK:>
Debugging representation of this CallStack object.
<END_TASK>
<USER_TASK:>
Description:
def dbg_repr(self):
"""
Debugging representation of this CallStack object.
:return: Details of this CalLStack
:rtype: str
""" |
stack = [ ]
for i, frame in enumerate(self):
s = "%d | %s -> %s, returning to %s" % (
i,
"None" if frame.call_site_addr is None else "%#x" % frame.call_site_addr,
"None" if frame.func_addr is None else "%#x" % frame.func_addr,
... |
<SYSTEM_TASK:>
Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery.
<END_TASK>
<USER_TASK:>
Description:
def stack_suffix(self, context_sensitivity_level):
"""
Generate the stack suffix. A stack suffix can be used as the key to a SimRun in CFG recovery.
... |
ret = ()
for frame in self:
if len(ret) >= context_sensitivity_level*2:
break
ret = (frame.call_site_addr, frame.func_addr) + ret
while len(ret) < context_sensitivity_level*2:
ret = (None, None) + ret
return ret |
<SYSTEM_TASK:>
Check if the return target exists in the stack, and return the index if exists. We always search from the most
<END_TASK>
<USER_TASK:>
Description:
def _find_return_target(self, target):
"""
Check if the return target exists in the stack, and return the index if exists. We always search f... |
for i, frame in enumerate(self):
if frame.ret_addr == target:
return i
return None |
<SYSTEM_TASK:>
Load the web list from the configuration file.
<END_TASK>
<USER_TASK:>
Description:
def load(self, config):
"""Load the web list from the configuration file.""" |
web_list = []
if config is None:
logger.debug("No configuration file available. Cannot load ports list.")
elif not config.has_section(self._section):
logger.debug("No [%s] section in the configuration file. Cannot load ports list." % self._section)
else:
... |
<SYSTEM_TASK:>
Build the sensors list depending of the type.
<END_TASK>
<USER_TASK:>
Description:
def build_sensors_list(self, type):
"""Build the sensors list depending of the type.
type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT
output: a list
""" |
ret = []
if type == SENSOR_TEMP_UNIT and self.init_temp:
input_list = self.stemps
self.stemps = psutil.sensors_temperatures()
elif type == SENSOR_FAN_UNIT and self.init_fan:
input_list = self.sfans
self.sfans = psutil.sensors_fans()
else:
... |
<SYSTEM_TASK:>
Add an user to the dictionary.
<END_TASK>
<USER_TASK:>
Description:
def add_user(self, username, password):
"""Add an user to the dictionary.""" |
self.server.user_dict[username] = password
self.server.isAuth = True |
<SYSTEM_TASK:>
Init the connection to the rabbitmq server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the rabbitmq server.""" |
if not self.export_enable:
return None
try:
parameters = pika.URLParameters(
'amqp://' + self.user +
':' + self.password +
'@' + self.host +
':' + self.port + '/')
connection = pika.BlockingConnection(pa... |
<SYSTEM_TASK:>
Write the points in RabbitMQ.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points in RabbitMQ.""" |
data = ('hostname=' + self.hostname + ', name=' + name +
', dateinfo=' + datetime.datetime.utcnow().isoformat())
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
else:
data += ", " + columns[i] + "=" + s... |
<SYSTEM_TASK:>
Normalize name for the Statsd convention
<END_TASK>
<USER_TASK:>
Description:
def normalize(name):
"""Normalize name for the Statsd convention""" |
# Name should not contain some specials chars (issue #1068)
ret = name.replace(':', '')
ret = ret.replace('%', '')
ret = ret.replace(' ', '_')
return ret |
<SYSTEM_TASK:>
Init the connection to the Statsd server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the Statsd server.""" |
if not self.export_enable:
return None
logger.info(
"Stats will be exported to StatsD server: {}:{}".format(self.host,
self.port))
return StatsClient(self.host,
int(self.port),... |
<SYSTEM_TASK:>
Load the ports list from the configuration file.
<END_TASK>
<USER_TASK:>
Description:
def load(self, config):
"""Load the ports list from the configuration file.""" |
ports_list = []
if config is None:
logger.debug("No configuration file available. Cannot load ports list.")
elif not config.has_section(self._section):
logger.debug("No [%s] section in the configuration file. Cannot load ports list." % self._section)
else:
... |
<SYSTEM_TASK:>
Init the connection to the OpenTSDB server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the OpenTSDB server.""" |
if not self.export_enable:
return None
try:
db = potsdb.Client(self.host,
port=int(self.port),
check_host=True)
except Exception as e:
logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)... |
<SYSTEM_TASK:>
Init the connection to the MQTT server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the MQTT server.""" |
if not self.export_enable:
return None
try:
client = paho.Client(client_id='glances_' + self.hostname,
clean_session=False)
client.username_pw_set(username=self.user,
password=self.password)
... |
<SYSTEM_TASK:>
Write the points in MQTT.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points in MQTT.""" |
WHITELIST = '_-' + string.ascii_letters + string.digits
SUBSTITUTE = '_'
def whitelisted(s,
whitelist=WHITELIST,
substitute=SUBSTITUTE):
return ''.join(c if c in whitelist else substitute for c in s)
for sensor, value in zip... |
<SYSTEM_TASK:>
Load server and password list from the confiuration file.
<END_TASK>
<USER_TASK:>
Description:
def load(self):
"""Load server and password list from the confiuration file.""" |
# Init the static server list (if defined)
self.static_server = GlancesStaticServer(config=self.config)
# Init the password list (if defined)
self.password = GlancesPassword(config=self.config) |
<SYSTEM_TASK:>
Return the URI for the given server dict.
<END_TASK>
<USER_TASK:>
Description:
def __get_uri(self, server):
"""Return the URI for the given server dict.""" |
# Select the connection mode (with or without password)
if server['password'] != "":
if server['status'] == 'PROTECTED':
# Try with the preconfigure password (only if status is PROTECTED)
clear_password = self.password.get_password(server['name'])
... |
<SYSTEM_TASK:>
Connect and display the given server
<END_TASK>
<USER_TASK:>
Description:
def __display_server(self, server):
"""
Connect and display the given server
""" |
# Display the Glances client for the selected server
logger.debug("Selected server {}".format(server))
# Connection can take time
# Display a popup
self.screen.display_popup(
'Connect to {}:{}'.format(server['name'], server['port']), duration=1)
# A passwor... |
<SYSTEM_TASK:>
Generate graph from the data.
<END_TASK>
<USER_TASK:>
Description:
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... |
if data == {}:
return False
chart = DateTimeLine(title=title.capitalize(),
width=self.width,
height=self.height,
style=self.style,
show_dots=False,
... |
<SYSTEM_TASK:>
Return True if Glances is running in standalone mode.
<END_TASK>
<USER_TASK:>
Description:
def is_standalone(self):
"""Return True if Glances is running in standalone mode.""" |
return (not self.args.client and
not self.args.browser and
not self.args.server and
not self.args.webserver) |
<SYSTEM_TASK:>
Return True if Glances is running in client mode.
<END_TASK>
<USER_TASK:>
Description:
def is_client(self):
"""Return True if Glances is running in client mode.""" |
return (self.args.client or self.args.browser) and not self.args.server |
<SYSTEM_TASK:>
Read a password from the command line.
<END_TASK>
<USER_TASK:>
Description:
def __get_password(self, description='',
confirm=False, clear=False, username='glances'):
"""Read a password from the command line.
- if confirm = True, with confirmation
- if clear... |
from glances.password import GlancesPassword
password = GlancesPassword(username=username)
return password.get_password(description, confirm, clear) |
<SYSTEM_TASK:>
Load outdated parameter in the global section of the configuration file.
<END_TASK>
<USER_TASK:>
Description:
def load_config(self, config):
"""Load outdated parameter in the global section of the configuration file.""" |
global_section = 'global'
if (hasattr(config, 'has_section') and
config.has_section(global_section)):
self.args.disable_check_update = config.get_value(global_section, 'check_update').lower() == 'false'
else:
logger.debug("Cannot find section {} in the c... |
<SYSTEM_TASK:>
Return True if a new version is available
<END_TASK>
<USER_TASK:>
Description:
def is_outdated(self):
"""Return True if a new version is available""" |
if self.args.disable_check_update:
# Check is disabled by configuration
return False
logger.debug("Check Glances version (installed: {} / latest: {})".format(self.installed_version(), self.latest_version()))
return LooseVersion(self.latest_version()) > LooseVersion(self... |
<SYSTEM_TASK:>
Load cache file and return cached data
<END_TASK>
<USER_TASK:>
Description:
def _load_cache(self):
"""Load cache file and return cached data""" |
# If the cached file exist, read-it
max_refresh_date = timedelta(days=7)
cached_data = {}
try:
with open(self.cache_file, 'rb') as f:
cached_data = pickle.load(f)
except Exception as e:
logger.debug("Cannot read version from cache file: {}... |
<SYSTEM_TASK:>
Save data to the cache file.
<END_TASK>
<USER_TASK:>
Description:
def _save_cache(self):
"""Save data to the cache file.""" |
# Create the cache directory
safe_makedirs(self.cache_dir)
# Create/overwrite the cache file
try:
with open(self.cache_file, 'wb') as f:
pickle.dump(self.data, f)
except Exception as e:
logger.error("Cannot write version to cache file {} ... |
<SYSTEM_TASK:>
Update the servers' list screen.
<END_TASK>
<USER_TASK:>
Description:
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 ever... |
# 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)
... |
<SYSTEM_TASK:>
Write the points to the Prometheus exporter using Gauge.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge.""" |
logger.debug("Export {} stats to Prometheus exporter".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in iteritems(dict(zip(columns, points))) if isinstance(v, Number)}
# Write metrics to the Prometheus exporter
for... |
<SYSTEM_TASK:>
Parse tags into a dict.
<END_TASK>
<USER_TASK:>
Description:
def parse_tags(self, tags):
"""Parse tags into a dict.
input tags: a comma separated list of 'key:value' pairs.
Example: foo:bar,spam:eggs
output dtags: a dict of tags.
Example: {'foo': 'bar', 's... |
dtags = {}
if tags:
try:
dtags = dict([x.split(':') for x in tags.split(',')])
except ValueError:
# one of the 'key:value' pairs was missing
logger.info('Invalid tags passed: %s', tags)
dtags = {}
return dt... |
<SYSTEM_TASK:>
Update stats to a server.
<END_TASK>
<USER_TASK:>
Description:
def update(self, stats):
"""Update stats to a server.
The method builds two lists: names and values
and calls the export method to export the stats.
Note: this class can be overwrite (for example in CSV and G... |
if not self.export_enable:
return False
# Get all the stats & limits
all_stats = stats.getAllExportsAsDict(plugin_list=self.plugins_to_export())
all_limits = stats.getAllLimitsAsDict(plugin_list=self.plugins_to_export())
# Loop over plugins to export
for pl... |
<SYSTEM_TASK:>
Set the stats to the input_stats one.
<END_TASK>
<USER_TASK:>
Description:
def _set_stats(self, input_stats):
"""Set the stats to the input_stats one.""" |
# Build the all_stats with the get_raw() method of the plugins
return {p: self._plugins[p].get_raw() for p in self._plugins if self._plugins[p].is_enable()} |
<SYSTEM_TASK:>
Init the connection to the InfluxDB server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the InfluxDB server.""" |
if not self.export_enable:
return None
try:
db = InfluxDBClient(host=self.host,
port=self.port,
username=self.user,
password=self.password,
database=s... |
<SYSTEM_TASK:>
Normalize data for the InfluxDB's data model.
<END_TASK>
<USER_TASK:>
Description:
def _normalize(self, name, columns, points):
"""Normalize data for the InfluxDB's data model.""" |
for i, _ in enumerate(points):
# Supported type:
# https://docs.influxdata.com/influxdb/v1.5/write_protocols/line_protocol_reference/
if points[i] is None:
# Ignore points with None value
del(points[i])
del(columns[i])
... |
<SYSTEM_TASK:>
Write the points to the InfluxDB server.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the InfluxDB server.""" |
# Manage prefix
if self.prefix is not None:
name = self.prefix + '.' + name
# Write input to the InfluxDB database
try:
self.client.write_points(self._normalize(name, columns, points))
except Exception as e:
logger.error("Cannot export {} stat... |
<SYSTEM_TASK:>
Return True if the process item match the current filter
<END_TASK>
<USER_TASK:>
Description:
def is_filtered(self, process):
"""Return True if the process item match the current filter
The proces item is a dict.
""" |
if self.filter is None:
# No filter => Not filtered
return False
if self.filter_key is None:
# Apply filter on command line and process name
return self._is_process_filtered(process, key='name') or \
self._is_process_filtered(process, key... |
<SYSTEM_TASK:>
Load the password from the configuration file.
<END_TASK>
<USER_TASK:>
Description:
def load(self, config):
"""Load the password from the configuration file.""" |
password_dict = {}
if config is None:
logger.warning("No configuration file available. Cannot load password list.")
elif not config.has_section(self._section):
logger.warning("No [%s] section in the configuration file. Cannot load password list." % self._section)
... |
<SYSTEM_TASK:>
Get GPU device memory consumption in percent.
<END_TASK>
<USER_TASK:>
Description:
def get_mem(device_handle):
"""Get GPU device memory consumption in percent.""" |
try:
memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle)
return memory_info.used * 100.0 / memory_info.total
except pynvml.NVMLError:
return None |
<SYSTEM_TASK:>
Overwrite the exit method to close the GPU API.
<END_TASK>
<USER_TASK:>
Description:
def exit(self):
"""Overwrite the exit method to close the GPU API.""" |
if self.nvml_ready:
try:
pynvml.nvmlShutdown()
except Exception as e:
logger.debug("pynvml failed to shutdown correctly ({})".format(e))
# Call the father exit method
super(Plugin, self).exit() |
<SYSTEM_TASK:>
Get stats from Glances server.
<END_TASK>
<USER_TASK:>
Description:
def update_glances(self):
"""Get stats from Glances server.
Return the client/server connection status:
- Connected: Connection OK
- Disconnected: Connection NOK
""" |
# Update the stats
try:
server_stats = json.loads(self.client.getAll())
except socket.error:
# Client cannot get server stats
return "Disconnected"
except Fault:
# Client cannot get server stats (issue #375)
return "Disconnecte... |
<SYSTEM_TASK:>
Manage limits of the folder list.
<END_TASK>
<USER_TASK:>
Description:
def get_alert(self, stat, header=""):
"""Manage limits of the folder list.""" |
if not isinstance(stat['size'], numbers.Number):
ret = 'DEFAULT'
else:
ret = 'OK'
if stat['critical'] is not None and \
stat['size'] > int(stat['critical']) * 1000000:
ret = 'CRITICAL'
elif stat['warning'] is not None and \... |
<SYSTEM_TASK:>
A safe function for creating a directory tree.
<END_TASK>
<USER_TASK:>
Description:
def safe_makedirs(path):
"""A safe function for creating a directory tree.""" |
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise |
<SYSTEM_TASK:>
Set the plugin list according to the Glances server.
<END_TASK>
<USER_TASK:>
Description:
def set_plugins(self, input_plugins):
"""Set the plugin list according to the Glances server.""" |
header = "glances_"
for item in input_plugins:
# Import the plugin
try:
plugin = __import__(header + item)
except ImportError:
# Server plugin can not be imported from the client side
logger.error("Can not import {} plu... |
<SYSTEM_TASK:>
Init the connection to the RESTful server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the RESTful server.""" |
if not self.export_enable:
return None
# Build the RESTful URL where the stats will be posted
url = '{}://{}:{}{}'.format(self.protocol,
self.host,
self.port,
self.path)
... |
<SYSTEM_TASK:>
Init the monitored folder list.
<END_TASK>
<USER_TASK:>
Description:
def __set_folder_list(self, section):
"""Init the monitored folder list.
The list is defined in the Glances configuration file.
""" |
for l in range(1, self.__folder_list_max_size + 1):
value = {}
key = 'folder_' + str(l) + '_'
# Path is mandatory
value['indice'] = str(l)
value['path'] = self.config.get_value(section, key + 'path')
if value['path'] is None:
... |
<SYSTEM_TASK:>
Return the size of the directory given by path
<END_TASK>
<USER_TASK:>
Description:
def __folder_size(self, path):
"""Return the size of the directory given by path
path: <string>""" |
ret = 0
for f in scandir(path):
if f.is_dir() and (f.name != '.' or f.name != '..'):
ret += self.__folder_size(os.path.join(path, f.name))
else:
try:
ret += f.stat().st_size
except OSError:
... |
<SYSTEM_TASK:>
Close the socket and context
<END_TASK>
<USER_TASK:>
Description:
def exit(self):
"""Close the socket and context""" |
if self.client is not None:
self.client.close()
if self.context is not None:
self.context.destroy() |
<SYSTEM_TASK:>
Write the points to the ZeroMQ server.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the ZeroMQ server.""" |
logger.debug("Export {} stats to ZeroMQ".format(name))
# Create DB input
data = dict(zip(columns, points))
# Do not publish empty stats
if data == {}:
return False
# Glances envelopes the stats in a publish message with two frames:
# - First frame ... |
<SYSTEM_TASK:>
Init the connection to the Cassandra server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the Cassandra server.""" |
if not self.export_enable:
return None
# if username and/or password are not set the connection will try to connect with no auth
auth_provider = PlainTextAuthProvider(
username=self.username, password=self.password)
# Cluster
try:
cluster = ... |
<SYSTEM_TASK:>
Write the points to the Cassandra cluster.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the Cassandra cluster.""" |
logger.debug("Export {} stats to Cassandra".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in dict(zip(columns, points)).iteritems() if isinstance(v, Number)}
# Write input to the Cassandra table
try:
... |
<SYSTEM_TASK:>
Try to determine the name of a Linux distribution.
<END_TASK>
<USER_TASK:>
Description:
def _linux_os_release():
"""Try to determine the name of a Linux distribution.
This function checks for the /etc/os-release file.
It takes the name from the 'NAME' field and the version from 'VERSION_ID'.... |
pretty_name = ''
ashtray = {}
keys = ['NAME', 'VERSION_ID']
try:
with open(os.path.join('/etc', 'os-release')) as f:
for line in f:
for key in keys:
if line.startswith(key):
ashtray[key] = re.sub(r'^"|"$', '', line.strip().... |
<SYSTEM_TASK:>
Return the alert status relative to the process number.
<END_TASK>
<USER_TASK:>
Description:
def get_alert(self, nbprocess=0, countmin=None, countmax=None, header="", log=False):
"""Return the alert status relative to the process number.""" |
if nbprocess is None:
return 'OK'
if countmin is None:
countmin = nbprocess
if countmax is None:
countmax = nbprocess
if nbprocess > 0:
if int(countmin) <= int(nbprocess) <= int(countmax):
return 'OK'
else:
... |
<SYSTEM_TASK:>
Return the alert status relative to the port scan return value.
<END_TASK>
<USER_TASK:>
Description:
def get_ports_alert(self, port, header="", log=False):
"""Return the alert status relative to the port scan return value.""" |
ret = 'OK'
if port['status'] is None:
ret = 'CAREFUL'
elif port['status'] == 0:
ret = 'CRITICAL'
elif (isinstance(port['status'], (float, int)) and
port['rtt_warning'] is not None and
port['status'] > port['rtt_warning']):
... |
<SYSTEM_TASK:>
Return the plugins list.
<END_TASK>
<USER_TASK:>
Description:
def getPluginsList(self, enable=True):
"""Return the plugins list.
if enable is True, only return the active plugins (default)
if enable is False, return all the plugins
Return: list of plugin name
""" |
if enable:
return [p for p in self._plugins if self._plugins[p].is_enable()]
else:
return [p for p in self._plugins] |
<SYSTEM_TASK:>
Return the exports list.
<END_TASK>
<USER_TASK:>
Description:
def getExportsList(self, enable=True):
"""Return the exports list.
if enable is True, only return the active exporters (default)
if enable is False, return all the exporters
Return: list of export module name
... |
if enable:
return [e for e in self._exports]
else:
return [e for e in self._exports_all] |
<SYSTEM_TASK:>
Export all the stats.
<END_TASK>
<USER_TASK:>
Description:
def export(self, input_stats=None):
"""Export all the stats.
Each export module is ran in a dedicated thread.
""" |
# threads = []
input_stats = input_stats or {}
for e in self._exports:
logger.debug("Export stats using the %s module" % e)
thread = threading.Thread(target=self._exports[e].update,
args=(input_stats,))
# threads.append(... |
<SYSTEM_TASK:>
Init the connection to the ES server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the ES server.""" |
if not self.export_enable:
return None
self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
template_body = {
"mappings": {
"glances": {
"dynamic_templates": [
{
"integers": {
... |
<SYSTEM_TASK:>
Write the points to the ES server.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the ES server.""" |
logger.debug("Export {} stats to ElasticSearch".format(name))
# Create DB input
# https://elasticsearch-py.readthedocs.io/en/master/helpers.html
actions = []
for c, p in zip(columns, points):
dtnow = datetime.utcnow()
action = {
"_index":... |
<SYSTEM_TASK:>
Get the first public IP address returned by one of the online services.
<END_TASK>
<USER_TASK:>
Description:
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() > ... |
<SYSTEM_TASK:>
Request the url service and put the result in the queue_target.
<END_TASK>
<USER_TASK:>
Description:
def _get_ip_public(self, queue_target, url, json=False, key=None):
"""Request the url service and put the result in the queue_target.""" |
try:
response = urlopen(url, timeout=self.timeout).read().decode('utf-8')
except Exception as e:
logger.debug("IP plugin - Cannot open URL {} ({})".format(url, e))
queue_target.put(None)
else:
# Request depend on service
try:
... |
<SYSTEM_TASK:>
Init the connection to the Kafka server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the Kafka server.""" |
if not self.export_enable:
return None
# Build the server URI with host and port
server_uri = '{}:{}'.format(self.host, self.port)
try:
s = KafkaProducer(bootstrap_servers=server_uri,
value_serializer=lambda v: json.dumps(v).encode... |
<SYSTEM_TASK:>
Write the points to the kafka server.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the kafka server.""" |
logger.debug("Export {} stats to Kafka".format(name))
# Create DB input
data = dict(zip(columns, points))
# Send stats to the kafka topic
# key=<plugin name>
# value=JSON dict
try:
self.client.send(self.topic,
key=name,
... |
<SYSTEM_TASK:>
Specific case for io_counters
<END_TASK>
<USER_TASK:>
Description:
def _sort_io_counters(process,
sortedby='io_counters',
sortedby_secondary='memory_percent'):
"""Specific case for io_counters
Sum of io_r + io_w""" |
return process[sortedby][0] - process[sortedby][2] + process[sortedby][1] - process[sortedby][3] |
<SYSTEM_TASK:>
Return a sort lambda function for the sortedbykey
<END_TASK>
<USER_TASK:>
Description:
def _sort_lambda(sortedby='cpu_percent',
sortedby_secondary='memory_percent'):
"""Return a sort lambda function for the sortedbykey""" |
ret = None
if sortedby == 'io_counters':
ret = _sort_io_counters
elif sortedby == 'cpu_times':
ret = _sort_cpu_times
return ret |
<SYSTEM_TASK:>
Update the global process count from the current processes list
<END_TASK>
<USER_TASK:>
Description:
def update_processcount(self, plist):
"""Update the global process count from the current processes list""" |
# Update the maximum process ID (pid) number
self.processcount['pid_max'] = self.pid_max
# For each key in the processcount dict
# count the number of processes with the same status
for k in iterkeys(self.processcount):
self.processcount[k] = len(list(filter(lambda v... |
<SYSTEM_TASK:>
Get the maximum PID value.
<END_TASK>
<USER_TASK:>
Description:
def pid_max(self):
"""
Get the maximum PID value.
On Linux, the value is read from the `/proc/sys/kernel/pid_max` file.
From `man 5 proc`:
The default value for this file, 32768, results in the same ... |
if LINUX:
# XXX: waiting for https://github.com/giampaolo/psutil/issues/720
try:
with open('/proc/sys/kernel/pid_max', 'rb') as f:
return int(f.read())
except (OSError, IOError):
return None
else:
return... |
<SYSTEM_TASK:>
Convert seconds to human-readable time.
<END_TASK>
<USER_TASK:>
Description:
def seconds_to_hms(input_seconds):
"""Convert seconds to human-readable time.""" |
minutes, seconds = divmod(input_seconds, 60)
hours, minutes = divmod(minutes, 60)
hours = int(hours)
minutes = int(minutes)
seconds = str(int(seconds)).zfill(2)
return hours, minutes, seconds |
<SYSTEM_TASK:>
Return path, cmd and arguments for a process cmdline.
<END_TASK>
<USER_TASK:>
Description:
def split_cmdline(cmdline):
"""Return path, cmd and arguments for a process cmdline.""" |
path, cmd = os.path.split(cmdline[0])
arguments = ' '.join(cmdline[1:])
return path, cmd, arguments |
<SYSTEM_TASK:>
Return the alert relative to the Nice configuration list
<END_TASK>
<USER_TASK:>
Description:
def get_nice_alert(self, value):
"""Return the alert relative to the Nice configuration list""" |
value = str(value)
try:
if value in self.get_limit('nice_critical'):
return 'CRITICAL'
except KeyError:
pass
try:
if value in self.get_limit('nice_warning'):
return 'WARNING'
except KeyError:
pass
... |
<SYSTEM_TASK:>
Build the header and add it to the ret dict.
<END_TASK>
<USER_TASK:>
Description:
def __msg_curse_header(self, ret, process_sort_key, args=None):
"""Build the header and add it to the ret dict.""" |
sort_style = 'SORT'
if args.disable_irix and 0 < self.nb_log_core < 10:
msg = self.layout_header['cpu'].format('CPU%/' + str(self.nb_log_core))
elif args.disable_irix and self.nb_log_core != 0:
msg = self.layout_header['cpu'].format('CPU%/C')
else:
m... |
<SYSTEM_TASK:>
Return the sum of the stats value for the given key.
<END_TASK>
<USER_TASK:>
Description:
def __sum_stats(self, key, indice=None, mmm=None):
"""Return the sum of the stats value for the given key.
* indice: If indice is set, get the p[key][indice]
* mmm: display min, max, mean or... |
# Compute stats summary
ret = 0
for p in self.stats:
if key not in p:
# Correct issue #1188
continue
if p[key] is None:
# Correct https://github.com/nicolargo/glances/issues/1105#issuecomment-363553788
conti... |
<SYSTEM_TASK:>
Build and return the header line
<END_TASK>
<USER_TASK:>
Description:
def build_header(self, plugin, attribute, stat):
"""Build and return the header line""" |
line = ''
if attribute is not None:
line += '{}.{}{}'.format(plugin, attribute, self.separator)
else:
if isinstance(stat, dict):
for k in stat.keys():
line += '{}.{}{}'.format(plugin,
str(k... |
<SYSTEM_TASK:>
Build and return the data line
<END_TASK>
<USER_TASK:>
Description:
def build_data(self, plugin, attribute, stat):
"""Build and return the data line""" |
line = ''
if attribute is not None:
line += '{}{}'.format(str(stat.get(attribute, self.na)),
self.separator)
else:
if isinstance(stat, dict):
for v in stat.values():
line += '{}{}'.format(str(v), self... |
<SYSTEM_TASK:>
Init the connection to the Riemann server.
<END_TASK>
<USER_TASK:>
Description:
def init(self):
"""Init the connection to the Riemann server.""" |
if not self.export_enable:
return None
try:
client = bernhard.Client(host=self.host, port=self.port)
return client
except Exception as e:
logger.critical("Connection to Riemann failed : %s " % e)
return None |
<SYSTEM_TASK:>
Write the points in Riemann.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points in Riemann.""" |
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
else:
data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]}
logger.debug(data)
try:
self.cli... |
<SYSTEM_TASK:>
Write the points to the CouchDB server.
<END_TASK>
<USER_TASK:>
Description:
def export(self, name, columns, points):
"""Write the points to the CouchDB server.""" |
logger.debug("Export {} stats to CouchDB".format(name))
# Create DB input
data = dict(zip(columns, points))
# Set the type to the current stat name
data['type'] = name
data['time'] = couchdb.mapping.DateTimeField()._to_json(datetime.now())
# Write input to the... |
<SYSTEM_TASK:>
Update core stats.
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update core stats.
Stats is a dict (with both physical and log cpu number) instead of a integer.
""" |
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the standard system lib
# The psutil 2.0 include psutil.cpu_count() and psutil.cpu_count(logical=False)
# Return a dict with:
# - phys: physical... |
<SYSTEM_TASK:>
Return the current sort in the loop
<END_TASK>
<USER_TASK:>
Description:
def loop_position(self):
"""Return the current sort in the loop""" |
for i, v in enumerate(self._sort_loop):
if v == glances_processes.sort_key:
return i
return 0 |
<SYSTEM_TASK:>
Disable the full quicklook mode
<END_TASK>
<USER_TASK:>
Description:
def enable_fullquicklook(self):
"""Disable the full quicklook mode""" |
self.args.disable_quicklook = False
for p in ['cpu', 'gpu', 'mem', 'memswap']:
setattr(self.args, 'disable_' + p, True) |
<SYSTEM_TASK:>
Shutdown the curses window.
<END_TASK>
<USER_TASK:>
Description:
def end(self):
"""Shutdown the curses window.""" |
if hasattr(curses, 'echo'):
curses.echo()
if hasattr(curses, 'nocbreak'):
curses.nocbreak()
if hasattr(curses, 'curs_set'):
try:
curses.curs_set(1)
except Exception:
pass
curses.endwin() |
<SYSTEM_TASK:>
Display stats on the screen.
<END_TASK>
<USER_TASK:>
Description:
def display(self, stats, cs_status=None):
"""Display stats on the screen.
stats: Stats database to display
cs_status:
"None": standalone or server mode
"Connected": Client is connected to a ... |
# Init the internal line/column for Glances Curses
self.init_line_column()
# Update the stats messages
###########################
# Get all the plugins but quicklook and proceslist
self.args.cs_status = cs_status
__stat_display = self.__get_stat_display(stats,... |
<SYSTEM_TASK:>
Display the left sidebar in the Curses interface.
<END_TASK>
<USER_TASK:>
Description:
def __display_left(self, stat_display):
"""Display the left sidebar in the Curses interface.""" |
self.init_column()
if self.args.disable_left_sidebar:
return
for s in self._left_sidebar:
if ((hasattr(self.args, 'enable_' + s) or
hasattr(self.args, 'disable_' + s)) and s in stat_display):
self.new_line()
self.display... |
<SYSTEM_TASK:>
Display the right sidebar in the Curses interface.
<END_TASK>
<USER_TASK:>
Description:
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:
return
# Restore line position
self.next_line = self.saved_line
# Display right sidebar
self.new_column()
for p in self._right_sideba... |
<SYSTEM_TASK:>
Display a centered popup.
<END_TASK>
<USER_TASK:>
Description:
def display_popup(self, message,
size_x=None, size_y=None,
duration=3,
is_input=False,
input_size=30,
input_value=None):
"""... |
# Center the popup
sentence_list = message.split('\n')
if size_x is None:
size_x = len(max(sentence_list, key=len)) + 4
# Add space for the input field
if is_input:
size_x += input_size
if size_y is None:
size_y = len(sente... |
<SYSTEM_TASK:>
Display the plugin_stats on the screen.
<END_TASK>
<USER_TASK:>
Description:
def display_plugin(self, plugin_stats,
display_optional=True,
display_additional=True,
max_y=65535,
add_space=0):
"""Display the... |
# Exit if:
# - the plugin_stats message is empty
# - the display tag = False
if plugin_stats is None or not plugin_stats['msgdict'] or not plugin_stats['display']:
# Exit
return 0
# Get the screen size
screen_x = self.screen.getmaxyx()[1]
... |
<SYSTEM_TASK:>
Clear and update the screen.
<END_TASK>
<USER_TASK:>
Description:
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 ... |
self.erase()
self.display(stats, cs_status=cs_status) |
<SYSTEM_TASK:>
Update the screen.
<END_TASK>
<USER_TASK:>
Description:
def update(self,
stats,
duration=3,
cs_status=None,
return_to_browser=False):
"""Update the screen.
INPUT
stats: Stats database to display
duration: duratio... |
# 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.')
dura... |
<SYSTEM_TASK:>
Return the width of the formatted curses message.
<END_TASK>
<USER_TASK:>
Description:
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['optional'] else "")
for i in curse_msg['msgdict']]).split('\n'), key=len))
else:
... |
<SYSTEM_TASK:>
r"""Return the height of the formatted curses message.
<END_TASK>
<USER_TASK:>
Description:
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.debug('ERROR: Can not compute plugin height ({})'.format(e))
return 0
else:
return c + 1 |
<SYSTEM_TASK:>
SNMP getbulk request.
<END_TASK>
<USER_TASK:>
Description:
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 transac... |
if self.version.startswith('3'):
errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
cmdgen.UsmUserData(self.user, self.auth),
cmdgen.UdpTransportTarget((self.host, self.port)),
non_repeaters,
max_repetitions,
... |
<SYSTEM_TASK:>
Load the server list from the configuration file.
<END_TASK>
<USER_TASK:>
Description:
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] section in the configuration file. Cannot load server list." % self._section)
else:
... |
<SYSTEM_TASK:>
Add a new server to the list.
<END_TASK>
<USER_TASK:>
Description:
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 port
'username': 'glances', # Default username
'password': ... |
<SYSTEM_TASK:>
Remove a server from the dict.
<END_TASK>
<USER_TASK:>
Description:
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("Updated servers list (%s servers): %s" % (
len(se... |
<SYSTEM_TASK:>
Method called when a new Zeroconf client is detected.
<END_TASK>
<USER_TASK:>
Description:
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 wi... |
if srv_type != zeroconf_type:
return False
logger.debug("Check new Zeroconf server: %s / %s" %
(srv_type, srv_name))
info = zeroconf.get_service_info(srv_type, srv_name)
if info:
new_server_ip = socket.inet_ntoa(info.address)
new_... |
<SYSTEM_TASK:>
Remove the server from the list.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Try to find the active IP addresses.
<END_TASK>
<USER_TASK:>
Description:
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)[netifaces.AF_INET][0]['addr'] |
<SYSTEM_TASK:>
Compress result with deflate algorithm if the client ask for it.
<END_TASK>
<USER_TASK:>
Description:
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(
request.method,
request.url,
['{}: {}'.format(h, request.headers.... |
<SYSTEM_TASK:>
Load the outputs section of the configuration file.
<END_TASK>
<USER_TASK:>
Description:
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('Numb... |
<SYSTEM_TASK:>
Main entry point for Glances.
<END_TASK>
<USER_TASK:>
Description:
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('{} {} and psutil {} detected'.format(
platform.python_implementation(),
platform.python_version(),
psut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.