garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/components/services.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Button, Card} from '@garage44/mithril/components'

import {Lines, SERIES} from '@/components/charts'
import {runnersCard} from '@/components/runners'
import {api} from '@/lib/api'
import type {Runners, Watch, WatchTarget} from '@/lib/api'
import {bytes} from '@/lib/format'
import {local} from '@/lib/reactive'

/*
 * Workspace ▸ Services (watch.rs): every deploy target the hub watches — is it
 * up, what it serves, its memory, CPU and answer time — each chart crossed by a
 * line at every deploy, which says the landings it carried. Asked for every
 * minute, which is how often the hub samples.
 */

const RANGES: {label: string; s: number}[] = [
    {label: '6 h', s: 6 * 3600},
    {label: '24 h', s: 86400},
    {label: '7 d', s: 7 * 86400},
]

const STATE_WORD: Record<WatchTarget['state'], string> = {ok: 'up', trouble: 'in trouble', down: 'down', unknown: 'not sampled'}

const sha8 = (s: string | null | undefined) => (s ? s.slice(0, 8) : '—')
const clock = (t: number) => new Date(t * 1000).toLocaleTimeString(undefined, {hour: '2-digit', minute: '2-digit'})
const dayClock = (t: number) => new Date(t * 1000).toLocaleString(undefined, {weekday: 'short', hour: '2-digit'})
const mb = (v: number) => (v >= 1024 ? `${(v / 1024).toFixed(1)} GB` : `${Math.round(v)} MB`)
const pct = (v: number) => `${Math.round(v)} %`
const ms = (v: number) => `${Math.round(v)} ms`

/** What a target's last sample says, in one line. */
function nowLine(t: WatchTarget): string {
    const n = t.now
    if (!n) return t.why
    const parts = [`serves ${sha8(t.serves)}`]
    if (n.mem != null) parts.push(bytes(n.mem))
    if (n.cpu != null) parts.push(`CPU ${pct(n.cpu)}`)
    const answer = n.probes?.map((p) => p.ms).filter((x): x is number => x != null)
    if (answer?.length) parts.push(`answers in ${ms(Math.max(...answer))}`)
    if (t.restarts_h) parts.push(`${t.restarts_h} restarts this hour`)
    return parts.join(' · ')
}

/** The buckets a target was down in, joined into spans. */
function downSpans(t: WatchTarget, step: number): [number, number][] {
    const out: [number, number][] = []
    for (const p of t.points) {
        if (p[4]) continue
        const last = out[out.length - 1]
        if (last && last[1] >= p[0]) last[1] = p[0] + step
        else out.push([p[0], p[0] + step])
    }
    return out
}

export class Services extends MithrilComponent {
    s = local({data: null as Watch | null, runners: null as Runners | null, failed: false, range: RANGES[0]!.s, open: null as string | null})
    timer = 0

    oninit() {
        void this.load()
        this.timer = window.setInterval(() => void this.load(), 60_000)
    }

    onremove() {
        window.clearInterval(this.timer)
    }

    async load() {
        try {
            // A hub from before runners.rs has no runners to say: the services all the same.
            const [data, runners] = await Promise.all([api.watch(this.s.range), api.runners(this.s.range).catch(() => null)])
            this.s.data = data
            this.s.runners = runners
            this.s.failed = false
        } catch {
            this.s.failed = true
        }
    }

    chart(w: Watch, t: WatchTarget, title: string, k: 1 | 2 | 3, format: (v: number) => string) {
        const points = t.points.filter((p) => p[k] != null).map((p) => [p[0], p[k]!] as [number, number])
        if (!points.length) return null
        const label = w.to - w.from > 2 * 86400 ? dayClock : clock
        return [
            <p class="hint">{title}</p>,
            <Lines
                series={[{label: title, color: SERIES[0]!}]}
                points={[points]}
                from={w.from}
                to={w.to}
                step={w.step}
                format={format}
                label={label}
                tall={130}
                spans={downSpans(t, w.step)}
                marks={t.deploys.map((d) => ({
                    t: d.t,
                    lines: [
                        sha8(d.sha),
                        `deployed ${clock(d.t)}${d.by ? ` by ${d.by}` : ''}`,
                        ...(d.landings.length ? d.landings.map((l) => `${l.session}${l.branch ? ` · ${l.branch}` : ''}`) : ['no landing of its own']),
                    ],
                }))}
            />,
        ]
    }

    detail(w: Watch, t: WatchTarget) {
        return (
            <div class="stack">
                {this.chart(w, t, 'Memory', 1, mb)}
                {this.chart(w, t, 'CPU, of one core', 2, pct)}
                {this.chart(w, t, 'Answer time', 3, ms)}
                <p class="hint">
                    {t.unit ? <code>{t.unit}</code> : null} {t.probes.map((p) => <code>{p}</code>)} · a dashed line is a deploy (tap it for the landings it carried), red is down.
                    {t.memory_mb ? ` In trouble above ${mb(t.memory_mb)}` : ''}
                    {t.restarts_per_h != null ? `${t.memory_mb ? ' or' : ' In trouble at'} more than ${t.restarts_per_h} restarts an hour.` : t.memory_mb ? '.' : ''}
                </p>
            </div>
        )
    }

    view() {
        const w = this.s.data
        if (!w) return <Card>{this.s.failed ? <p class="hint">The hub did not answer; trying again.</p> : <p class="hint">Asking the hub…</p>}</Card>
        if (!w.targets.length) {
            return (
                <div class="stack">
                    {runnersCard(this.s.runners)}
                    <Card>
                    <h3 class="card__title">Services</h3>
                    <p class="hint">
                        No deploy target is watched yet. Give one a <code>watch</code> in hub.conf — its systemd unit and a health address — and the hub samples it every minute.
                    </p>
                    </Card>
                </div>
            )
        }
        const open = w.targets.find((t) => t.name === this.s.open) ?? w.targets.find((t) => t.state !== 'ok') ?? w.targets[0]!
        const mn = w.machine.now
        return (
            <div class="stack">
                <Card>
                    <h3 class="card__title">Services</h3>
                    <div class="services__ranges">
                        {RANGES.map((r) => (
                            <Button
                                size="sm"
                                variant={this.s.range === r.s ? 'primary' : 'ghost'}
                                onclick={() => {
                                    this.s.range = r.s
                                    void this.load()
                                }}
                            >
                                {r.label}
                            </Button>
                        ))}
                    </div>
                    <ul class="services">
                        {w.targets.map((t) => (
                            <li
                                class={`services__row${t === open ? ' services__row--open' : ''}${t.state === 'down' ? ' services__row--down' : ''}`}
                                onclick={() => (this.s.open = t.name)}
                            >
                                <span class={`services__dot services__dot--${t.state}`} />
                                <b>{t.name}</b>
                                <span class="hint services__state">{STATE_WORD[t.state]}</span>
                                <span class="hint">{t.state === 'ok' || !t.now ? nowLine(t) : `${t.why} · ${nowLine(t)}`}</span>
                            </li>
                        ))}
                    </ul>
                    {this.detail(w, open)}
                </Card>
                {runnersCard(this.s.runners)}
                {mn ? (
                    <Card>
                        <h3 class="card__title">This machine</h3>
                        <p class="hint">
                            {mn.mem_used != null && mn.mem_total ? `${bytes(mn.mem_used)} of ${bytes(mn.mem_total)} memory in use` : ''}
                            {mn.load != null ? ` · load ${mn.load.toFixed(1)}` : ''}
                        </p>
                        <ul class="power">
                            {mn.disks.map((d) => (
                                <li>
                                    <code>{d.p}</code> <span class="hint">{bytes(d.free)} free of {bytes(d.size)} ({Math.round((100 * (d.size - d.free)) / d.size)} % used)</span>
                                </li>
                            ))}
                        </ul>
                        <p class="hint">Sampled every minute; kept two weeks.</p>
                    </Card>
                ) : null}
            </div>
        )
    }
}