File size: 22,271 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""Connection to one machine (local shell or system ssh), the per-server session
(metrics, live history, rules, autopilot) and the manager of all sessions."""
import json, os, queue, shutil, subprocess, threading, time
from collections import namedtuple
from datetime import datetime
from types import SimpleNamespace

import plat
from history import Analysis, ProcTrend, ServiceTrend, Store, analyze
from metrics import Metrics
from model import RULE_METRICS, ServerConfig, catalogue, command, new_id

PIPE = subprocess.PIPE
SSH_OPTIONS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR']
STATUS = ('Disabled', 'Connecting', 'Online', 'Offline')
DISABLED, CONNECTING, ONLINE, OFFLINE = range(4)
AlertEvent = namedtuple('AlertEvent', 'time server severity message')  # severity: info|warning|critical|resolved|action

# ---- UI-thread dispatch -----------------------------------------------------------------
class Loop:
    """Hands work to the UI thread: worker threads post() calls, timers are due in pump(), which the UI calls often."""
    def __init__(self): self.calls, self.timers = queue.SimpleQueue(), set()
    def post(self, fn, *args): self.calls.put((fn, args))
    def pump(self):
        while not self.calls.empty():
            fn, args = self.calls.get()
            fn(*args)
        now = time.monotonic()
        for t in [t for t in self.timers if t.due <= now]:
            if t in self.timers:  # not stopped by a call that ran just before
                t.start() if t.every else t.stop()
                t.fn()

loop = Loop()

class Timer:
    """Restartable timer on the loop; with every (seconds) it repeats."""
    def __init__(self, fn, every=0):
        self.fn, self.every = fn, every
        if every: self.start()
    def start(self, seconds=None):
        self.due = time.monotonic() + (seconds or self.every)
        loop.timers.add(self)
    def stop(self): loop.timers.discard(self)

class Signal(list):
    """List of listeners; calling it calls them all."""
    def __call__(self, *args):
        for fn in list(self): fn(*args)

# ---- Link ---------------------------------------------------------------------------------
class Link:
    """Streams collector frames and runs one-shot commands on one machine. close() kills everything."""
    def __init__(self, cfg, on_frame, on_lost):
        self.cfg, self.on_frame, self.on_lost, self.procs, self.pending, self.closed = cfg, on_frame, on_lost, set(), {}, False
    def spawn(self, interval=None, **kw):
        c, argv, env = self.cfg, plat.shell(interval), None
        if c.transport:
            options = SSH_OPTIONS + (['NumberOfPasswordPrompts=1'] if c.password else ['BatchMode=yes'])
            if c.password:  # a helper script answers ssh's password prompt
                env = {'DISPLAY': ':0', **os.environ, 'SSH_ASKPASS': plat.askpass(), 'SSH_ASKPASS_REQUIRE': 'force', 'SERVERMONITOR_ASKPASS': c.password}
            argv = ['ssh', *(x for o in options for x in ('-o', o)), *(['-i', os.path.expanduser(c.keyFile)] if c.keyFile else []),
                    *(['-p', str(c.port)] if c.port != 22 else []), '-T', f'{c.user}@{c.host}' if c.user else c.host, ' '.join(argv)]
        try: p = subprocess.Popen(argv, stdin=PIPE, stdout=PIPE, env=env, **plat.SPAWN, **kw)
        except OSError as e: raise OSError(f'cannot start {argv[0]}: {e.strerror}') from e
        self.procs.add(p)
        return p
    def post(self, fn, *args):  # results reach the UI thread, unless the link was closed meanwhile
        loop.post(lambda: self.closed or fn(*args))
    def start(self):
        try: p = self.spawn(self.cfg.interval, stderr=PIPE)
        except OSError as e: return self.post(self.on_lost, str(e))
        threading.Thread(target=self.stream, args=(p,), daemon=True).start()
    def stream(self, p):  # worker thread: frames out of stdout, the last error line out of stderr
        buf, err = b'', [b'']

        def errors():
            for chunk in iter(lambda: p.stderr.read1(4096), b''): err[0] = (err[0] + chunk)[-4096:]

        reader = threading.Thread(target=errors, daemon=True)
        reader.start()
        try:
            p.stdin.write(plat.collector(self.cfg.interval).encode())
            p.stdin.close()
            for chunk in iter(lambda: p.stdout.read1(1 << 16), b''):
                buf += chunk
                while b'@@SNAP_END' in buf:
                    end = buf.find(b'@@SNAP_END')
                    begin = buf.rfind(b'@@SNAP_BEGIN', 0, end)
                    if begin >= 0 and loop.calls.qsize() < 100:  # a stalled UI must not pile up frames
                        self.post(self.on_frame, buf[begin:end].decode('utf-8', 'replace'))
                    buf = buf[end + 10:]
                if len(buf) > 8 << 20: buf = b''
        except (OSError, ValueError):
            pass  # killed while writing or reading
        code = p.wait()
        reader.join(2)
        lines = err[0].decode('utf-8', 'replace').split('\n')
        self.post(self.on_lost, next((l.strip() for l in reversed(lines) if l.strip()), f'connection closed (exit code {code})'))
    def exec(self, script, timeout, done=None):
        """Runs a script; done(code, output) is called on the UI thread (code -1: killed, timed out or not started)."""
        try: p = self.spawn(stderr=subprocess.STDOUT)
        except OSError as e: return done and self.post(done, -1, str(e))
        self.pending[p] = done

        def work():
            try:
                out, code = p.communicate(script.encode(), timeout)[0], p.returncode
            except subprocess.TimeoutExpired:
                plat.kill(p)
                try: out, code = p.communicate(timeout=2)[0], -1
                except subprocess.TimeoutExpired: out, code = b'', -1  # something it started still holds the pipe
            self.post(self.finished, p, -1 if code < 0 else code, out.decode('utf-8', 'replace') + ('\n[killed or timed out]' if code < 0 else ''))

        threading.Thread(target=work, daemon=True).start()
    def finished(self, p, code, out):
        self.procs.discard(p)
        done = self.pending.pop(p)
        if done: done(code, out)
    def close(self, reason='connection stopped'):
        self.closed = True
        for p in self.procs: plat.kill(p)
        for done in self.pending.values():
            if done: done(-1, reason)

# ---- live history -----------------------------------------------------------------------
class Live:
    """The last hour of samples in memory, for the live charts."""
    KEYS, CAP = 'cpu user sys iowait steal mem cache swap rx tx rd wr load'.split(), 1800
    def __init__(self): self.t, self.s, self.if_rx, self.if_tx = [], {k: [] for k in self.KEYS}, {}, {}
    def push(self, m):
        n = len(self.t)

        def add(v, x):
            v[:0] = [0.0] * (n - len(v))  # align series that appeared later
            v.append(x)
            del v[:-self.CAP]

        add(self.t, m.timestamp)
        values = (m.cpu_usage, m.cpu_user, m.cpu_system + m.cpu_irq, m.cpu_iowait, m.cpu_steal, m.mem_pct,
                  (m.cached + m.buffers) * 100 / m.mem_total if m.mem_total > 0 else 0, m.swap_pct, m.net_rx_bps, m.net_tx_bps,
                  m.disk_read_bps, m.disk_write_bps, m.load1)
        for k, x in zip(self.KEYS, values): add(self.s[k], x)
        for i in m.nets:
            add(self.if_rx.setdefault(i.name, []), i.rx_bps)
            add(self.if_tx.setdefault(i.name, []), i.tx_bps)

# ---- session ----------------------------------------------------------------------------
class Session:
    def __init__(self, cfg):
        self.cfg, self.status, self.err, self.link, self.engine = cfg, DISABLED, '', None, {}
        self.m, self.live, self.an = Metrics(), Live(), Analysis()
        self.store = Store(os.path.join(Manager.config_dir(), 'history', cfg.id))
        self.retries, self.paused, self.offline_alerted = 0, False, False
        self.reported, self.dry, self.cooldown, self.rules, self.procs, self.svcs = set(), set(), {}, {}, {}, {}  # analyzer / rule / tracking state
        self.updated, self.analysis_updated, self.alert = Signal(), Signal(), Signal()
        self.retry, self.watchdog, first = Timer(self.start), Timer(lambda: self.lost('no data received (timeout)')), Timer(self.analyze)
        self.offline = Timer(self.down, cfg.interval)  # downtime -> availability: one sample per interval, like uptime
        self.timers = [self.retry, self.watchdog, first, self.offline, Timer(self.analyze, 60)]
        first.start(3)
    def online(self): return self.status == ONLINE and self.m.valid
    def down(self):
        if self.status == OFFLINE or (self.status == CONNECTING and self.retries): self.record(False)
    def set_config(self, c):
        old, self.cfg, self.offline.every = self.cfg, c, c.interval
        if any(getattr(c, k) != getattr(old, k) for k in ('transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled')):
            self.live, self.m, self.procs, self.svcs = Live(), Metrics(), {}, {}  # may be another machine now
            self.start() if c.enabled else self.stop()
        self.updated()
    def set_paused(self, paused):
        self.paused = paused
        self.updated()
    def reconnect(self):
        self.retries, self.paused = 0, False
        self.start()
    def drop_link(self, reason):
        self.retry.stop()
        self.watchdog.stop()
        link, self.link = self.link, None
        if link: link.close(reason)
    def start(self):
        self.drop_link('connection restarted')
        if not self.cfg.enabled: return self.set_status(DISABLED)
        self.engine, self.m.valid = {}, False  # online() only again with a fresh sample
        self.link = Link(self.cfg, self.frame, self.lost)
        self.set_status(CONNECTING)
        self.watchdog.start(25)
        self.link.start()
    def stop(self):
        self.drop_link('connection stopped')
        self.set_status(OFFLINE if self.cfg.enabled else DISABLED)
    def close(self):
        self.stop()
        for t in self.timers: t.stop()
    def set_status(self, status, err=''):
        if err or status == ONLINE: self.err = err
        if status != self.status:
            self.status = status
            self.updated()
    def frame(self, raw):
        now = time.time() * 1000
        self.watchdog.start(max(15, self.cfg.interval * 5 + 10))
        m = plat.parse(raw, self.engine, now)
        if m.uptime <= 0: return
        if self.status != ONLINE:
            self.retries = 0
            if self.offline_alerted: self.raise_alert('resolved', 'Server is back online')
            self.offline_alerted = False
            self.set_status(ONLINE)
        if not m.valid or self.paused:  # the first sample has no rates yet
            return
        if m.uptime < self.m.uptime: self.procs = {}  # rebooted: PIDs start again, old trends would be blamed on new processes
        first, self.m = not self.m.valid, m
        self.live.push(m)
        self.record(True)
        self.track(now)
        self.evaluate_rules()
        if first: self.analyze()  # first sample of this connection: the last analysis saw "unreachable"
        self.updated()
    def lost(self, why):
        was = self.status == ONLINE
        self.drop_link('connection lost: ' + why)
        self.set_status(OFFLINE, why)
        if (was or self.retries == 1) and not self.offline_alerted:
            self.raise_alert('critical', 'Server is unreachable: ' + why)
            self.offline_alerted = True
        if self.cfg.enabled:
            self.retry.start((3, 5, 10, 20, 30, 60)[min(self.retries, 5)])  # back-off
            self.retries += 1
    def exec(self, cmd, privileged, done=None, timeout=60):
        """Runs a command on the machine; privileged ones go through sudo when the server is set up for it."""
        if self.link and self.status == ONLINE: self.link.exec(plat.wrap(cmd, privileged, self.cfg.useSudo), timeout, done)
        elif done: loop.post(done, -1, 'server is not connected')
    def metric_value(self, key):
        m = self.m
        return {'cpu': m.cpu_usage, 'iowait': m.cpu_iowait, 'load': m.load1 * 100 / max(1, m.cpu_count), 'mem': m.mem_pct, 'swap': m.swap_pct,
                'disk': m.max_disk_pct, 'diskio': m.max_disk_util, 'temp': m.max_temp, 'rx': m.net_rx_bps / 1e6, 'tx': m.net_tx_bps / 1e6,
                'failed': m.services_failed, 'procs': len(m.procs), 'gpu': m.gpu_max(), 'gputemp': m.gpu_max(True)}.get(key, 0)
    def active_alerts(self):
        down = ['Unreachable: ' + self.err] if self.status == OFFLINE else []
        return down + [r.condition() for r in self.cfg.rules if r.id in self.rules and self.rules[r.id].active]
    def raise_alert(self, severity, message): self.alert(AlertEvent(datetime.now(), self.cfg.name, severity, message))
    def record(self, up):
        m, nan = self.m, float('nan')
        self.store.add(int(time.time()), (
            m.cpu_usage, m.cpu_iowait, m.load1, m.mem_pct, m.swap_pct if m.swap_total > 0 else nan, m.max_disk_pct if m.mounts else nan,
            m.max_disk_util, m.net_rx_bps, m.net_tx_bps, m.disk_read_bps, m.disk_write_bps, m.max_temp if m.temps else nan, len(m.procs),
            m.gpu_max() if m.gpus else nan, m.services_failed), up)
    def track(self, now):
        """Per-process CPU streaks and RSS per minute; service failure transitions."""
        procs = {}
        for p in self.m.procs:
            t = self.procs.get(p.pid)
            if not t or t.name != p.name:  # new, or the pid was reused
                t = SimpleNamespace(name=p.name, high_since=0, last_minute=0, rss=[])
            t.protected = plat.protected(p)
            t.high_since = 0 if p.cpu < self.cfg.autopilot.runawayCpu else t.high_since or now
            if now - t.last_minute >= 60000: t.last_minute, t.rss = now, t.rss[-59:] + [p.rss]
            procs[p.pid] = t
        self.procs, svcs = procs, {}
        for s in self.m.services:
            t, failed = self.svcs.get(s.unit) or SimpleNamespace(last='', preexisting=False, fails=[], restarts=[]), s.active == 'failed'
            svcs[s.unit] = t
            if not t.last:
                t.preexisting = failed  # failed before monitoring started: leave it alone
            elif failed and t.last != 'failed':
                t.fails.append(now)
                t.preexisting = False
            elif not failed:
                t.preexisting = False
            t.last = s.active
            t.fails, t.restarts = ([x for x in v if now - x <= 3600000] for v in (t.fails, t.restarts))
        if svcs: self.svcs = svcs  # forgets removed services; a sample without a service list changes nothing
    def evaluate_rules(self):
        now, m = time.time() * 1000, self.m
        for r in self.cfg.rules:
            st = self.rules.setdefault(r.id, SimpleNamespace(since=0, last_fire=0, active=False))
            v = self.metric_value(r.metric)
            idle = not r.enabled or (r.metric in ('gpu', 'gputemp') and not m.gpus) or (r.metric == 'temp' and not m.temps)
            if idle or (v >= r.value if r.op == '<' else v <= r.value):
                if st.active and not idle: self.raise_alert('resolved', f'Recovered: {r.condition()} (now {v:.1f})')
                del self.rules[r.id]
                continue
            st.since = st.since or now
            if now - st.since < r.duration * 1000 or (st.active and (r.action == 'notify' or now - st.last_fire < r.cooldown * 1000)): continue
            unit = catalogue(RULE_METRICS, r.metric, 2)
            if not st.active: self.raise_alert(r.severity, f'{r.condition()} (now {v:.1f}' + (f' {unit}' if unit else '') + ')')
            st.active, st.last_fire = True, now
            action, arg = r.action, r.arg
            if action.startswith('kill_top'):  # heaviest process that is not protected
                best = max((p for p in m.procs if not plat.protected(p)), key=lambda p: p.rss if action == 'kill_top_mem' else p.cpu, default=None)
                action, arg = ('kill_pid', str(best.pid)) if best else ('notify', '')
            if action != 'notify': self.run(action, arg, f'Automation "{r.condition()}": {r.action_text()}')
    def run(self, action, arg, what, done=None):
        cmds = {'command': arg, 'disk_cleanup': self.cfg.autopilot.diskCleanupCommand, **{k: command(v, arg) for k, v in plat.CMD.items()}}
        if not cmds.get(action): return done and done(-1, 'nothing to do')

        def report(code, out):
            tail = ' '.join(out.split())[-300:]  # one line: events are lines in alerts.log
            self.raise_alert('action', f'{what} -> ' + (f'failed ({code})' if code else 'OK') + (f' | {tail}' if tail else ''))
            if done: done(code, out)

        self.exec(cmds[action], True, report, 300)
    def run_finding(self, f, automatic, done=None):
        if automatic and f.action == 'restart_service': self.svcs[f.arg].restarts.append(time.time() * 1000)
        self.run(f.action, '' if f.action == 'disk_cleanup' else f.arg, ('Autopilot: ' if automatic else 'Manual fix: ') + f'{f.label} ({f.title})', done)
    def analyze(self):
        now, trends, ap = time.time() * 1000, [], self.cfg.autopilot
        for p in self.m.procs:
            t = self.procs.get(p.pid)
            rss = t.rss if t else []
            growth = rss[-1] - rss[0] if len(rss) >= 2 else 0
            pt = ProcTrend(p.pid, len(rss), p.name, p.user, p.cpu, (now - t.high_since) / 60000 if t and t.high_since else 0, p.rss, growth,
                           growth * 100 / rss[0] if growth and rss[0] > 0 else 0,
                           sum(b > a for a, b in zip(rss, rss[1:])) / (len(rss) - 1) if len(rss) >= 2 else 0, bool(t and t.protected))
            if pt.high_cpu_minutes > 0 or pt.minutes >= 30: trends.append(pt)
        svcs = [ServiceTrend(unit, t.last == 'failed', t.preexisting, len(t.fails), len(t.restarts))
                for unit, t in self.svcs.items() if t.last == 'failed' or t.fails]
        self.an = analyze(self.store, self.m, ap, trends, svcs, self.online())

        for f in self.an.findings:  # announce each new finding once
            if f.key not in self.reported and f.category != 'Availability': self.raise_alert(f.severity, f'Insight: {f.title} - {f.detail}')
        self.reported = {f.key for f in self.an.findings}

        dry = set()  # act on eligible findings, with cooldowns; a dry run says once what it would do
        for f in self.an.findings if ap.enabled and self.online() else ():
            if not f.auto: continue
            if ap.dryRun:
                dry.add(f.key)
                if f.key not in self.dry: self.raise_alert('action', f'Autopilot (dry run) would: {f.label} - {f.title}')
            elif now - self.cooldown.get(f.key, 0) >= {'disk_cleanup': 6 * 3600000, 'restart_service': 120000}.get(f.action, 900000):
                self.cooldown[f.key] = now
                self.run_finding(f, True)
        self.dry = dry
        self.analysis_updated()

# ---- manager ----------------------------------------------------------------------------
class Manager:
    def __init__(self):
        self.sessions, self.alerts = [], []
        self.changed, self.alert, self.cleared = Signal(), Signal(), Signal()  # server list changed, alert raised, alerts cleared
    @staticmethod
    def config_dir():
        os.makedirs(plat.config_dir(), exist_ok=True)
        return plat.config_dir()
    def path(self, name): return os.path.join(self.config_dir(), name)
    def session(self, server_id): return next((s for s in self.sessions if s.cfg.id == server_id), None)
    def attach(self, cfg):
        s = Session(cfg)
        s.alert.append(self.on_alert)
        self.sessions.append(s)
        return s
    def on_alert(self, e):
        self.alerts[:0] = [e]
        del self.alerts[2000:]
        log = self.path('alerts.log')
        try:
            with open(log, 'w' if os.path.exists(log) and os.path.getsize(log) > 5 << 20 else 'a', encoding='utf-8') as f:
                f.write(f'{e.time.isoformat(timespec="seconds")}\t{e.severity}\t{e.server}\t{e.message}\n')
        except OSError:
            pass  # the event still reaches the window
        self.alert(e)
    def load(self):
        try:
            with open(self.path('servers.json'), encoding='utf-8') as f:
                for o in json.load(f)['servers']: self.attach(ServerConfig.from_json(o))
        except FileNotFoundError:  # first start: monitor this machine
            self.attach(ServerConfig(new_id(), 'This computer', 'Local', transport=0))
            self.save()
        except (OSError, ValueError, LookupError, TypeError, AttributeError):
            pass  # unreadable or damaged file: start with the servers read so far
        for s in self.sessions: s.start()
        self.changed()
    def save(self):
        tmp = self.path('servers.json.tmp')
        with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f:
            json.dump({'version': 1, 'servers': [s.cfg.to_json() for s in self.sessions]}, f, indent=4)
        os.replace(tmp, self.path('servers.json'))
    def add(self, cfg):
        s = self.attach(cfg)
        self.save()
        s.start()
        self.changed()
        return s
    def update(self, cfg):
        s = self.session(cfg.id)
        if s:
            s.set_config(cfg)
            self.save()
            self.changed()
    def remove(self, server_id, delete_history):
        s = self.session(server_id)
        if not s: return
        self.sessions.remove(s)
        s.alert.clear()
        s.close()
        if delete_history: shutil.rmtree(s.store.dir, ignore_errors=True)
        self.save()
        self.changed()
    def move(self, server_id, delta):
        i = self.sessions.index(self.session(server_id))
        j = min(max(i + delta, 0), len(self.sessions) - 1)
        if i != j:
            self.sessions.insert(j, self.sessions.pop(i))
            self.save()
            self.changed()
    def clear_alerts(self):
        self.alerts.clear()
        self.cleared()
    def close(self):
        for s in self.sessions: s.close()