Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
plt.grid(True)
# Points are stored as tuple (date, value)
x, y = zip(*h[i['name']])
plt.plot_date(x, y,
fmt='', drawstyle='default', linestyle='-',
color=self.get_graph_color(i),
xdate=True, ydate=False)
if index_graph == 1:
# Title only on top of the first graph
plt.title(p.capitalize())
else:
# The key did not exist
# Find if anothers key ends with the key
# Ex: key='tx' => 'ethernet_tx'
# Add one curve per chart
stats_history_filtered = sorted([key for key in iterkeys(h) if key.endswith('_' + i['name'])])
logger.debug("Generate graphs: %s %s" %
(p, stats_history_filtered))
if len(stats_history_filtered) > 0:
# Create 'n' graph
# Each graph iter through the stats
plt.clf()
index_item = 0
for k in stats_history_filtered:
index_item += 1
plt.subplot(
len(stats_history_filtered), 1, index_item)
# Legend
plt.ylabel(self.get_graph_yunit(i, pre_label=k))
# Curves
plt.grid(True)
# Points are stored as tuple (date, value)
for p in stats.getPluginsList():
# History
h = stats.get_plugin(p).get_export_history()
# Current plugin item history list
ih = stats.get_plugin(p).get_items_history_list()
# Check if we must process history
if h is None or ih is None:
# History (h) not available for plugin (p)
continue
# Init graph
plt.clf()
index_graph = 0
handles = []
labels = []
for i in ih:
if i['name'] in iterkeys(h):
# The key exist
# Add the curves in the current chart
logger.debug("Generate graph: %s %s" % (p, i['name']))
index_graph += 1
# Labels
handles.append(plt.Rectangle((0, 0), 1, 1, fc=self.get_graph_color(i), ec=self.get_graph_color(i), linewidth=2))
labels.append(self.get_graph_legend(i))
# Legend
plt.ylabel(self.get_graph_yunit(i, pre_label=''))
# Curves
plt.grid(True)
# Points are stored as tuple (date, value)
x, y = zip(*h[i['name']])
plt.plot_date(x, y,
fmt='', drawstyle='default', linestyle='-',
color=self.get_graph_color(i),
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: v['status'] is k,
plist)))
# Compute thread
self.processcount['thread'] = sum(i['num_threads'] for i in plist
if i['num_threads'] is not None)
# Compute total
self.processcount['total'] = len(plist)
def __build_export(self, stats):
"""Build the export lists."""
export_names = []
export_values = []
if isinstance(stats, dict):
# Stats is a dict
# Is there a key ?
if 'key' in iterkeys(stats) and stats['key'] in iterkeys(stats):
pre_key = '{}.'.format(stats[stats['key']])
else:
pre_key = ''
# Walk through the dict
for key, value in iteritems(stats):
if isinstance(value, bool):
value = json.dumps(value)
if isinstance(value, list):
try:
value = value[0]
except IndexError:
value = ''
if isinstance(value, dict):
item_names, item_values = self.__build_export(value)
item_names = [pre_key + key.lower() + str(i) for i in item_names]
export_names += item_names
def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Optional
for key in iterkeys(self.stats):
self.views[key]['optional'] = True
csv_data = [time.strftime('%Y-%m-%d %H:%M:%S')]
# Loop over plugins to export
for plugin in self.plugins_to_export():
if isinstance(all_stats[plugin], list):
for stat in all_stats[plugin]:
# First line: header
if self.first_line:
csv_header += ('{}_{}_{}'.format(
plugin, self.get_item_key(stat), item) for item in stat)
# Others lines: stats
csv_data += itervalues(stat)
elif isinstance(all_stats[plugin], dict):
# First line: header
if self.first_line:
fieldnames = iterkeys(all_stats[plugin])
csv_header += ('{}_{}'.format(plugin, fieldname)
for fieldname in fieldnames)
# Others lines: stats
csv_data += itervalues(all_stats[plugin])
# Export to CSV
# Manage header
if self.first_line:
if self.old_header is None:
# New file, write the header on top on the CSV file
self.writer.writerow(csv_header)
# File already exist, check if header are compatible
if self.old_header != csv_header:
# Header are differents, log an error and do not write data
logger.error("Cannot append data to existing CSV file. Headers are differents.")
logger.debug("Old header: {}".format(self.old_header))
if not self.stats or self.is_disable():
return ret
# Max size for the interface name
name_max_width = max_width - 12
# Header
msg = '{:{width}}'.format('RAID disks',
width=name_max_width)
ret.append(self.curse_add_line(msg, "TITLE"))
msg = '{:>7}'.format('Used')
ret.append(self.curse_add_line(msg))
msg = '{:>7}'.format('Avail')
ret.append(self.curse_add_line(msg))
# Data
arrays = sorted(iterkeys(self.stats))
for array in arrays:
# New line
ret.append(self.curse_new_line())
# Display the current status
status = self.raid_alert(self.stats[array]['status'],
self.stats[array]['used'],
self.stats[array]['available'],
self.stats[array]['type'])
# Data: RAID type name | disk used | disk available
array_type = self.stats[array]['type'].upper() if self.stats[array]['type'] is not None else 'UNKNOWN'
# Build the full name = array type + array name
full_name = '{} {}'.format(array_type, array)
msg = '{:{width}}'.format(full_name,
width=name_max_width)
ret.append(self.curse_add_line(msg))
if self.stats[array]['type'] == 'raid0' and self.stats[array]['status'] == 'active':
stats['total'] = int(
fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
stats['used'] = int(
fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
stats['percent'] = float(
stats['used'] * 100 / stats['total'])
stats['free'] = stats['total'] - stats['used']
break
else:
stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])
if stats['total'] == '':
self.reset()
return stats
for key in iterkeys(stats):
if stats[key] != '':
stats[key] = float(stats[key]) * 1024
# used=total-free
stats['used'] = stats['total'] - stats['free']
# percent: the percentage usage calculated as (total -
# available) / total * 100.
stats['percent'] = float(
(stats['total'] - stats['free']) / stats['total'] * 100)
# Update the stats
self.stats = stats
return self.stats