File size: 4,673 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | """One parsed sample (Metrics) and the frame helpers shared by the platform parsers."""
from collections import namedtuple
Core = namedtuple('Core', 'usage mhz')
Mount = namedtuple('Mount', 'device type mount total used avail pct')
Disk = namedtuple('Disk', 'name read_bps write_bps read_iops write_iops util total_read total_written')
Net = namedtuple('Net', 'name state speed virt rx_bps tx_bps rx_pps tx_pps rx_bytes tx_bytes errors drops')
Proc = namedtuple('Proc', 'pid ppid threads nice name user state cpu mem_pct rss vsz age') # cpu: % of one core
Service = namedtuple('Service', 'unit load active sub description')
Temp = namedtuple('Temp', 'name celsius')
Gpu = namedtuple('Gpu', 'index name util mem_used mem_total temp power fan')
class Metrics:
TEXTS = 'hostname os kernel arch cpu_model virt fullest_mount busiest_disk'
NUMBERS = ('cpu_count logged_users procs_running procs_blocked threads_total sockets_used services_failed services_running '
'uptime load1 load5 load15 cpu_usage cpu_user cpu_system cpu_iowait cpu_steal cpu_irq ctxt_per_sec intr_per_sec '
'forks_per_sec avg_mhz mem_total mem_free mem_available mem_used buffers cached shared slab dirty swap_total '
'swap_used mem_pct swap_pct disk_read_bps disk_write_bps max_disk_pct max_disk_util net_rx_bps net_tx_bps max_temp')
LISTS = 'cores mounts disks nets procs services temps gpus'
def __init__(self, timestamp=0):
self.valid, self.timestamp, self.tcp = False, timestamp, {} # tcp: state name -> connections
for names, value in ((self.TEXTS, ''), (self.NUMBERS, 0)):
for k in names.split(): setattr(self, k, value)
for k in self.LISTS.split(): setattr(self, k, [])
def gpu_max(self, temp=False): return max((g.temp if temp else g.util for g in self.gpus), default=0)
def num(s):
"""Number from text; 0 when missing or malformed."""
try: return float(s)
except (TypeError, ValueError): return 0.0
def to_int(s, base=10):
try: return int(str(s).strip(), base)
except ValueError: return 0
def sections(frame):
"""Splits a collector frame into {section name: lines}."""
sec, cur = {}, None
for line in frame.replace('\r', '').split('\n'):
if line.startswith('@@S '): cur = sec.setdefault(line[4:].strip(), [])
elif cur is not None and not line.startswith('@@'): cur.append(line)
return sec
def rates(state, dt):
"""Returns delta(key, counters) -> per-second rates against the previous frame; remembers the new counters."""
prev, state['counters'] = state.get('counters', {}), {}
def delta(key, v):
p = prev.get(key, ())
state['counters'][key] = v
return [max(0.0, (a - b) / dt) for a, b in zip(v, p)] if dt > 0.05 and len(p) == len(v) else [0.0] * len(v)
return delta
def add_disk(m, d, physical=True):
"""Lists a disk; physical ones count towards the totals and the busiest-disk figure."""
m.disks.append(d)
if physical:
m.disk_read_bps += d.read_bps
m.disk_write_bps += d.write_bps
if d.util >= m.max_disk_util: m.max_disk_util, m.busiest_disk = d.util, d.name
def add_mount(m, mt):
m.mounts.append(mt)
if mt.pct >= m.max_disk_pct: m.max_disk_pct, m.fullest_mount = mt.pct, mt.mount
def finish(m, sec, state, temp_unit):
"""What every platform shares: percentages, totals, sensors (value / temp_unit = Celsius), cached GPUs and services, ordering."""
m.mem_pct = m.mem_used * 100 / m.mem_total if m.mem_total > 0 else 0
m.swap_pct = m.swap_used * 100 / m.swap_total if m.swap_total > 0 else 0
m.net_rx_bps, m.net_tx_bps = (sum(getattr(n, k) for n in m.nets if not n.virt) for k in ('rx_bps', 'tx_bps'))
m.threads_total = sum(p.threads for p in m.procs)
if 'gpu' in sec: # nvidia-smi CSV; like the services it arrives every few samples: keep the last list
state['gpus'] = [Gpu(int(num(f[0])), f[1].strip(), *map(num, f[2:8])) for f in (l.split(',') for l in sec['gpu']) if len(f) >= 8]
m.gpus, m.services = state.get('gpus', []), state.get('services', [])
m.services_failed = sum(s.active == 'failed' for s in m.services)
m.services_running = sum(s.sub == 'running' for s in m.services)
for line in sec.get('thermal', ()):
name, _, value = line.rpartition('|')
t = Temp(name.strip(), num(value) / temp_unit)
if name and 0 < t.celsius <= 150 and all(t.name != x.name for x in m.temps): m.temps.append(t)
m.max_temp = max((t.celsius for t in m.temps), default=0)
m.nets.sort(key=lambda n: (n.virt, n.name))
m.procs.sort(key=lambda p: (-p.cpu, -p.rss))
return m
|