File size: 6,270 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
"""Server configuration, alert rules, autopilot policy and text formatting."""
import base64, binascii, math, uuid
from dataclasses import asdict, dataclass, field, fields

import plat
from metrics import to_int

# ---- formatting -------------------------------------------------------------
def fmt_bytes(b, prec=1):
    i = 0
    while abs(b) >= 1024 and i < 5: b, i = b / 1024, i + 1
    return f'{b:.{prec if i else 0}f} ' + 'B KB MB GB TB PB'.split()[i]

def rate(b): return fmt_bytes(b) + '/s'
def pct(p, prec=1): return f'{p:.{prec}f}%'
def temp(c): return f'{c:.0f} °C'

def count(v):
    a = abs(v)
    return f'{v / 1e9:.1f}G' if a >= 1e9 else f'{v / 1e6:.1f}M' if a >= 1e6 else f'{v / 1e3:.1f}K' if a >= 1e4 else f'{v:.0f}'

def duration(sec):
    s = int(sec)
    d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60
    return f'{d}d {h}h {m}m' if d else f'{h}h {m}m' if h else f'{m}m {s % 60}s' if m else f'{s}s'

def rnd(x):
    """Rounds half up (Python's round() rounds half to even)."""
    return math.floor(x + 0.5)

def command(template, q='', n=None):
    """Fills a platform command template: {q} = quoted argument, {n} = integer argument (default: q as a number)."""
    return template.replace('{q}', plat.quote(str(q))).replace('{n}', str(to_int(q if n is None else n)))

# ---- catalogues: (key, label, unit) and (key, label, argument hint) ------------
RULE_METRICS = [d for d in (
    ('cpu', 'CPU usage', '%'), ('iowait', 'CPU I/O wait', '%'), ('load', 'Load (1 min) per core', '%'), ('mem', 'Memory usage', '%'),
    ('swap', 'Swap usage', '%'), ('disk', 'Fullest disk usage', '%'), ('diskio', 'Busiest disk utilisation', '%'),
    ('temp', 'Hottest sensor', '°C'), ('rx', 'Network download', 'MB/s'), ('tx', 'Network upload', 'MB/s'), ('failed', 'Failed services', ''),
    ('procs', 'Process count', ''), ('gpu', 'GPU usage (max)', '%'), ('gputemp', 'GPU temperature (max)', '°C')) if plat.POSIX_CPU or d[0] != 'iowait']
RULE_ACTIONS = [(k, text, plat.HINTS.get(k, '')) for k, text in (
    ('notify', 'Notify only'), ('restart_failed', 'Restart failed services'), ('restart_service', 'Restart a service'),
    ('kill_top_cpu', 'Terminate top CPU process'), ('kill_top_mem', 'Terminate top memory process'),
    ('drop_caches', 'Sync + drop page cache'), ('command', 'Run a command')) if k != 'drop_caches' or k in plat.CMD]

def catalogue(defs, key, col=1):
    """Label (col 1) or unit / hint (col 2) of a rule metric or action."""
    return next((d[col] for d in defs if d[0] == key), key if col == 1 else '')

# ---- configuration (field names = servers.json keys) ---------------------------
@dataclass
class Rule:
    """When <metric> <op> <value> for <duration> s -> <action>(<arg>), again after <cooldown> s."""
    id: str = ''; metric: str = 'cpu'; op: str = '>'; action: str = 'notify'; arg: str = ''; severity: str = 'warning'
    enabled: bool = True; value: float = 90.0; duration: int = 60; cooldown: int = 300
    def condition(self):
        unit = catalogue(RULE_METRICS, self.metric, 2)
        return (f'{catalogue(RULE_METRICS, self.metric)} {self.op} {self.value:g}' + (f' {unit}' if unit else '')
                + (f' for {self.duration} s' if self.duration else ''))
    def action_text(self): return catalogue(RULE_ACTIONS, self.action) + (f': {self.arg}' if self.arg else '')

@dataclass
class AutopilotConfig:
    """History-driven automatic control (evaluated by the analyzer every minute)."""
    enabled: bool = True; dryRun: bool = False; restartFailed: bool = True; diskCleanup: bool = False; anomalyAlerts: bool = True
    maxRestartsPerHour: int = 3; runawayMinutes: int = 10; diskForecastDays: int = 3
    runawayCpu: float = 90.0; diskCleanupAt: float = 92.0; leakMemPressure: float = 90.0; anomalyZ: float = 3.0
    runawayMode: str = 'renice'; leakMode: str = 'notify'  # none|renice|terminate, none|notify|terminate
    diskCleanupCommand: str = plat.CLEANUP

def new_id(): return str(uuid.uuid4())[:12]

def default_rules():
    return [Rule(new_id(), m, value=float(v), duration=d, severity=s) for m, v, d, s in (
        ('cpu', 90, 60, 'warning'), ('mem', 90, 60, 'warning'), ('swap', 80, 120, 'warning'), ('disk', 90, 0, 'critical'),
        ('temp', 85, 30, 'critical'), ('load', 150, 120, 'warning'), ('failed', 0, 0, 'warning'))]

def load(cls, o):
    """Dataclass from a JSON object: known scalar fields only, converted to the declared type."""
    c = cls()
    for f in fields(cls):
        if f.type in (str, int, float, bool) and o.get(f.name) is not None:
            try: setattr(c, f.name, f.type(o[f.name]))
            except (TypeError, ValueError): pass
    return c

def xor_b64(s, encode):
    """Light obfuscation of saved passwords (NOT encryption)."""
    key = b'ServerMonitor/obfuscation/v1'
    try: b = s.encode() if encode else base64.b64decode(s)
    except binascii.Error: return ''
    b = bytes(x ^ key[i % len(key)] for i, x in enumerate(b))
    return base64.b64encode(b).decode() if encode else b.decode('utf-8', 'replace')

@dataclass
class ServerConfig:
    id: str = ''; name: str = ''; group: str = ''; host: str = ''; user: str = ''; keyFile: str = ''; password: str = ''; notes: str = ''
    transport: int = 1; port: int = 22; interval: int = plat.INTERVAL; useSudo: bool = False; enabled: bool = True  # transport: 0 Local, 1 SSH
    rules: list = field(default_factory=default_rules)
    autopilot: AutopilotConfig = field(default_factory=AutopilotConfig)
    def address(self):
        if not self.transport: return 'this machine'
        return (f'{self.user}@' if self.user else '') + self.host + (f':{self.port}' if self.port != 22 else '')
    def to_json(self): return {**asdict(self), 'password': xor_b64(self.password, True)}
    @classmethod
    def from_json(cls, o):
        c = load(cls, o)
        c.autopilot = load(AutopilotConfig, o.get('autopilot', {}))
        if 'rules' in o: c.rules = [load(Rule, r) for r in o['rules']]
        for r in c.rules: r.id = r.id or new_id()
        c.transport = 0 if o.get('transport', 1) == 0 else 1
        c.password = xor_b64(o.get('password', ''), False)
        c.interval = min(max(c.interval, 1), 300)
        c.id = c.id or new_id()
        return c

TRANSPORTS = ('Local', 'SSH')