File size: 20,280 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | """Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y)
and the statistics-only analyzer that feeds the autopilot."""
import math, os, struct, time
from array import array
from bisect import bisect_left, bisect_right
from collections import namedtuple
import plat
from model import duration, fmt_bytes, pct, rate, rnd, temp
KEYS = 'cpu iowait load mem swap disk diskio rx tx rd wr temp procs gpu failed'.split()
NAMES = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read',
'Disk write', 'Temperature', 'Processes', 'GPU', 'Failed services']
CPU, IOWAIT, LOAD, MEM, SWAP, DISK, DISKIO, RX, TX, RD, WR, TEMP, PROCS, GPU, FAILED = range(15)
H_COUNT, NAN = len(KEYS), math.nan
TIERS, TIER_NAMES = ('raw', 'minute', 'hour', 'day'), ('every sample', '1 minute', '1 hour', '1 day')
STEP, KEEP, MAX_SPAN = (1, 60, 3600, 86400), (6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400), (6 * 3600, 8 * 86400, 400 * 86400)
REC = struct.Struct('<qII15f15f') # ts (bucket start for aggregates), samples, online samples, avg[15], max[15]
HEADER = b'SMH1' + bytes([H_COUNT, 0]) + struct.pack('<H', REC.size)
class Points:
"""Column store of history records: ts, n (samples), up (online samples), avg[metric], max[metric]."""
def __init__(self, rows=(), cols=None):
self.c = cols or [array(t, c) for t, c in zip('qII' + 'f' * 30, zip(*rows) if rows else [()] * 33)]
(self.ts, self.n, self.up), self.avg, self.max = self.c[:3], self.c[3:3 + H_COUNT], self.c[3 + H_COUNT:]
def __len__(self): return len(self.ts)
def add(self, row):
for c, v in zip(self.c, row): c.append(v)
def cut(self, i, j=None): return Points(cols=[c[i:j] for c in self.c])
def rows(self): return zip(*self.c)
class Acc:
"""Running aggregate of one open bucket."""
def __init__(self, bucket=-1):
self.bucket, self.n, self.up = bucket, 0, 0
self.cnt, self.sum, self.max = [0] * H_COUNT, [0.0] * H_COUNT, [NAN] * H_COUNT
def add(self, r):
self.n, self.up = self.n + r[1], self.up + r[2]
for i in range(H_COUNT if r[2] else 0):
avg, mx = r[3 + i], r[3 + H_COUNT + i]
if avg == avg:
self.sum[i] += avg * r[2]
self.cnt[i] += r[2]
if self.max[i] != self.max[i] or mx > self.max[i]: self.max[i] = mx
def row(self): # through the record format, so the values are float32 like the stored ones
return REC.unpack(REC.pack(self.bucket, self.n, self.up, *(s / c if c else NAN for s, c in zip(self.sum, self.cnt)), *self.max))
class Store:
def __init__(self, path):
self.dir, self.tz, self.appends = path, time.localtime().tm_gmtoff, [0] * 4
os.makedirs(path, exist_ok=True)
now = int(time.time())
self.tiers, self.acc = [Points() for _ in TIERS], [Acc() for _ in TIERS]
for t in range(4): self.load(t, now)
for t in (1, 2, 3): # rebuild from finer data what is not stored yet: buckets the last run left open, and the current one
finer, stored = self.tiers[t - 1], self.tiers[t].ts[-1] if len(self.tiers[t]) else -1
for r in [*finer.cut(bisect_right(finer.ts, stored)).rows(), *([self.acc[t - 1].row()] if self.acc[t - 1].n else [])]:
b, a = self.bucket(t, r[0]), self.acc[t]
if b <= stored: continue
if b != a.bucket:
if a.n: self.append(t, a.row())
a = self.acc[t] = Acc(b)
a.add(r)
def file(self, t): return os.path.join(self.dir, TIERS[t] + '.bin')
def bucket(self, t, ts): return (ts + self.tz) // 86400 * 86400 - self.tz if t == 3 else ts // STEP[t] * STEP[t] # days start at local midnight
def load(self, t, now):
try:
with open(self.file(t), 'rb') as f: data = f.read()
except OSError:
return
if not data.startswith(HEADER): return os.replace(self.file(t), self.file(t) + '.old')
rows, last = [], -1
for r in REC.iter_unpack(data[len(HEADER):len(data) - (len(data) - len(HEADER)) % REC.size]):
if now - KEEP[t] <= r[0] <= now + 86400 and r[0] > last:
rows.append(r)
last = r[0]
self.tiers[t] = Points(rows)
if len(HEADER) + len(rows) * REC.size != len(data): # expired or damaged records, or a cut-off one that would misalign what is appended
self.rewrite(t)
def rewrite(self, t):
try:
with open(self.file(t) + '.tmp', 'wb') as f: f.write(HEADER + b''.join(REC.pack(*r) for r in self.tiers[t].rows()))
os.replace(self.file(t) + '.tmp', self.file(t))
except OSError:
pass # history stays in memory when the disk is full or read-only
def append(self, t, row):
p = self.tiers[t]
if len(p) and row[0] <= p.ts[-1]: return
p.add(row)
try:
with open(self.file(t), 'ab') as f:
if f.tell() < len(HEADER):
f.truncate(0)
f.write(HEADER)
f.write(REC.pack(*row))
except OSError:
pass
self.appends[t] += 1
if self.appends[t] % 500 == 0: # trim expired points now and then
k = bisect_left(p.ts, row[0] - KEEP[t])
if k:
self.tiers[t] = p.cut(k)
self.rewrite(t)
def add(self, ts, values, up):
"""Records one sample; up=False records downtime only."""
v = values if up else [NAN] * H_COUNT
raw = REC.unpack(REC.pack(ts, 1, int(up), *v, *v))
self.append(0, raw)
for t in (1, 2, 3): # every coarser tier accumulates every raw sample
b, a = self.bucket(t, ts), self.acc[t]
if a.bucket != b:
if a.n and a.bucket < b: self.append(t, a.row())
a = self.acc[t] = Acc(b)
a.add(raw)
def range(self, frm, to, t):
"""Points of tier t in [frm, to], including the open bucket."""
p, a = self.tiers[t], self.acc[t]
out = p.cut(bisect_left(p.ts, frm), bisect_right(p.ts, to))
if t and a.n and frm <= a.bucket <= to and (not len(out) or out.ts[-1] < a.bucket): out.add(a.row())
return out
def span(self, frm, to):
"""(points, tier) from the finest tier that covers the range."""
now, t = int(time.time()), 0
while t < 3 and (frm < now - KEEP[t] or to - frm > MAX_SPAN[t]): t += 1
return self.range(frm, to, t), t
def first_ts(self): return min((p.ts[0] for p in self.tiers if len(p)), default=0)
def disk_bytes(self): return sum(os.path.getsize(self.file(t)) for t in range(4) if os.path.exists(self.file(t)))
Stats = namedtuple('Stats', 'min avg p95 max count', defaults=(NAN, NAN, NAN, NAN, 0)) # max = peak of max[]
def stats(p, m):
v = [(a, x, u) for a, x, u in zip(p.avg[m], p.max[m], p.up) if u and a == a]
if not v: return Stats()
a = sorted(r[0] for r in v)
return Stats(a[0], sum(r[0] * r[2] for r in v) / sum(r[2] for r in v), a[min(len(a) - 1, int(len(a) * 0.95))], max(r[1] for r in v), len(a))
def regression(p, m):
"""Least-squares (slope per second, squared correlation) of a metric over time."""
xy = [(t - p.ts[0], y) for t, y, u in zip(p.ts, p.avg[m], p.up) if u and y == y]
n, sx, sy = len(xy), sum(x for x, _ in xy), sum(y for _, y in xy)
den, num, vy = n * sum(x * x for x, _ in xy) - sx * sx, n * sum(x * y for x, y in xy) - sx * sy, n * sum(y * y for _, y in xy) - sy * sy
if n < 3 or den <= 0: return 0.0, 0.0
return num / den, num * num / (den * vy) if vy > 1e-9 else 0.0
def slot(ts):
"""(weekday, hour) of a timestamp in local time; Monday = 0."""
t = time.localtime(ts)
return t.tm_wday, t.tm_hour
def fmt_metric(m, v):
if v != v: return '—'
return rate(v) if m in (RX, TX, RD, WR) else f'{v:.2f}' if m == LOAD else temp(v) if m == TEMP else f'{v:.0f}' if m in (PROCS, FAILED) else pct(v)
# ---- analysis -------------------------------------------------------------------
# action: disk_cleanup | restart_service | renice | kill_pid
Finding = namedtuple('Finding', 'key severity category title detail advice action arg label auto')
ProcTrend = namedtuple('ProcTrend', 'pid minutes name user cpu_now high_cpu_minutes rss_now rss_growth rss_growth_pct rss_monotonic protected',
defaults=(0, 0, '', '', 0, 0, 0, 0, 0, 0, False))
ServiceTrend = namedtuple('ServiceTrend', 'unit failed_now preexisting fails_last_hour auto_restarts_last_hour')
Anomaly = namedtuple('Anomaly', 'metric baseline hm now mean sd z')
class Analysis:
def __init__(self):
self.when, self.health, self.grade, self.disk_basis = 0, 100, 'A', ''
self.reasons, self.capacity, self.findings, self.anomalies = [], [], [], []
self.disk_full_days, self.disk_slope_per_day, self.mem_slope_per_hour, self.mem_trend_r2 = -1, 0, 0, 0
self.up, self.down, self.cpu30, self.mem30 = [NAN] * 3, [0] * 3, Stats(), Stats() # 24 h, 7 d, 30 d: availability %, seconds offline
self.heat = [[[NAN] * 24 for _ in range(7)] for _ in range(2)] # weekly pattern: 0 = CPU, 1 = memory
self.heat_n = [[0] * 24 for _ in range(7)]
def analyze(st, m, ap, procs, svcs, online):
a = Analysis()
now = a.when = int(time.time())
minute, hour, cores = st.tiers[1], st.tiers[2], max(1, m.cpu_count)
def add(key, sev, cat, title, detail, advice, action='', arg='', label='', auto=False):
a.findings.append(Finding(key, sev, cat, title, detail, advice, action, arg, label, bool(auto)))
def sev(crit, warn): return 'critical' if crit else 'warning' if warn else 'info'
# availability
spans = (86400, 7 * 86400, 30 * 86400)
for i, span in enumerate(spans):
p = st.span(now - span, now)[0]
n, up = sum(p.n), sum(p.up)
if n: a.up[i], a.down[i] = up * 100 / n, (n - up) / n * min(span, now - st.first_ts()) # share of the monitored part of the window
if a.up[0] < 99:
add('avail24', sev(a.up[0] < 95, True), 'Availability', f'Availability last 24 h is {pct(a.up[0], 2)}',
f'The server could not be reached for about {duration(a.down[0])} in the last day.',
'Check network stability, power and whether the machine rebooted (uptime).')
w30, w7 = st.range(now - spans[2], now, 2), st.range(now - spans[1], now, 1)
a.cpu30, a.mem30 = (stats(w30 if len(w30) >= 24 else w7, k) for k in (CPU, MEM))
# disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better
slope = r2 = 0.0
week, day = st.range(now - spans[1], now, 2), st.range(now - 86400, now, 1)
if len(week) >= 48: (slope, r2), a.disk_basis = regression(week, DISK), 'hourly averages, last 7 days'
if len(day) >= 120:
s2, r2b = regression(day, DISK)
if len(week) < 48 or r2b > r2: slope, r2, a.disk_basis = s2, r2b, 'minute averages, last 24 hours'
a.disk_slope_per_day = slope * 86400
if a.disk_slope_per_day > 0.05 and r2 >= 0.3 and m.max_disk_pct > 0: a.disk_full_days = (100 - m.max_disk_pct) / a.disk_slope_per_day
if 0 <= a.disk_full_days < 30:
add('diskfull', sev(a.disk_full_days < ap.diskForecastDays, a.disk_full_days < 14), 'Disk',
f'Disk {m.fullest_mount} will be full in {duration(a.disk_full_days * 86400)}',
f'Usage {pct(m.max_disk_pct)}, growing {a.disk_slope_per_day:.2f} points/day (trend from {a.disk_basis}, fit R² {r2:.2f}).',
'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup',
ap.diskCleanup and a.disk_full_days < ap.diskForecastDays)
if m.max_disk_pct >= ap.diskCleanupAt:
add('diskhigh', sev(m.max_disk_pct >= 97, True), 'Disk', f'Disk {m.fullest_mount} is {pct(m.max_disk_pct)} full',
f'Above the cleanup threshold of {pct(ap.diskCleanupAt, 0)}.', 'Free space soon: services fail when the disk is full.',
'disk_cleanup', '', 'Run cleanup', ap.diskCleanup)
# whole-machine memory trend over 6 h
six = st.range(now - 6 * 3600, now, 1)
if len(six) >= 90:
slope, a.mem_trend_r2 = regression(six, MEM)
a.mem_slope_per_hour = slope * 3600
left = (100 - m.mem_pct) / max(0.01, a.mem_slope_per_hour)
if a.mem_slope_per_hour > 1 and a.mem_trend_r2 > 0.8 and m.mem_pct > 40:
add('memtrend', sev(False, left < 12), 'Memory', f'Memory keeps growing (+{a.mem_slope_per_hour:.1f} points/hour)',
f'Steady growth over 6 h (R² {a.mem_trend_r2:.2f}). At this rate memory is exhausted in about {duration(left * 3600)}.',
'Look for a leaking process (Processes tab, sort by RSS).')
# processes: leaks and runaways
for p in procs:
if p.protected: continue
who = f'{p.name} (PID {p.pid})'
if p.minutes >= 30 and p.rss_growth_pct >= 25 and p.rss_growth >= 100e6 and p.rss_monotonic >= 0.8:
add(f'leak:{p.pid}', sev(m.mem_pct >= ap.leakMemPressure, True), 'Process', 'Possible memory leak: ' + who,
f'RSS grew {fmt_bytes(p.rss_growth)} (+{pct(p.rss_growth_pct, 0)}) in {p.minutes} min and rose in '
f'{rnd(p.rss_monotonic * 100)}% of the minutes; now {fmt_bytes(p.rss_now)}.',
'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', str(p.pid), 'Terminate',
ap.leakMode == 'terminate' and m.mem_pct >= ap.leakMemPressure)
if p.high_cpu_minutes >= ap.runawayMinutes:
term = ap.runawayMode == 'terminate'
add(f'runaway:{p.pid}', 'warning', 'Process', 'Runaway process: ' + who,
f'Above {pct(ap.runawayCpu, 0)} CPU for {rnd(p.high_cpu_minutes)} min (now {pct(p.cpu_now)}, user {p.user}).',
plat.TEXT['renice_advice'], 'kill_pid' if term else 'renice', str(p.pid), 'Terminate' if term else plat.TEXT['renice'],
ap.runawayMode != 'none')
# services: failures and flapping
for s in svcs:
flap = s.fails_last_hour >= 3 or s.auto_restarts_last_hour >= ap.maxRestartsPerHour
if s.failed_now:
add('svc:' + s.unit, sev(flap, True), 'Service', f'Service {s.unit} ' + ('keeps failing' if flap else 'has failed'),
'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' if s.preexisting
else f'Failed {s.fails_last_hour}× in the last hour; autopilot restarted it {s.auto_restarts_last_hour}×.',
'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' if flap else 'Restart it and check the logs.',
'restart_service', s.unit, 'Restart', ap.restartFailed and not s.preexisting and s.auto_restarts_last_hour < ap.maxRestartsPerHour)
elif s.fails_last_hour >= 3:
add('flap:' + s.unit, 'warning', 'Service', f'Service {s.unit} is unstable',
f'It failed {s.fails_last_hour} times within the last hour.', 'Inspect its logs and resource limits.')
# overload and swap thrashing
last15 = st.range(now - 900, now, 1)
load15, io15, cpu15, busy15 = (stats(last15, k).avg for k in (LOAD, IOWAIT, CPU, DISKIO))
if online and load15 / cores > 1.5:
add('load', sev(load15 / cores > 3, True), 'CPU', f'CPU is overloaded (load {load15:.1f} on {cores} cores)',
f'15-minute average load is {load15 / cores:.1f}× the number of cores; tasks are waiting for CPU.',
'Find the busiest processes, spread work over time, or add CPU.')
thrash = plat.thrashing(io15, m.mem_pct, busy15)
if online and m.swap_pct > 50 and thrash:
add('thrash', 'critical', 'Memory', 'Swap thrashing', f'Swap {pct(m.swap_pct)} used{thrash}.', 'Stop memory-hungry processes or add RAM.')
# anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h)
raw = st.range(now - 600, now, 0)
same = [i for i in range(bisect_right(hour.ts, now - 56 * 86400), bisect_left(hour.ts, now - 3600)) if slot(hour.ts[i]) == slot(now)]
recent = range(bisect_left(minute.ts, now - 86400), bisect_left(minute.ts, now - 900))
checks = [(CPU, 5.0, False), (MEM, 3.0, False), (LOAD, 0.25 * cores, False), (IOWAIT, 3.0, False), (RX, 256e3, True), (TX, 256e3, True)]
for hm, floor, down in checks if online and len(raw) >= 10 else (): # (metric, smallest deviation unit, alert on drops)
if hm == IOWAIT and not plat.POSIX_CPU: continue
cur, basis = stats(raw, hm).avg, 'same weekday & hour, last 8 weeks'
v = [hour.avg[hm][i] for i in same if hour.up[i] and hour.avg[hm][i] == hour.avg[hm][i]]
if len(v) < 3:
v, basis = [minute.avg[hm][i] for i in recent if minute.up[i] and minute.avg[hm][i] == minute.avg[hm][i]], 'last 24 hours'
if len(v) < 360: continue
mean = sum(v) / len(v)
sd = math.sqrt(sum((x - mean) ** 2 for x in v) / len(v))
z = (cur - mean) / max(sd, floor)
a.anomalies.append(Anomaly(NAMES[hm], basis, hm, cur, mean, sd, z))
hi, lo = z >= ap.anomalyZ, down and mean > 1e6 and cur < mean * 0.1
if ap.anomalyAlerts and (hi or lo):
add('anomaly:' + KEYS[hm], sev(False, z >= ap.anomalyZ * 2), 'Anomaly', f'Unusually {"high" if hi else "low"} {NAMES[hm].lower()}',
f'Last 10 min {fmt_metric(hm, cur)}, usually {fmt_metric(hm, mean)} ± {fmt_metric(hm, sd)} ({basis}); {z:.1f}σ.',
'Check what changed: deploys, cron jobs, traffic, attacks.' if hi else 'Traffic dropped sharply - check the service is still serving.')
# weekly heatmaps from 4 weeks of hours
total = [[[0.0] * 24 for _ in range(7)] for _ in range(2)]
for i in range(bisect_left(hour.ts, now - 28 * 86400), len(hour)):
cpu, mem = hour.avg[CPU][i], hour.avg[MEM][i]
if not hour.up[i] or cpu != cpu: continue
d, h = slot(hour.ts[i])
a.heat_n[d][h] += 1
for k, v in enumerate((cpu, mem if mem == mem else 0)):
total[k][d][h] += v
a.heat[k][d][h] = total[k][d][h] / a.heat_n[d][h]
# capacity advice
for s, name, lo, hi, lo_txt, hi_txt in ((a.cpu30, 'CPU', 15, 80, 'is mostly idle', 'is often saturated - add cores or move work away'),
(a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits')):
if s.count >= 60: a.capacity.append(f'{name} {lo_txt if s.p95 < lo else hi_txt if s.p95 > hi else "headroom is healthy"} (p95 {pct(s.p95)}).')
if a.disk_full_days >= 0:
a.capacity.append(f'Disk grows {a.disk_slope_per_day:.2f} points/day - full in about {duration(a.disk_full_days * 86400)}.')
elif a.disk_basis:
a.capacity.append('Disk usage is stable.')
if not a.capacity: a.capacity.append('Collecting history - capacity advice appears after about an hour of data.')
# health score
score = 100.0
def pen(when, p, why):
nonlocal score
if when and p > 0.5:
score -= p
a.reasons.append(f'−{rnd(p)} {why}')
cpu = m.cpu_usage if cpu15 != cpu15 else cpu15
pen(not online, 60, 'server unreachable')
pen(cpu > 70, min(24, (cpu - 70) * 0.8), f'CPU busy ({pct(cpu)})')
pen(m.mem_pct > 80, min(30, (m.mem_pct - 80) * 1.5), f'memory high ({pct(m.mem_pct)})')
pen(m.max_disk_pct > 80, min(40, (m.max_disk_pct - 80) * 2), f'disk high ({pct(m.max_disk_pct)})')
pen(m.swap_pct > 50, 10, 'heavy swap use')
pen(m.max_temp > 80, min(20, (m.max_temp - 80) * 2), f'hot ({temp(m.max_temp)})')
pen(a.up[0] < 100, min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h')
pen(True, min(50, sum(0 if f.category == 'Availability' else {'critical': 15, 'warning': 7}.get(f.severity, 2) for f in a.findings)),
f'{len(a.findings)} finding(s)')
a.health = min(max(rnd(score), 0), 100)
a.grade = 'FDCBA'[sum(a.health >= x for x in (40, 60, 75, 90))]
a.findings.sort(key=lambda f: {'critical': 0, 'warning': 1}.get(f.severity, 2))
return a
|