140 lines
7.9 KiB
TypeScript
140 lines
7.9 KiB
TypeScript
import { notFound } from "next/navigation";
|
||
import { Plus, RefreshCw, Server, Trash2 } from "lucide-react";
|
||
import { HOST_STATUS_RU, isSuperadmin, listHosts, type RunnerHostView } from "@peppa/core";
|
||
import { ensureSshKey, runnerImage } from "@peppa/runner";
|
||
import { Hidden } from "@/components/cards";
|
||
import { ago, Disclosure, Empty, Flash, PageHeader, Section } from "@/components/common";
|
||
import { Badge } from "@/components/ui/badge";
|
||
import { Button } from "@/components/ui/button";
|
||
import { Card } from "@/components/ui/card";
|
||
import { Input, Label } from "@/components/ui/input";
|
||
import { Workspace } from "@/components/Workspace";
|
||
import { requireUser } from "@/lib/auth";
|
||
import { db } from "@/lib/db";
|
||
import { getT } from "@/lib/i18n";
|
||
import type { Translator } from "@peppa/shared/i18n";
|
||
import { addHostAction, checkHostAction, deleteHostAction, toggleHostAction, updateHostAction } from "./actions";
|
||
|
||
export async function generateMetadata() {
|
||
const t = await getT();
|
||
return { title: t("Хосты — Peppa FACTORY") };
|
||
}
|
||
|
||
function StatusOf({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||
if (h.disabledAt) return <Badge variant="secondary">{t("отключён")}</Badge>;
|
||
return <Badge variant={h.status === "online" ? "ok" : h.status === "offline" ? "danger" : "info"}>{t(HOST_STATUS_RU[h.status])}</Badge>;
|
||
}
|
||
|
||
function HostFields({ h, t }: { h?: RunnerHostView; t: Translator }) {
|
||
return (
|
||
<div className="grid gap-2 sm:grid-cols-2">
|
||
<Label>
|
||
{t("SSH-адрес")}
|
||
<Input name="sshTarget" required placeholder="peppa@build1.example.com" defaultValue={h?.sshTarget} className="h-8 font-mono" />
|
||
</Label>
|
||
<Label>
|
||
{t("Порт SSH")}
|
||
<Input name="sshPort" type="number" min={1} max={65535} placeholder="22" defaultValue={h?.sshPort} className="h-8" />
|
||
</Label>
|
||
<Label>
|
||
{t("Каталог на хосте (от домашнего)")}
|
||
<Input name="workdir" placeholder="peppa" defaultValue={h?.workdir} className="h-8 font-mono" />
|
||
</Label>
|
||
<Label>
|
||
{t("Адрес Peppa FACTORY для хоста (релей агента)")}
|
||
<Input name="peppaUrl" placeholder={t("как PEPPA_WEB_URL")} defaultValue={h?.peppaUrl ?? ""} className="h-8 font-mono" />
|
||
</Label>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function HostCard({ h, t }: { h: RunnerHostView; t: Translator }) {
|
||
const i = h.info ?? {};
|
||
return (
|
||
<Card id={`h-${h.id}`} className="gap-2">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<span className="font-semibold">{h.name}</span>
|
||
<span className="font-mono text-xs text-muted-foreground">{h.sshTarget}{h.sshPort !== 22 ? `:${h.sshPort}` : ""}</span>
|
||
<StatusOf h={h} t={t} />
|
||
<span className="ml-auto text-xs text-muted-foreground">{t("раннеров: {n}", { n: h.runners })}</span>
|
||
</div>
|
||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||
{i.load != null && <span>{t("загрузка {load}", { load: i.load })}{i.cpus ? ` / ${i.cpus} CPU` : ""}</span>}
|
||
{i.docker && <span>docker {i.docker}</span>}
|
||
{i.tmux && <span>{i.tmux}</span>}
|
||
{i.os && <span>{i.os}</span>}
|
||
<span>{t("образ раннера:")} {i.image ? <span className="font-mono">{i.image}</span> : t("не загружен")}</span>
|
||
<span>{t("проверен {ago}", { ago: ago(h.lastSeenAt, t) })}</span>
|
||
</div>
|
||
{h.lastError && <p className="m-0 text-xs text-destructive">{h.lastError}</p>}
|
||
<div className="flex flex-wrap gap-2">
|
||
<form action={checkHostAction}>
|
||
<Hidden fields={{ id: h.id }} />
|
||
<Button size="sm" variant="outline"><RefreshCw />{t("Проверить")}</Button>
|
||
</form>
|
||
<form action={toggleHostAction}>
|
||
<Hidden fields={{ id: h.id, disable: h.disabledAt ? "0" : "1" }} />
|
||
<Button size="sm" variant="outline">{h.disabledAt ? t("Включить") : t("Отключить")}</Button>
|
||
</form>
|
||
<form action={deleteHostAction}>
|
||
<Hidden fields={{ id: h.id }} />
|
||
<Button size="sm" variant="ghost" disabled={h.runners > 0} title={h.runners > 0 ? t("На хосте работают раннеры") : undefined}><Trash2 />{t("Удалить")}</Button>
|
||
</form>
|
||
</div>
|
||
<Disclosure summary={t("Изменить")}>
|
||
<form action={updateHostAction} className="flex flex-col gap-2">
|
||
<Hidden fields={{ id: h.id }} />
|
||
<HostFields h={h} t={t} />
|
||
<Button size="sm" variant="default" className="self-start">{t("Сохранить и проверить")}</Button>
|
||
</form>
|
||
</Disclosure>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
export default async function Hosts({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||
const user = await requireUser();
|
||
const t = await getT();
|
||
if (!(await isSuperadmin(db, user))) notFound();
|
||
const { error } = await searchParams;
|
||
const [hosts, pub] = await Promise.all([listHosts(db), ensureSshKey().catch((e: Error) => t("(ключ не создан: {message})", { message: e.message }))]);
|
||
return (
|
||
<Workspace>
|
||
<div className="max-w-3xl">
|
||
<Flash error={error} />
|
||
<PageHeader title={<><Server className="mr-1 inline size-5 text-primary" />{t("Хосты")}</>}>
|
||
{t("Серверы, на которых работают раннеры. Peppa FACTORY заходит на хост по SSH своим ключом и запускает там tmux с агентом в контейнере образа раннера; агент ходит в Peppa FACTORY только через релей. Демона на хосте нет — нужны sshd, tmux и docker. Проект выбирает хосты в «⋯ Настройки проекта → Раннеры». Раздел видят только суперадмины.")}
|
||
</PageHeader>
|
||
|
||
<Section title={t("Хосты")} count={hosts.length}>
|
||
{hosts.length === 0 ? <Empty>{t("Хостов нет — раннеры работают на Mac Peppa FACTORY.")}</Empty> : hosts.map((h) => <HostCard key={h.id} h={h} t={t} />)}
|
||
<Disclosure summary={<span className="flex items-center gap-1.5"><Plus className="size-4" />{t("Подключить хост")}</span>}>
|
||
<form action={addHostAction} className="flex flex-col gap-2">
|
||
<Label>
|
||
{t("Имя")}
|
||
<Input name="name" required placeholder="build1" className="h-8" />
|
||
</Label>
|
||
<HostFields t={t} />
|
||
<Button size="sm" variant="default" className="self-start">{t("Подключить и проверить")}</Button>
|
||
</form>
|
||
</Disclosure>
|
||
</Section>
|
||
|
||
<Section title={t("Как подготовить хост")}>
|
||
<ol className="m-0 flex list-decimal flex-col gap-2 pl-5 text-sm">
|
||
<li>
|
||
{t("Добавьте ключ Peppa FACTORY в {file} пользователя на хосте:").split("{file}").flatMap((part, i) => (i ? [<code key={i}>~/.ssh/authorized_keys</code>, part] : [part]))}
|
||
<pre className="mt-1 overflow-x-auto rounded-md bg-muted p-2 text-xs"><code>{pub}</code></pre>
|
||
</li>
|
||
<li>{t("Установите tmux и docker; пользователь должен иметь доступ к docker.")}</li>
|
||
<li>
|
||
{t("Загрузите образ раннера")} <code>{runnerImage()}</code>: <code>{t("scripts/runner-image.sh --push <имя хоста>")}</code> ({t("или")} <code>{t("peppa host push-image <имя>")}</code>).
|
||
</li>
|
||
<li>{t("Адрес Peppa FACTORY для хоста должен открываться с хоста (по умолчанию — адрес веба); через него идут хуки, MCP и git агента.")}</li>
|
||
</ol>
|
||
</Section>
|
||
</div>
|
||
</Workspace>
|
||
);
|
||
}
|