feat(worker): supervise VPN connections and recover batched telemetry
This commit is contained in:
@@ -1,579 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
FeatureSettingsWindow,
|
||||
FieldFrame,
|
||||
Icon,
|
||||
Select,
|
||||
SettingsCard,
|
||||
StatusBadge,
|
||||
TextField,
|
||||
WindowFooterActions,
|
||||
} from "@nodedc/ui-react";
|
||||
|
||||
import {
|
||||
applyComputeContourNetwork,
|
||||
fetchComputeContourAgentInstall,
|
||||
fetchComputeContourNetwork,
|
||||
type ComputeContour,
|
||||
type ComputeContourAgentInstall,
|
||||
type ComputeContourDraft,
|
||||
type ComputeContourNetworkStatus,
|
||||
type ComputeContourPlatform,
|
||||
} from "../../core/system/computeContours";
|
||||
import {
|
||||
DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
|
||||
parseTelemetryPollIntervalDraft,
|
||||
resolveTelemetryPollIntervalDraft,
|
||||
} from "../../core/system/telemetryPollInterval";
|
||||
|
||||
interface ComputeContourSettingsWindowProps {
|
||||
open: boolean;
|
||||
contour: ComputeContour | null;
|
||||
mode: "create" | "edit";
|
||||
onClose: () => void;
|
||||
onCreate: (draft: ComputeContourDraft) => Promise<ComputeContour>;
|
||||
onUpdate: (
|
||||
contour: ComputeContour,
|
||||
draft: ComputeContourDraft,
|
||||
) => Promise<ComputeContour>;
|
||||
}
|
||||
|
||||
const platformOptions = [
|
||||
{ value: "windows", label: "Windows", description: "Worker с Windows service" },
|
||||
{ value: "linux", label: "Linux", description: "Worker с systemd service" },
|
||||
{ value: "unknown", label: "Не определено", description: "Платформа будет уточнена" },
|
||||
] satisfies Array<{
|
||||
value: ComputeContourPlatform;
|
||||
label: string;
|
||||
description: string;
|
||||
}>;
|
||||
|
||||
function emptyDraft(): ComputeContourDraft {
|
||||
return {
|
||||
display_name: "",
|
||||
expected_node_id: "",
|
||||
platform: "unknown",
|
||||
telemetry_mode: "agent-mqtt",
|
||||
address: "",
|
||||
ssh_port: 22,
|
||||
mqtt_host: "127.0.0.1",
|
||||
mqtt_port: 1883,
|
||||
mqtt_bind_address: "127.0.0.1",
|
||||
telemetry_poll_interval_seconds: DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
|
||||
mqtt_publish_interval_seconds: 2,
|
||||
};
|
||||
}
|
||||
|
||||
function draftFromContour(contour: ComputeContour | null): ComputeContourDraft {
|
||||
if (!contour) return emptyDraft();
|
||||
return {
|
||||
display_name: contour.display_name,
|
||||
expected_node_id: contour.expected_node_id,
|
||||
platform: contour.platform,
|
||||
telemetry_mode: contour.telemetry_mode,
|
||||
address: contour.address,
|
||||
ssh_port: contour.ssh_port,
|
||||
mqtt_host: contour.mqtt_host,
|
||||
mqtt_port: contour.mqtt_port,
|
||||
mqtt_bind_address: contour.mqtt_bind_address,
|
||||
telemetry_poll_interval_seconds: contour.telemetry_poll_interval_seconds,
|
||||
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
|
||||
};
|
||||
}
|
||||
|
||||
export function ComputeContourSettingsWindow({
|
||||
open,
|
||||
contour,
|
||||
mode,
|
||||
onClose,
|
||||
onCreate,
|
||||
onUpdate,
|
||||
}: ComputeContourSettingsWindowProps) {
|
||||
const [draft, setDraft] = useState<ComputeContourDraft>(() => draftFromContour(contour));
|
||||
const [telemetryPollIntervalDraft, setTelemetryPollIntervalDraft] = useState(
|
||||
() => String(draftFromContour(contour).telemetry_poll_interval_seconds),
|
||||
);
|
||||
const [mqttPublishIntervalDraft, setMqttPublishIntervalDraft] = useState(
|
||||
() => String(draftFromContour(contour).mqtt_publish_interval_seconds),
|
||||
);
|
||||
const [activeSection, setActiveSection] = useState<"connection" | "agent">("connection");
|
||||
const [install, setInstall] = useState<ComputeContourAgentInstall | null>(null);
|
||||
const [network, setNetwork] = useState<ComputeContourNetworkStatus | null>(null);
|
||||
const [networkAction, setNetworkAction] = useState<
|
||||
"refresh" | "broker" | "worker" | null
|
||||
>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const nextDraft = draftFromContour(mode === "edit" ? contour : null);
|
||||
setDraft(nextDraft);
|
||||
setTelemetryPollIntervalDraft(String(nextDraft.telemetry_poll_interval_seconds));
|
||||
setMqttPublishIntervalDraft(String(nextDraft.mqtt_publish_interval_seconds));
|
||||
setActiveSection("connection");
|
||||
setInstall(null);
|
||||
setNetwork(null);
|
||||
setNetworkAction(null);
|
||||
setError(null);
|
||||
}, [contour, mode, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || mode !== "edit" || !contour) return;
|
||||
const controller = new AbortController();
|
||||
setNetworkAction("refresh");
|
||||
void fetchComputeContourNetwork(contour.contour_id, controller.signal)
|
||||
.then((document) => {
|
||||
if (!controller.signal.aborted) setNetwork(document);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setNetworkAction(null);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [contour, mode, open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || mode !== "edit" || !contour) return;
|
||||
const controller = new AbortController();
|
||||
void fetchComputeContourAgentInstall(contour.contour_id, controller.signal)
|
||||
.then((document) => {
|
||||
if (!controller.signal.aborted) setInstall(document);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(reason instanceof Error ? reason.message : "Инструкция агента недоступна.");
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [contour, mode, open]);
|
||||
|
||||
const telemetryPollIntervalSeconds = useMemo(
|
||||
() => parseTelemetryPollIntervalDraft(telemetryPollIntervalDraft),
|
||||
[telemetryPollIntervalDraft],
|
||||
);
|
||||
const mqttPublishIntervalSeconds = useMemo(
|
||||
() => parseTelemetryPollIntervalDraft(mqttPublishIntervalDraft),
|
||||
[mqttPublishIntervalDraft],
|
||||
);
|
||||
|
||||
const valid = useMemo(() => (
|
||||
Boolean(draft.display_name.trim())
|
||||
&& Boolean(draft.expected_node_id.trim())
|
||||
&& Boolean(draft.mqtt_host.trim())
|
||||
&& Boolean(draft.mqtt_bind_address.trim())
|
||||
&& Number.isInteger(draft.ssh_port)
|
||||
&& draft.ssh_port > 0
|
||||
&& Number.isInteger(draft.mqtt_port)
|
||||
&& draft.mqtt_port > 0
|
||||
&& telemetryPollIntervalSeconds !== null
|
||||
&& mqttPublishIntervalSeconds !== null
|
||||
), [draft, mqttPublishIntervalSeconds, telemetryPollIntervalSeconds]);
|
||||
|
||||
const networkProfileDirty = Boolean(
|
||||
contour
|
||||
&& (
|
||||
draft.mqtt_host !== contour.mqtt_host
|
||||
|| draft.mqtt_port !== contour.mqtt_port
|
||||
|| draft.mqtt_bind_address !== contour.mqtt_bind_address
|
||||
|| draft.mqtt_publish_interval_seconds !== contour.mqtt_publish_interval_seconds
|
||||
),
|
||||
);
|
||||
|
||||
const commitTelemetryPollInterval = () => {
|
||||
const resolution = resolveTelemetryPollIntervalDraft(
|
||||
telemetryPollIntervalDraft,
|
||||
draft.telemetry_poll_interval_seconds,
|
||||
);
|
||||
setTelemetryPollIntervalDraft(resolution.draft);
|
||||
if (!resolution.accepted) return;
|
||||
setDraft((current) => (
|
||||
current.telemetry_poll_interval_seconds === resolution.seconds
|
||||
? current
|
||||
: {
|
||||
...current,
|
||||
telemetry_poll_interval_seconds: resolution.seconds,
|
||||
}
|
||||
));
|
||||
};
|
||||
|
||||
const commitMqttPublishInterval = () => {
|
||||
const resolution = resolveTelemetryPollIntervalDraft(
|
||||
mqttPublishIntervalDraft,
|
||||
draft.mqtt_publish_interval_seconds,
|
||||
);
|
||||
setMqttPublishIntervalDraft(resolution.draft);
|
||||
if (!resolution.accepted) return;
|
||||
setDraft((current) => (
|
||||
current.mqtt_publish_interval_seconds === resolution.seconds
|
||||
? current
|
||||
: {
|
||||
...current,
|
||||
mqtt_publish_interval_seconds: resolution.seconds,
|
||||
}
|
||||
));
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (
|
||||
!valid
|
||||
|| busy
|
||||
|| telemetryPollIntervalSeconds === null
|
||||
|| mqttPublishIntervalSeconds === null
|
||||
) return;
|
||||
const committedDraft = {
|
||||
...draft,
|
||||
telemetry_poll_interval_seconds: telemetryPollIntervalSeconds,
|
||||
mqtt_publish_interval_seconds: mqttPublishIntervalSeconds,
|
||||
};
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (mode === "edit" && contour) {
|
||||
await onUpdate(contour, committedDraft);
|
||||
} else {
|
||||
await onCreate(committedDraft);
|
||||
}
|
||||
onClose();
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : "Контур не сохранён.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshNetwork = async () => {
|
||||
if (!contour || networkAction) return;
|
||||
setNetworkAction("refresh");
|
||||
setError(null);
|
||||
try {
|
||||
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
|
||||
} finally {
|
||||
setNetworkAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const applyNetwork = async (target: "broker" | "worker") => {
|
||||
if (!contour || networkAction || networkProfileDirty) return;
|
||||
setNetworkAction(target);
|
||||
setError(null);
|
||||
try {
|
||||
await applyComputeContourNetwork(contour.contour_id, target);
|
||||
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
|
||||
} catch (reason) {
|
||||
setError(
|
||||
reason instanceof Error ? reason.message : "Сетевой профиль не применён.",
|
||||
);
|
||||
} finally {
|
||||
setNetworkAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<FeatureSettingsWindow
|
||||
open={open}
|
||||
title={mode === "create" ? "Добавить вычислительный контур" : "Настройки контура"}
|
||||
subtitle="Локальная переносимая конфигурация"
|
||||
identity={{
|
||||
title: contour?.display_name ?? "Новый контур",
|
||||
subtitle: contour?.expected_node_id ?? "Node ID не назначен",
|
||||
avatarLabel: contour?.display_name.slice(0, 2).toUpperCase() ?? "WC",
|
||||
}}
|
||||
sections={[
|
||||
{
|
||||
id: "connection",
|
||||
label: "Подключение",
|
||||
group: "ВЫЧИСЛИТЕЛЬНЫЙ КОНТУР",
|
||||
icon: "network",
|
||||
},
|
||||
{
|
||||
id: "agent",
|
||||
label: "Агент",
|
||||
group: "ТЕЛЕМЕТРИЯ",
|
||||
icon: "activity",
|
||||
disabled: mode === "create",
|
||||
},
|
||||
]}
|
||||
activeSection={activeSection}
|
||||
onSectionChange={setActiveSection}
|
||||
onClose={onClose}
|
||||
footer={(
|
||||
<WindowFooterActions>
|
||||
<Button variant="secondary" onClick={onClose}>Отмена</Button>
|
||||
<Button variant="primary" disabled={!valid || busy} onClick={() => void save()}>
|
||||
{busy ? "Сохраняем…" : mode === "create" ? "Добавить контур" : "Сохранить"}
|
||||
</Button>
|
||||
</WindowFooterActions>
|
||||
)}
|
||||
>
|
||||
<div className="compute-contour-settings">
|
||||
{activeSection === "connection" ? (
|
||||
<>
|
||||
<SettingsCard
|
||||
eyebrow="КОНТУР"
|
||||
title="Идентичность и локальная сеть"
|
||||
description="Node ID проверяется независимо от IP-адреса. Адрес можно менять при переносе комплекта в другую локальную сеть."
|
||||
>
|
||||
<div className="compute-contour-settings__form">
|
||||
<TextField
|
||||
label="Название"
|
||||
value={draft.display_name}
|
||||
placeholder="Worker 006"
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
display_name: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Ожидаемый Node ID"
|
||||
value={draft.expected_node_id}
|
||||
placeholder="DESKTOP-OPJ8J04"
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
expected_node_id: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<FieldFrame label="Операционная система">
|
||||
<Select
|
||||
label="Операционная система"
|
||||
value={draft.platform}
|
||||
options={platformOptions}
|
||||
variant="split"
|
||||
menuWidth="anchor"
|
||||
onChange={(platform) => setDraft((current) => ({ ...current, platform }))}
|
||||
/>
|
||||
</FieldFrame>
|
||||
<TextField
|
||||
label="Адрес узла"
|
||||
hint="IP или hostname в текущей LAN"
|
||||
value={draft.address}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
address: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="MQTT broker"
|
||||
hint="Стабильный hostname рекомендуется вместо выдаваемого DHCP IP"
|
||||
value={draft.mqtt_host}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_host: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="MQTT port"
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={String(draft.mqtt_port)}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_port: Number(event.currentTarget.value),
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Публикация broker"
|
||||
hint="IP текущего Mac в разрешённой LAN · 0.0.0.0 запрещён"
|
||||
value={draft.mqtt_bind_address}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
mqtt_bind_address: event.currentTarget.value,
|
||||
}))}
|
||||
/>
|
||||
<TextField
|
||||
label="Обновление интерфейса"
|
||||
hint="1–60 с"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
aria-invalid={telemetryPollIntervalSeconds === null}
|
||||
value={telemetryPollIntervalDraft}
|
||||
onChange={(event) => setTelemetryPollIntervalDraft(event.currentTarget.value)}
|
||||
onBlur={commitTelemetryPollInterval}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commitTelemetryPollInterval();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setTelemetryPollIntervalDraft(
|
||||
String(draft.telemetry_poll_interval_seconds),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
label="Интервал MQTT агента"
|
||||
hint="1–60 с · применяется конфигурацией агента"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
aria-invalid={mqttPublishIntervalSeconds === null}
|
||||
value={mqttPublishIntervalDraft}
|
||||
onChange={(event) => setMqttPublishIntervalDraft(event.currentTarget.value)}
|
||||
onBlur={commitMqttPublishInterval}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
commitMqttPublishInterval();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setMqttPublishIntervalDraft(
|
||||
String(draft.mqtt_publish_interval_seconds),
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{draft.telemetry_mode === "legacy-ssh" ? (
|
||||
<TextField
|
||||
label="SSH port"
|
||||
type="number"
|
||||
min={1}
|
||||
max={65535}
|
||||
value={String(draft.ssh_port)}
|
||||
onChange={(event) => setDraft((current) => ({
|
||||
...current,
|
||||
ssh_port: Number(event.currentTarget.value),
|
||||
}))}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
<SettingsCard
|
||||
eyebrow="СЕТЕВОЙ ПРОФИЛЬ"
|
||||
title="MQTT · Mac ↔ Worker"
|
||||
description="Mesh-точки одной LAN не закрепляются по отдельности. Профиль хранит стабильное имя Mac и адрес публикации broker в текущей сети."
|
||||
actions={(
|
||||
<StatusBadge tone={network?.broker.ready ? "success" : "warning"}>
|
||||
{network?.broker.ready ? "Broker доступен" : "Нужна проверка"}
|
||||
</StatusBadge>
|
||||
)}
|
||||
>
|
||||
<div className="compute-contour-settings__network">
|
||||
<dl>
|
||||
<div>
|
||||
<dt>Endpoint Worker</dt>
|
||||
<dd>{network
|
||||
? `${network.broker.configured_host}:${network.broker.configured_port}`
|
||||
: "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Текущий IP</dt>
|
||||
<dd>{network?.broker.resolved_addresses.join(", ") || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Публикация Mac</dt>
|
||||
<dd>{network?.broker.bind_address ?? "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{contour?.display_name ?? "Worker"}</dt>
|
||||
<dd>{network?.worker.reachable
|
||||
? `${network.worker.mqtt_host ?? "—"}:${network.worker.mqtt_port ?? "—"}`
|
||||
: "Недоступен"}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="compute-contour-settings__network-statuses">
|
||||
<StatusBadge tone={network?.broker.bind_reachable ? "success" : "danger"}>
|
||||
{network?.broker.bind_reachable
|
||||
? "Listener Mac доступен"
|
||||
: "Listener Mac недоступен"}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={network?.worker.broker_reachable ? "success" : "danger"}>
|
||||
{network?.worker.broker_reachable
|
||||
? "Worker видит broker"
|
||||
: "Worker не видит broker"}
|
||||
</StatusBadge>
|
||||
<StatusBadge tone={network?.worker.matches_profile ? "success" : "warning"}>
|
||||
{network?.worker.matches_profile
|
||||
? "Профиль синхронизирован"
|
||||
: "Профиль отличается"}
|
||||
</StatusBadge>
|
||||
</div>
|
||||
<div className="compute-contour-settings__network-actions">
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction)}
|
||||
icon={<Icon name="refresh" size={14} />}
|
||||
onClick={() => void refreshNetwork()}
|
||||
>
|
||||
{networkAction === "refresh" ? "Проверяем…" : "Проверить"}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction) || networkProfileDirty}
|
||||
onClick={() => void applyNetwork("broker")}
|
||||
>
|
||||
{networkAction === "broker" ? "Применяем…" : "Применить на Mac"}
|
||||
</Button>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={Boolean(networkAction) || networkProfileDirty}
|
||||
onClick={() => void applyNetwork("worker")}
|
||||
>
|
||||
{networkAction === "worker" ? "Применяем…" : "Применить на Worker"}
|
||||
</Button>
|
||||
</div>
|
||||
{networkProfileDirty ? (
|
||||
<p>Сначала сохраните изменённый сетевой профиль, затем примените его.</p>
|
||||
) : null}
|
||||
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{activeSection === "agent" ? (
|
||||
<SettingsCard
|
||||
eyebrow="АГЕНТ"
|
||||
title="Telegraf · универсальный сборщик"
|
||||
description="Hardware и runtime собирает готовый агент. Mission Core нормализует только контур, LAB/run и стадии обработки."
|
||||
actions={(
|
||||
<StatusBadge tone={install?.ready ? "success" : "warning"}>
|
||||
{install?.ready ? "Готов к установке" : "Нужен scoped MQTT credential"}
|
||||
</StatusBadge>
|
||||
)}
|
||||
>
|
||||
{install ? (
|
||||
<div className="compute-contour-settings__install">
|
||||
<dl>
|
||||
<div><dt>Шаблон</dt><dd>{install.agent.configuration_template}</dd></div>
|
||||
<div><dt>Секрет</dt><dd>интерактивный ввод · не хранится в UI</dd></div>
|
||||
</dl>
|
||||
<code>{install.command}</code>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
icon={<Icon name="copy" size={14} />}
|
||||
onClick={() => void navigator.clipboard.writeText(install.command)}
|
||||
>
|
||||
Копировать команду
|
||||
</Button>
|
||||
{install.blocked_reason ? <p>{install.blocked_reason}</p> : null}
|
||||
</div>
|
||||
) : (
|
||||
<p className="compute-contour-settings__empty">
|
||||
Сохраните контур, чтобы получить платформенную инструкцию установки.
|
||||
</p>
|
||||
)}
|
||||
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import {Button, Description, Icon, SettingsCard, StatusBadge} from "@nodedc/ui-react";
|
||||
import {fleetRequest} from "../../core/fleet/useFleet";
|
||||
import {connectionRequest, type ConnectionCatalog} from "../../core/system/workerConnections";
|
||||
|
||||
export function ImportNetworkProfile({onImported, disabled = false}: {onImported: () => Promise<unknown>; disabled?: boolean}) {
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return <>
|
||||
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event => {
|
||||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
|
||||
if (!file || busy) return;
|
||||
setBusy(true); setError(null);
|
||||
void (async () => {
|
||||
if (file.size > 16384) throw Error("Выберите файл подключения, выданный установщиком VPS.");
|
||||
await fleetRequest("/network-profiles/import", "POST", {document: await file.text()}, 240000);
|
||||
await onImported();
|
||||
})().catch(e => setError(e instanceof Error ? e.message : "Не удалось добавить профиль."))
|
||||
.finally(() => setBusy(false));
|
||||
}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={disabled || busy} loading={busy} onClick={() => input.current?.click()}>
|
||||
Импортировать подключение к серверу
|
||||
</Button>
|
||||
<Description>Файл mission-core-wireguard.json выдаёт установщик NODE.DC на вашем VPS. Получите его у администратора этого сервера и выберите здесь. Приглашение действует 24 часа; затем администратор выпускает новое. Экспорт туннеля из приложения WireGuard (.conf) не подходит.</Description>
|
||||
{error && <p role="alert"><StatusBadge tone="warning">{error}</StatusBadge></p>}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function SharedNetworkProfiles() {
|
||||
const [catalog, setCatalog] = useState<ConnectionCatalog | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
async function refresh(signal?: AbortSignal) {
|
||||
const value = await connectionRequest<ConnectionCatalog>("", undefined, signal);
|
||||
if (!signal?.aborted) {setCatalog(value); setError(null);}
|
||||
}
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void refresh(controller.signal).catch(e => {if (!controller.signal.aborted) setError(e.message);});
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
return <SettingsCard eyebrow="ОБЩИЕ СЕТИ" title="Сетевые подключения"
|
||||
description="Профили доступны всему парку. Активное подключение выбирается отдельно в настройках каждого устройства.">
|
||||
{catalog?.profiles.map(profile => <p key={profile.id}>
|
||||
<strong>{profile.name}</strong> · {profile.provider === "tailscale" ? "Tailscale" : "WireGuard"}
|
||||
{profile.provider === "wireguard" ? " · подключение устройств настраивается отдельно" : " · сеть текущего клиента"}
|
||||
</p>)}
|
||||
<Description>Адреса WireGuard в списке — серверы VPN. Tailscale показывает текущую сеть приложения на этом компьютере.</Description>
|
||||
<ImportNetworkProfile onImported={refresh}/>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{catalog?.notice && <Description>{catalog.notice}</Description>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { SegmentedControl } from "@nodedc/ui-react";
|
||||
|
||||
import { workspacesForRoot } from "../../productModel";
|
||||
|
||||
const systemWorkspaces = workspacesForRoot("system");
|
||||
const systemWorkspaces = workspacesForRoot("system").filter(item => item.kind === "compute-modules" || item.kind === "network-monitor");
|
||||
const compactLabels: Record<string, string> = {
|
||||
modules: "Модули",
|
||||
integrations: "Интеграции",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {useState} from "react";
|
||||
import {Button, Description, Icon} from "@nodedc/ui-react";
|
||||
import {connectionRequest, type TailscaleClient} from "../../core/system/workerConnections";
|
||||
|
||||
export function TailscaleClientStatus({client, disabled, onOpened}: {
|
||||
client: TailscaleClient; disabled: boolean; onOpened: () => Promise<unknown>;
|
||||
}) {
|
||||
const [opening, setOpening] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
if (client.state === "connected") return null;
|
||||
return <>
|
||||
<Description>{client.message}</Description>
|
||||
{client.state === "not_installed" ? <Button icon={<Icon name="download"/>}
|
||||
onClick={() => window.open("https://tailscale.com/download", "_blank", "noopener,noreferrer")}>
|
||||
Скачать Tailscale
|
||||
</Button> : client.can_open ? <Button disabled={disabled || opening} loading={opening}
|
||||
onClick={() => {
|
||||
setOpening(true); setError(null);
|
||||
void connectionRequest("/tailscale/open", {}).then(onOpened)
|
||||
.catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось открыть Tailscale."))
|
||||
.finally(() => setOpening(false));
|
||||
}}>{client.state === "needs_login" ? "Авторизироваться" : "Открыть Tailscale"}</Button>
|
||||
: <Description>Откройте установленный клиент Tailscale на этом компьютере и проверьте подключение.</Description>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Button, Description, FeatureSettingsWindow, FieldFrame, Icon, IconButton,
|
||||
Select, SettingsCard, StatusBadge, TextField, WindowFooterActions} from "@nodedc/ui-react";
|
||||
import {connectionRequest, keepAvailableSelection, workerCandidate, type ConnectionCheck} from "../../core/system/workerConnections";
|
||||
import {useConnectionCatalog} from "../../core/system/useConnectionCatalog";
|
||||
import type {ComputeContour, ComputeContourDraft} from "../../core/system/computeContours";
|
||||
import {ImportNetworkProfile} from "./SharedNetworkProfiles";
|
||||
import {TailscaleClientStatus} from "./TailscaleClientStatus";
|
||||
|
||||
interface Props {open: boolean; mode: "create" | "edit"; contour: ComputeContour | null;
|
||||
onClose: () => void; onChanged: () => void;
|
||||
onUpdate: (contour: ComputeContour, draft: ComputeContourDraft) => Promise<ComputeContour>}
|
||||
|
||||
export function WorkerConnectionSettings({open, mode, contour, onClose, onChanged, onUpdate}: Props) {
|
||||
const [section, setSection] = useState("connections");
|
||||
const [name, setName] = useState("");
|
||||
const [poll, setPoll] = useState("3");
|
||||
const [provider, setProvider] = useState("tailscale");
|
||||
const [profileId, setProfileId] = useState("");
|
||||
const [peerId, setPeerId] = useState("");
|
||||
const [selectedPath, setSelectedPath] = useState("");
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [acting, setBusy] = useState(false);
|
||||
const {catalog, refresh, discoveryError, initializing} = useConnectionCatalog(open, acting);
|
||||
const busy = acting || initializing;
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [check, setCheck] = useState<ConnectionCheck | null>(null);
|
||||
const worker = mode === "edit" ? catalog?.workers.find(x => x.contour_id === contour?.contour_id) : null;
|
||||
const enroll = !worker;
|
||||
const profiles = catalog?.profiles.filter(x => x.provider === provider
|
||||
&& catalog.available_profile_ids.includes(x.id)
|
||||
&& !worker?.connections.some(c => c.profile_id === x.id)) ?? [];
|
||||
const profile = profiles.find(x => x.id === profileId);
|
||||
const peers = catalog?.peers.filter(x => x.profile_id === profileId) ?? [];
|
||||
const candidate = workerCandidate(catalog, profileId, peerId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError(null); setCheck(null); setAdding(false); setSelectedPath("");
|
||||
setSection("connections"); setName(contour?.display_name ?? "");
|
||||
setPoll(String(contour?.telemetry_poll_interval_seconds ?? 3));
|
||||
}, [open, contour?.contour_id, mode]);
|
||||
useEffect(() => {setSelectedPath(worker?.active_connection_id ?? "");}, [worker?.active_connection_id]);
|
||||
useEffect(() => {setProfileId(current => keepAvailableSelection(current, profiles.map(x => x.id), profiles[0]?.id));}, [provider, catalog, worker?.revision]);
|
||||
useEffect(() => {setPeerId(current => keepAvailableSelection(current, peers.map(x => x.id)));}, [profileId, catalog]);
|
||||
const availableNetworks = catalog?.available_profile_ids.join(",");
|
||||
useEffect(() => {setCheck(null);}, [availableNetworks, catalog?.tailscale_client?.state]);
|
||||
async function action(fn: () => Promise<void>) {
|
||||
setBusy(true); setError(null);
|
||||
try {await fn();} catch (e) {setError(e instanceof Error ? e.message : "Операция не выполнена.");}
|
||||
finally {setBusy(false);}
|
||||
}
|
||||
async function add() {
|
||||
if (!catalog || !profile || !peerId) return;
|
||||
await connectionRequest(enroll ? "/enroll" : `/${worker!.contour_id}/attach`, {
|
||||
profile_id: profile.id, peer_id: peerId, revision: enroll ? catalog.revision : worker!.revision,
|
||||
...(enroll ? {binding_id: candidate.binding?.id} : {}),
|
||||
});
|
||||
await refresh(); onChanged(); setAdding(false); setCheck(null);
|
||||
if (mode === "create") onClose();
|
||||
}
|
||||
|
||||
return <FeatureSettingsWindow open={open} title={mode === "create" ? "Подключить воркер" : "Настройки воркера"}
|
||||
subtitle="Сетевые подключения" identity={{title: contour?.display_name ?? "Новый воркер",
|
||||
subtitle: contour?.expected_node_id ?? "Подключение к Mission Core", avatarLabel: "WC"}}
|
||||
sections={[{id: "connections", label: "Подключения", icon: "network", group: "ВОРКЕР"},
|
||||
...(mode === "edit" ? [{id: "agent", label: "Агент", icon: "activity" as const, group: "ВОРКЕР"}] : [])]}
|
||||
activeSection={section} onSectionChange={setSection} onClose={busy ? () => {} : onClose}
|
||||
headerActions={<IconButton label="Обновить подключения" disabled={busy} onClick={() => void action(async () => {await refresh(); setCheck(null);})}><Icon name="refresh"/></IconButton>}
|
||||
footer={<WindowFooterActions><Button onClick={onClose} disabled={busy}>Готово</Button></WindowFooterActions>}>
|
||||
<div className="compute-contour-settings">
|
||||
{section === "agent" && contour && <SettingsCard title="Устройство и телеметрия"
|
||||
description={`Идентичность: ${contour.expected_node_id}. Платформа: ${contour.platform}.`}>
|
||||
<div className="compute-contour-settings__form">
|
||||
<TextField label="Название" value={name} onChange={event => setName(event.currentTarget.value)}/>
|
||||
<TextField label="Обновление интерфейса, с" type="number" min={1} max={60} value={poll} onChange={event => setPoll(event.currentTarget.value)}/>
|
||||
</div>
|
||||
<Button disabled={busy || !name.trim() || !Number.isInteger(Number(poll)) || Number(poll) < 1 || Number(poll) > 60}
|
||||
onClick={() => void action(async () => {await onUpdate(contour, {
|
||||
display_name: name, expected_node_id: contour.expected_node_id, platform: contour.platform,
|
||||
telemetry_mode: contour.telemetry_mode, address: contour.address, ssh_port: contour.ssh_port,
|
||||
mqtt_host: contour.mqtt_host, mqtt_port: contour.mqtt_port, mqtt_bind_address: contour.mqtt_bind_address,
|
||||
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
|
||||
telemetry_poll_interval_seconds: Number(poll),
|
||||
});})}>Сохранить</Button>
|
||||
</SettingsCard>}
|
||||
{section === "connections" && worker && <SettingsCard eyebrow="ПОДКЛЮЧЕНИЯ" title="Активное подключение"
|
||||
description="Выбор сети относится только к этому воркеру. Другие устройства сохраняют свои подключения.">
|
||||
<div className="compute-contour-settings__form compute-contour-settings__connection-row">
|
||||
<FieldFrame label="Подключение"><Select label="Подключение" value={selectedPath} disabled={busy}
|
||||
options={worker.connections.map(x => ({value: x.id, label: catalog?.profiles.find(p => p.id === x.profile_id)?.name ?? x.profile_id,
|
||||
description: x.id === worker.active_connection_id ? "Активное" : "Подготовлено"}))}
|
||||
onChange={value => {setSelectedPath(value); setCheck(null);}}/></FieldFrame>
|
||||
<div className="system-workspace__actions">
|
||||
<Button disabled={busy || !selectedPath} onClick={() => void action(async () => {
|
||||
setCheck(await connectionRequest<ConnectionCheck>(`/${worker.contour_id}/check`, {connection_id: selectedPath, revision: worker.revision}));
|
||||
})}>Проверить</Button>
|
||||
<Button disabled={busy || !selectedPath || selectedPath === worker.active_connection_id} onClick={() => void action(async () => {
|
||||
await connectionRequest(`/${worker.contour_id}/activate`, {connection_id: selectedPath, revision: worker.revision});
|
||||
await refresh(); onChanged(); setCheck(null);
|
||||
})}>Использовать</Button>
|
||||
<IconButton label="Добавить подключение" disabled={busy} onClick={() => setAdding(!adding)}><Icon name="plus"/></IconButton>
|
||||
</div>
|
||||
</div>
|
||||
{catalog?.tailscale_client && worker.connections.some(path => path.id === selectedPath
|
||||
&& catalog.profiles.some(p => p.id === path.profile_id && p.provider === "tailscale"))
|
||||
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
|
||||
{catalog?.tailscale_client?.state === "connected" && worker.connections.some(path => path.id === selectedPath
|
||||
&& !catalog.available_profile_ids.includes(path.profile_id))
|
||||
&& <Description>Выбранная сеть сейчас недоступна. Подключите её в VPN-клиенте.</Description>}
|
||||
{check && <><StatusBadge tone="success">Устройство подтверждено · {check.identity.hostname}</StatusBadge>
|
||||
{check.active && check.channels.map(x => <p key={x.id}><StatusBadge tone={x.connected ? "success" : "warning"}>{x.label} · {x.connected ? "соединение установлено" : "ожидает подключения"}</StatusBadge></p>)}
|
||||
{check.active && <Description>Проверка подтверждает соединения. Свежие показатели и состояние сервисов отображаются в «Модулях».</Description>}
|
||||
{check.active && check.channels.length === 0 && <Description>Рабочие каналы ещё не установлены.</Description>}</>}
|
||||
</SettingsCard>}
|
||||
{section === "connections" && catalog && (enroll || adding) && <SettingsCard eyebrow="НОВОЕ ПОДКЛЮЧЕНИЕ" title={enroll ? "Выберите устройство" : "Добавить резервную сеть"}
|
||||
description="Выберите VPN, общую сеть и компьютер. Устройства в сети могут быть воркерами, бортами или другими компьютерами.">
|
||||
<div className="compute-contour-settings__form">
|
||||
<FieldFrame label="Тип VPN"><Select label="Тип VPN" value={provider} disabled={busy}
|
||||
options={[{value: "tailscale", label: "Tailscale"}, {value: "wireguard", label: "WireGuard"}]} onChange={setProvider}/></FieldFrame>
|
||||
<FieldFrame label="Сеть"><Select label="Сеть" value={profileId} disabled={busy || !profiles.length}
|
||||
options={profiles.map(x => ({value: x.id, label: x.name}))} onChange={setProfileId}/></FieldFrame>
|
||||
<FieldFrame label="Устройство в сети"><Select label="Устройство в сети" value={peerId} disabled={busy || !peers.length}
|
||||
options={[{value: "", label: "Выберите устройство"}, ...peers.map(x => ({value: x.id, label: x.name,
|
||||
description: workerCandidate(catalog, profileId, x.id).enrolled ? "Уже подключён к Mission Core" : x.online === false ? "Не в сети" : "Доступен в VPN"}))]} onChange={setPeerId}/></FieldFrame>
|
||||
</div>
|
||||
{provider === "tailscale" && catalog.tailscale_client
|
||||
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
|
||||
{enroll && candidate.enrolled && <Description>Этот воркер уже подключён. Его сети можно изменить через настройки в разделе «Система».</Description>}
|
||||
{enroll && candidate.peer && !candidate.enrolled && !candidate.binding && <Description>Устройство найдено в VPN, но доступ Mission Core к нему ещё не настроен. Сначала требуется подготовка агента и доступа на самом компьютере. Одного подключения к VPN недостаточно.</Description>}
|
||||
{enroll && candidate.binding && <Description>Доступ к {candidate.binding.name} подготовлен. При добавлении проверим устройство и его ключ.</Description>}
|
||||
{provider === "tailscale" && <Description>Сеть берётся из приложения Tailscale на этом Mac. Чтобы увидеть новый компьютер, подключите его к той же сети Tailscale.</Description>}
|
||||
{provider === "wireguard" && <Description>Здесь перечислены серверы WireGuard, добавленные в Mission Core. Адрес в названии относится к серверу VPN, а не к воркеру.</Description>}
|
||||
{provider === "wireguard" && !peers.length && <Description>Сервер не сообщает о зарегистрированных воркерах. Здесь показан его реестр устройств; поиск остальных компьютеров в туннеле не выполняется.</Description>}
|
||||
{provider === "wireguard" && <ImportNetworkProfile disabled={busy} onImported={refresh}/>}
|
||||
{!profiles.length && <Description>Доступных новых профилей этого типа нет.</Description>}
|
||||
<Button variant="primary" disabled={busy || !profile || !peerId || candidate.peer?.online === false || (enroll && (!candidate.binding || Boolean(candidate.enrolled)))} onClick={() => void action(add)}>
|
||||
{busy ? "Проверяем…" : "Проверить и добавить"}</Button>
|
||||
</SettingsCard>}
|
||||
{busy && <Description>Проверяем подключение…</Description>}
|
||||
{error && <p role="alert"><StatusBadge tone="warning">{error}</StatusBadge></p>}
|
||||
{discoveryError && <Description role="alert">{discoveryError}</Description>}
|
||||
{catalog?.notice && catalog.notice !== catalog.tailscale_client?.message && <Description>{catalog.notice}</Description>}
|
||||
</div>
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -2,7 +2,8 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
|
||||
import type { ApplicationPanelUtilityAction } from "@nodedc/ui-react";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
import { ComputeContourSettingsWindow } from "./ComputeContourSettingsWindow";
|
||||
import { WorkerConnectionSettings } from "./WorkerConnectionSettings";
|
||||
import { useWorkerPower } from "./useWorkerPower";
|
||||
|
||||
interface ComputeContourSettingsController {
|
||||
canEdit: boolean;
|
||||
@@ -14,6 +15,7 @@ interface ComputeContourSettingsController {
|
||||
|
||||
export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
const contours = useComputeContours();
|
||||
const power = useWorkerPower(contours.selectedContour);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mode, setMode] = useState<"create" | "edit">("edit");
|
||||
const openCreate = useCallback(() => {
|
||||
@@ -47,16 +49,16 @@ export function useComputeContourSettings(): ComputeContourSettingsController {
|
||||
canEdit: contours.selectedContour !== null,
|
||||
openCreate,
|
||||
openEdit,
|
||||
utilityActions,
|
||||
utilityActions: [...utilityActions, power.action],
|
||||
window: (
|
||||
<ComputeContourSettingsWindow
|
||||
<><WorkerConnectionSettings
|
||||
open={open}
|
||||
mode={mode}
|
||||
contour={contours.selectedContour}
|
||||
contour={mode === "create" ? null : contours.selectedContour}
|
||||
onClose={() => setOpen(false)}
|
||||
onCreate={contours.createContour}
|
||||
onChanged={() => {contours.refresh(); contours.refreshTelemetry();}}
|
||||
onUpdate={contours.updateContour}
|
||||
/>
|
||||
/>{power.window}</>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import {useState} from "react";
|
||||
import {Button, ConfirmationModal, Window, WindowFooterActions, type ApplicationPanelUtilityAction} from "@nodedc/ui-react";
|
||||
import {connectionRequest} from "../../core/system/workerConnections";
|
||||
import type {ComputeContour} from "../../core/system/computeContours";
|
||||
|
||||
export function useWorkerPower(contour: ComputeContour | null) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [pending, setPending] = useState<{id: string; name: string; confirmation: string} | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const action: ApplicationPanelUtilityAction = {
|
||||
label: "Выключить воркер", icon: "power", disabled: !contour || busy,
|
||||
onClick: () => {if (!contour) return; setBusy(true); setError(null);
|
||||
const selected = contour;
|
||||
void connectionRequest<{confirmation: string}>(`/${selected.contour_id}/power/prepare`, {})
|
||||
.then(value => setPending({id: selected.contour_id, name: selected.display_name, confirmation: value.confirmation}))
|
||||
.catch(e => setMessage(e instanceof Error ? e.message : "Воркер недоступен."))
|
||||
.finally(() => setBusy(false));
|
||||
},
|
||||
};
|
||||
const window = <>
|
||||
<ConfirmationModal open={pending !== null} title="Выключить воркер?" danger
|
||||
confirmLabel="Да, выключить" pendingLabel="Передаём команду…" onClose={() => {if (!busy) setPending(null);}}
|
||||
description={<><p>Воркер «{pending?.name}» завершит работу. Выполняемые на нём задачи будут прерваны. Для включения потребуется доступ к компьютеру.</p>
|
||||
{error && <p role="alert">{error}</p>}</>}
|
||||
onConfirm={async () => {
|
||||
if (!pending || busy) return;
|
||||
setBusy(true); setError(null);
|
||||
try {
|
||||
const result = await connectionRequest<{message: string}>(`/${pending.id}/power/shutdown`, {confirmation: pending.confirmation});
|
||||
setPending(null); setMessage(result.message);
|
||||
} catch (e) {
|
||||
setPending(null); setMessage(e instanceof Error ? e.message : "Ответ не получен. Автоматического повтора нет.");
|
||||
} finally {setBusy(false);}
|
||||
}}/>
|
||||
<Window open={message !== null} title="Питание воркера" size="sm" onClose={() => setMessage(null)}
|
||||
footer={<WindowFooterActions><Button onClick={() => setMessage(null)}>Понятно</Button></WindowFooterActions>}>
|
||||
<p role="status">{message}</p>
|
||||
</Window>
|
||||
</>;
|
||||
return {action, window};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import {useCallback, useEffect, useRef, useState} from "react";
|
||||
import {connectionRequest, type ConnectionCatalog} from "./workerConnections";
|
||||
|
||||
/** One request at a time; refresh while visible and when returning from the VPN app. */
|
||||
export function useConnectionCatalog(open: boolean, suspended: boolean) {
|
||||
const [catalog, setCatalog] = useState<ConnectionCatalog | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [initializing, setInitializing] = useState(false);
|
||||
const active = useRef(false);
|
||||
const pause = useRef(suspended); pause.current = suspended;
|
||||
const request = useRef<{controller: AbortController; promise: Promise<ConnectionCatalog>} | null>(null);
|
||||
const refresh = useCallback((): Promise<ConnectionCatalog> => {
|
||||
if (request.current) return request.current.promise;
|
||||
const controller = new AbortController();
|
||||
const promise = connectionRequest<ConnectionCatalog>("", undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (active.current && !controller.signal.aborted) {setCatalog(value); setError(null);}
|
||||
return value;
|
||||
}).catch(reason => {
|
||||
if (active.current && !controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Не удалось обновить подключения.");
|
||||
throw reason;
|
||||
}).finally(() => {if (request.current?.controller === controller) request.current = null;});
|
||||
request.current = {controller, promise};
|
||||
return promise;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
active.current = true;
|
||||
let disposed = false;
|
||||
setCatalog(null); setError(null); setInitializing(true);
|
||||
void refresh().catch(() => {}).finally(() => {if (!disposed) setInitializing(false);});
|
||||
const update = () => {
|
||||
if (!pause.current && document.visibilityState === "visible") void refresh().catch(() => {});
|
||||
};
|
||||
const timer = window.setInterval(update, 5000);
|
||||
window.addEventListener("focus", update);
|
||||
document.addEventListener("visibilitychange", update);
|
||||
return () => {
|
||||
disposed = true; active.current = false;
|
||||
window.clearInterval(timer);
|
||||
window.removeEventListener("focus", update);
|
||||
document.removeEventListener("visibilitychange", update);
|
||||
request.current?.controller.abort(); request.current = null;
|
||||
};
|
||||
}, [open, refresh]);
|
||||
return {catalog, refresh, discoveryError: error, initializing};
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export function useWorkerTelemetry(
|
||||
pollMilliseconds = DEFAULT_WORKER_TELEMETRY_POLL_MILLISECONDS,
|
||||
enabled = true,
|
||||
externalRefreshGeneration = 0,
|
||||
historyLimit = 90,
|
||||
): WorkerTelemetryState {
|
||||
const normalizedPollMilliseconds = normalizeWorkerTelemetryPollMilliseconds(
|
||||
pollMilliseconds,
|
||||
@@ -44,7 +45,7 @@ export function useWorkerTelemetry(
|
||||
const stopPolling = startSequentialPolling(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const document = await fetchWorkerTelemetry(contourId, controller.signal);
|
||||
const document = await fetchWorkerTelemetry(contourId, controller.signal, historyLimit);
|
||||
if (controller.signal.aborted) return;
|
||||
setTelemetry(document);
|
||||
setError(null);
|
||||
@@ -70,6 +71,7 @@ export function useWorkerTelemetry(
|
||||
externalRefreshGeneration,
|
||||
generation,
|
||||
normalizedPollMilliseconds,
|
||||
historyLimit,
|
||||
]);
|
||||
|
||||
return { telemetry, loading, error, refresh };
|
||||
|
||||
@@ -5,7 +5,12 @@ export function workerConnectionStatus(telemetry: WorkerTelemetry | null) {
|
||||
const connection = telemetry?.connection;
|
||||
if (!connection) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Состояние вычислителя пока не подтверждено.'} as const;
|
||||
if (connection.reachable && !connection.identity_matches) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Ответивший узел не совпадает с выбранным вычислителем.'} as const;
|
||||
if (connection.reachable && connection.identity_matches && telemetry.node) return {state:'online', tone:'success', label:'В сети', detail:null} as const;
|
||||
if (connection.reachable && connection.identity_matches && telemetry.node) {
|
||||
if (typeof telemetry.node.cpu?.load_percent !== 'number' || typeof telemetry.node.memory?.used_percent !== 'number') {
|
||||
return {state:'unknown', tone:'warning', label:'Телеметрия неполная', detail:'Устройство отвечает, но свежие показатели нагрузки не получены.'} as const;
|
||||
}
|
||||
return {state:'online', tone:'success', label:'В сети', detail:null} as const;
|
||||
}
|
||||
if (['telemetry-receiver-unavailable','telemetry-agent-unavailable','invalid-telemetry-response'].includes(connection.error_code ?? '')) {
|
||||
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Mission Core не получает данные через службу телеметрии. Состояние самого вычислителя не подтверждено.'} as const;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
export interface NetworkProfile {
|
||||
id: string; name: string; provider: "tailscale" | "wireguard"; network_id: string;
|
||||
}
|
||||
export interface WorkerPath {id: string; profile_id: string; endpoint: string; peer_id: string}
|
||||
export interface WorkerBinding {
|
||||
contour_id: string; revision: number; active_connection_id: string | null;
|
||||
connections: WorkerPath[];
|
||||
}
|
||||
export interface ConnectionCatalog {
|
||||
revision: number; profiles: NetworkProfile[]; available_profile_ids: string[];
|
||||
peers: {id: string; profile_id: string; name: string; online: boolean | null}[];
|
||||
workers: WorkerBinding[];
|
||||
prepared: {id: string; contour_id: string; name: string; hostname: string; platform: string}[];
|
||||
notice: string | null;
|
||||
tailscale_client?: TailscaleClient;
|
||||
}
|
||||
export interface TailscaleClient {
|
||||
state: "not_installed" | "unavailable" | "needs_login" | "stopped" | "needs_approval" | "starting" | "connected";
|
||||
message: string; can_open: boolean; version: string | null;
|
||||
}
|
||||
|
||||
export function keepAvailableSelection(current: string, ids: string[], fallback = "") {
|
||||
return ids.includes(current) ? current : fallback;
|
||||
}
|
||||
export interface ConnectionCheck {
|
||||
identity: {hostname: string; platform: string}; active: boolean;
|
||||
channels: {id: string; label: string; connected: boolean}[];
|
||||
}
|
||||
|
||||
// A name match only selects an installed credential binding. Admission still
|
||||
// verifies the pinned host key and the remote identity on the server.
|
||||
export function workerCandidate(catalog: ConnectionCatalog | null, profileId: string, peerId: string) {
|
||||
const peer = catalog?.peers.find(x => x.profile_id === profileId && x.id === peerId);
|
||||
const enrolled = catalog?.workers.find(w => w.connections.some(x => x.profile_id === profileId && x.peer_id === peerId));
|
||||
const matches = peer ? catalog?.prepared.filter(x => x.hostname.toLowerCase() === peer.name.toLowerCase()
|
||||
&& !catalog.workers.some(w => w.contour_id === x.contour_id)) ?? [] : [];
|
||||
return {peer, enrolled, binding: matches.length === 1 ? matches[0] : null};
|
||||
}
|
||||
export async function connectionRequest<T>(path = "", body?: unknown, signal?: AbortSignal): Promise<T> {
|
||||
const response = await fetch(`/api/v1/system/connections${path}`, {
|
||||
method: body === undefined ? "GET" : "POST", cache: "no-store", signal,
|
||||
headers: body === undefined ? undefined : {"Content-Type": "application/json"},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const value = await response.json();
|
||||
if (!response.ok) throw new Error(typeof value.detail === "string" ? value.detail : "Подключение не подтверждено.");
|
||||
return value as T;
|
||||
}
|
||||
@@ -193,10 +193,11 @@ async function requestJson(
|
||||
export async function fetchWorkerTelemetry(
|
||||
contourId: string,
|
||||
signal?: AbortSignal,
|
||||
historyLimit = 90,
|
||||
): Promise<WorkerTelemetry> {
|
||||
const document = requireJsonRecord(
|
||||
await requestJson(
|
||||
`/api/v1/system/contours/${encodeURIComponent(contourId)}/telemetry?history=90`,
|
||||
`/api/v1/system/contours/${encodeURIComponent(contourId)}/telemetry?history=${historyLimit}`,
|
||||
{
|
||||
method: "GET",
|
||||
signal: signal
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.compute-contour-settings__connection-row {
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.compute-contour-settings__install,
|
||||
.compute-contour-settings__network {
|
||||
display: grid;
|
||||
|
||||
@@ -171,8 +171,8 @@ export function ComputeModulesWorkspace() {
|
||||
<h3>{node?.node_id ?? selectedContour?.expected_node_id ?? "Node ID не назначен"}</h3>
|
||||
<p>{node?.os.caption ?? "Аппаратный профиль недоступен"}</p>
|
||||
</div>
|
||||
<StatusBadge tone={node?.node_id ? "success" : "danger"}>
|
||||
{node?.node_id ? selectedContour?.display_name : "Нет данных"}
|
||||
<StatusBadge tone={connectionStatus.tone}>
|
||||
{connectionStatus.state === "online" ? selectedContour?.display_name : connectionStatus.label}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
<div className="worker-hardware__facts">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
|
||||
import {SharedNetworkProfiles} from '../../components/system/SharedNetworkProfiles';
|
||||
import {
|
||||
GlassSurface,
|
||||
StatusBadge,
|
||||
@@ -57,6 +58,7 @@ export function NetworkWorkspace() {
|
||||
</section>
|
||||
|
||||
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
|
||||
<SharedNetworkProfiles/>
|
||||
{error ? (
|
||||
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
|
||||
<StatusBadge tone="warning">{error}</StatusBadge>
|
||||
@@ -92,7 +94,7 @@ export function NetworkWorkspace() {
|
||||
</div>
|
||||
<div className="network-stat-card">
|
||||
<span>Активные интерфейсы</span>
|
||||
<strong>{telemetry?.network.interfaces.length ?? "—"}</strong>
|
||||
<strong>{telemetry?.network.interfaces.length || "—"}</strong>
|
||||
<small>{agentTelemetry ? "Telegraf net input" : "Windows network counters"}</small>
|
||||
</div>
|
||||
</section>
|
||||
@@ -114,7 +116,7 @@ export function NetworkWorkspace() {
|
||||
<i aria-hidden="true" data-state="online" />
|
||||
<div data-state={connected ? "online" : "unknown"}>
|
||||
<span>Telemetry plane</span>
|
||||
<strong>{agentTelemetry ? "Mosquitto + Timescale" : "SSH diagnostic"}</strong>
|
||||
<strong>{agentTelemetry ? "MQTT · текущая телеметрия" : "SSH diagnostic"}</strong>
|
||||
<small>
|
||||
{agentTelemetry
|
||||
? `${selectedContour?.mqtt_host ?? "—"}:${selectedContour?.mqtt_port ?? "—"}`
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {readFile} from "node:fs/promises";
|
||||
import ts from "typescript";
|
||||
|
||||
const moduleUrl = source => `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`;
|
||||
const transpile = source => ts.transpileModule(source, {compilerOptions: {
|
||||
module: ts.ModuleKind.ES2022, target: ts.ScriptTarget.ES2022,
|
||||
}}).outputText;
|
||||
const contractUrl = moduleUrl(transpile(await readFile("src/core/system/workerConnections.ts", "utf8")));
|
||||
const {keepAvailableSelection} = await import(contractUrl);
|
||||
|
||||
test("discovery preserves an existing choice but clears a peer from the previous account", () => {
|
||||
assert.equal(keepAvailableSelection("peer-b", ["peer-new", "peer-b"]), "peer-b");
|
||||
assert.equal(keepAvailableSelection("peer-b", ["other-account-peer"]), "");
|
||||
assert.equal(keepAvailableSelection("network-old", ["network-new"], "network-new"), "network-new");
|
||||
});
|
||||
|
||||
test("visible discovery is sequential, resumes after errors, and ignores a closed window's response", async () => {
|
||||
const effects = [], writes = [], calls = [];
|
||||
const events = new Map();
|
||||
let tick, removed = 0;
|
||||
const harness = {
|
||||
useState: initial => [initial, value => writes.push(value)],
|
||||
useRef: value => ({current: value}), useCallback: fn => fn,
|
||||
useEffect: fn => effects.push(fn),
|
||||
};
|
||||
const prior = {window: globalThis.window, document: globalThis.document,
|
||||
fetch: globalThis.fetch, hooks: globalThis.connectionHooks};
|
||||
globalThis.connectionHooks = harness;
|
||||
globalThis.window = {
|
||||
setInterval: fn => {tick = fn; return 1;}, clearInterval: () => {tick = undefined;},
|
||||
addEventListener: (name, fn) => events.set(name, fn),
|
||||
removeEventListener: name => {events.delete(name); removed++;},
|
||||
};
|
||||
globalThis.document = {
|
||||
visibilityState: "visible", addEventListener: (name, fn) => events.set(name, fn),
|
||||
removeEventListener: name => {events.delete(name); removed++;},
|
||||
};
|
||||
globalThis.fetch = (_, options) => new Promise((resolve, reject) => calls.push({options, resolve, reject}));
|
||||
let cleanup;
|
||||
try {
|
||||
const reactUrl = moduleUrl(`export const {useState,useRef,useCallback,useEffect}=globalThis.connectionHooks;`);
|
||||
const source = transpile(await readFile("src/core/system/useConnectionCatalog.ts", "utf8"))
|
||||
.replace('from "react"', `from "${reactUrl}"`)
|
||||
.replace('from "./workerConnections"', `from "${contractUrl}"`);
|
||||
const {useConnectionCatalog} = await import(moduleUrl(source));
|
||||
useConnectionCatalog(true, false);
|
||||
cleanup = effects[0]();
|
||||
const settled = () => new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls.length, 1);
|
||||
tick(); events.get("focus")();
|
||||
assert.equal(calls.length, 1, "focus and timer must reuse the pending request");
|
||||
calls[0].resolve(new Response(JSON.stringify({revision: 1})));
|
||||
await settled();
|
||||
assert(writes.some(x => x?.revision === 1));
|
||||
globalThis.document.visibilityState = "hidden";
|
||||
tick(); assert.equal(calls.length, 1);
|
||||
globalThis.document.visibilityState = "visible";
|
||||
events.get("visibilitychange")(); assert.equal(calls.length, 2);
|
||||
calls[1].reject(new Error("temporary disconnect")); await settled();
|
||||
tick(); assert.equal(calls.length, 3, "transient failure must not stop discovery");
|
||||
cleanup(); cleanup = null;
|
||||
assert(calls[2].options.signal.aborted);
|
||||
assert.equal(removed, 2); assert.equal(tick, undefined);
|
||||
const before = writes.length;
|
||||
calls[2].resolve(new Response(JSON.stringify({revision: 999})));
|
||||
await settled();
|
||||
assert.equal(writes.length, before, "late response must not update a closed window");
|
||||
} finally {
|
||||
cleanup?.();
|
||||
globalThis.window = prior.window; globalThis.document = prior.document;
|
||||
globalThis.fetch = prior.fetch; globalThis.connectionHooks = prior.hooks;
|
||||
}
|
||||
});
|
||||
@@ -11,7 +11,7 @@ after(async()=>{await server?.close();});
|
||||
|
||||
const core={ok:true,service:'mission-core-control-plane',version:'test',plugin_runtimes:{ready:1,total:1}};
|
||||
const contour={contour_id:'test-compute',display_name:'Test compute',expected_node_id:'test-node'};
|
||||
const worker={schema_version:'missioncore.worker-telemetry/v1',profile:{},connection:{reachable:true,identity_matches:true},node:{node_id:'test-node'},runtimes:[],pipeline:{},network:{},history:[]};
|
||||
const worker={schema_version:'missioncore.worker-telemetry/v1',profile:{},connection:{reachable:true,identity_matches:true},node:{node_id:'test-node',cpu:{load_percent:0},memory:{used_percent:15}},runtimes:[],pipeline:{},network:{},history:[]};
|
||||
const vehicle={id:'test-vehicle',name:'Test rover',enrollment:'paired',connectivity:'offline'};
|
||||
function installFetch(t,{failed=[],data={}}={}){
|
||||
const calls=[];
|
||||
@@ -75,3 +75,31 @@ test('a responding Core with recording capacity pressure remains reachable',asyn
|
||||
assert.equal(contourSummary(snapshot).online,2);
|
||||
assert.equal(contourSummary(snapshot).label,'Mission Core работает с ограничениями');
|
||||
});
|
||||
|
||||
|
||||
test('a pipeline-only heartbeat does not claim complete host telemetry', async () => {
|
||||
const {workerConnectionStatus}=await server.ssrLoadModule('/src/core/system/workerConnectionStatus.ts');
|
||||
const incomplete={...worker,node:{node_id:'test-node',cpu:{},memory:{used_percent:null}}};
|
||||
assert.equal(workerConnectionStatus(incomplete).state,'unknown');
|
||||
assert.equal(workerConnectionStatus(incomplete).label,'Телеметрия неполная');
|
||||
assert.equal(workerConnectionStatus(worker).state,'online');
|
||||
});
|
||||
|
||||
test('new worker selection distinguishes discovered, enrolled and prepared devices', async () => {
|
||||
const {workerCandidate}=await server.ssrLoadModule('/src/core/system/workerConnections.ts');
|
||||
const catalog={peers:[{id:'p',profile_id:'net',name:'node'}],workers:[],prepared:[]};
|
||||
assert.equal(workerCandidate(catalog,'net','p').binding,null);
|
||||
const ready={...catalog,prepared:[{id:'binding',contour_id:'c',hostname:'NODE'}]};
|
||||
assert.equal(workerCandidate(ready,'net','p').binding.id,'binding');
|
||||
const enrolled={...ready,workers:[{contour_id:'c',connections:[{profile_id:'net',peer_id:'p'}]}]};
|
||||
assert.equal(workerCandidate(enrolled,'net','p').enrolled.contour_id,'c');
|
||||
assert.equal(workerCandidate(enrolled,'net','p').binding,null);
|
||||
assert.equal(workerCandidate({...ready,prepared:[...ready.prepared,...ready.prepared]},'net','p').binding,null);
|
||||
});
|
||||
|
||||
test('system contains worker and VPS catalogs plus operational worker detail pages', async () => {
|
||||
const {workspacesForRoot,workspaceById}=await server.ssrLoadModule('/src/productModel.ts');
|
||||
assert.deepEqual(workspacesForRoot('system').map(x=>x.id),['workers','vps','modules','network']);
|
||||
assert.equal(workspaceById('integrations'),null);
|
||||
assert.equal(workspaceById('audit'),null);
|
||||
});
|
||||
|
||||
@@ -38,7 +38,7 @@ test("Compute-contour telemetry remains a bounded system feature slice", async (
|
||||
read("core/system/ComputeContourContext.tsx"),
|
||||
read("components/useApplicationPanelActions.ts"),
|
||||
read("components/system/useComputeContourSettings.tsx"),
|
||||
read("components/system/ComputeContourSettingsWindow.tsx"),
|
||||
read("components/system/WorkerConnectionSettings.tsx"),
|
||||
read("core/system/computeContours.ts"),
|
||||
read("core/system/telemetryPollInterval.ts"),
|
||||
read("core/system/sequentialPolling.ts"),
|
||||
@@ -100,16 +100,11 @@ test("Compute-contour telemetry remains a bounded system feature slice", async (
|
||||
assert.doesNotMatch(contourSettings, /<dt>Worker 006<\/dt>/);
|
||||
assert.match(contourSettings, /contour\?\.display_name/);
|
||||
assert.match(telemetryPolling, /Вычислительный контур не ответил\./);
|
||||
assert.match(contourSettings, /FieldFrame label="Операционная система"/);
|
||||
assert.match(contourSettings, /label="Обновление интерфейса"/);
|
||||
assert.match(contourSettings, /label="Интервал MQTT агента"/);
|
||||
assert.match(contourSettings, /label="Публикация broker"/);
|
||||
assert.match(contourSettings, /MQTT · Mac ↔ Worker/);
|
||||
assert.match(contourSettings, /applyComputeContourNetwork/);
|
||||
assert.match(contourSettings, /Применить на Worker/);
|
||||
assert.match(contourSettings, /value=\{telemetryPollIntervalDraft\}/);
|
||||
assert.match(contourSettings, /onBlur=\{commitTelemetryPollInterval\}/);
|
||||
assert.match(contourSettings, /event\.key === "Escape"/);
|
||||
assert.match(contourSettings, /label="Обновление интерфейса, с"/);
|
||||
assert.match(contourSettings, /label="Тип VPN"/);
|
||||
assert.match(contourSettings, /label="Сеть"/);
|
||||
assert.match(contourSettings, /label="Устройство в сети"/);
|
||||
assert.doesNotMatch(contourSettings, /label="Адрес узла"|label="Ожидаемый Node ID"|label="Публикация broker"/);
|
||||
assert.doesNotMatch(
|
||||
contourSettings,
|
||||
/telemetry_poll_interval_seconds:\s*Number\(event\.currentTarget\.value\)/,
|
||||
|
||||
@@ -241,3 +241,20 @@ See [the measured recovery audit](../../docs/audits/2026-09-25-worker-telemetry-
|
||||
for exact acceptance, remaining cold-boot/clean-host gates and bounded test
|
||||
entrypoints. The earlier LAN workflow remains a legacy explicit configuration;
|
||||
it is not the current Worker 006 transport.
|
||||
|
||||
|
||||
## MQTT batching — 2026-11-09
|
||||
|
||||
The Windows and Linux templates publish topic batches (`layout="batch"`). The
|
||||
normalizer accepts both legacy single samples and Telegraf `{"metrics":[...]}`
|
||||
messages, bounded to 512 samples and 1 MiB. Each metric keeps its original source
|
||||
time; batching does not renew stale samples or change ACL/freshness rules.
|
||||
Deploy the compatible normalizer before switching existing agents. A narrow
|
||||
managed-Windows migration is `telegraf/Enable-NdcMissionCoreTelemetryBatch.ps1`;
|
||||
its configuration backup and rollback preserve existing service credentials.
|
||||
|
||||
This avoids one synchronous QoS 1 round trip per metric on high-latency links.
|
||||
The Worker 006 controlled benchmark and remaining real-LTE acceptance are recorded
|
||||
in [Worker connections](../../docs/WORKER_CONNECTIONS.md). The current registry
|
||||
owns all four channel supervisors; the older telemetry startup tool refuses to
|
||||
replace a registry-managed tunnel.
|
||||
|
||||
@@ -29,6 +29,7 @@ PIPELINE_EVENT_MEASUREMENT: Final = "missioncore_pipeline_event"
|
||||
QUERY_SCHEMA: Final = "missioncore.telemetry-query/v1"
|
||||
SAFE_IDENTIFIER: Final = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")
|
||||
MAX_PAYLOAD_BYTES: Final = 1024 * 1024
|
||||
MAX_MESSAGE_METRICS: Final = 512
|
||||
MAX_TAGS: Final = 256
|
||||
MAX_SERIES_KEY_BYTES: Final = 4096
|
||||
LATEST_TTL_SECONDS: Final = 300
|
||||
@@ -218,6 +219,28 @@ def _normalize(topic: str, payload: bytes) -> tuple[object, ...]:
|
||||
)
|
||||
|
||||
|
||||
def normalize_message(topic: str, payload: bytes) -> list[tuple]:
|
||||
"""Accept both original single samples and Telegraf's topic batch envelope.
|
||||
|
||||
Validate the complete bounded message before admitting any of its samples.
|
||||
Every sample retains its own source timestamp and series identity.
|
||||
"""
|
||||
if len(payload) > MAX_PAYLOAD_BYTES:
|
||||
raise ValueError("telemetry message is too large")
|
||||
document = json.loads(payload)
|
||||
if not isinstance(document, dict) or "metrics" not in document:
|
||||
return [_normalize(topic, payload)]
|
||||
metrics = document["metrics"]
|
||||
if (
|
||||
set(document) != {"metrics"}
|
||||
or not isinstance(metrics, list)
|
||||
or not 1 <= len(metrics) <= MAX_MESSAGE_METRICS
|
||||
or any(not isinstance(metric, dict) or "metrics" in metric for metric in metrics)
|
||||
):
|
||||
raise ValueError("invalid telemetry batch")
|
||||
return [_normalize(topic, json.dumps(metric).encode("utf-8")) for metric in metrics]
|
||||
|
||||
|
||||
class LatestTelemetry:
|
||||
"""Bounded volatile latest-value cache; never a time-series archive."""
|
||||
|
||||
@@ -516,9 +539,9 @@ def main() -> None:
|
||||
|
||||
def on_message(_client, _userdata, message):
|
||||
try:
|
||||
row = _normalize(message.topic, message.payload)
|
||||
if cache.put(row):
|
||||
runtime_health.mark_ingested()
|
||||
for row in normalize_message(message.topic, message.payload):
|
||||
if cache.put(row):
|
||||
runtime_health.mark_ingested()
|
||||
except (ValueError, UnicodeDecodeError, TypeError, OverflowError):
|
||||
# Never log rejected payloads or emit an unbounded line per bad sample.
|
||||
return
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory=$true)][string]$ExpectedNodeId)
|
||||
# Narrow migration for existing managed agents; fresh installs use the templates.
|
||||
$ErrorActionPreference='Stop'
|
||||
$ProgressPreference='SilentlyContinue'
|
||||
if ($env:COMPUTERNAME -cne $ExpectedNodeId) { throw 'Worker identity mismatch' }
|
||||
$root='C:\ProgramData\NDC\MissionCore\telemetry-agent'
|
||||
$config=Join-Path $root 'telegraf.conf'
|
||||
$exe='C:\Program Files\NDC\Mission Core\Telegraf\telegraf.exe'
|
||||
$service=Get-CimInstance Win32_Service -Filter "Name='telegraf'"
|
||||
if (-not $service -or $service.PathName -notlike '*NDC\Mission Core\Telegraf\telegraf.exe*') { throw 'Managed agent required' }
|
||||
if ($service.State -ne 'Running') { throw 'Running baseline required' }
|
||||
if ((Get-Item $config -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Regular managed configuration required' }
|
||||
$before=[IO.File]::ReadAllText($config)
|
||||
$blocks=[regex]::Matches($before,'(?ms)^\[\[outputs\.mqtt\]\].*?(?=^\[\[|\z)')
|
||||
if ($blocks.Count -ne 2) { throw 'Expected separate host and pipeline outputs' }
|
||||
$after=$before
|
||||
foreach ($block in $blocks) {
|
||||
if ($block.Value -match '(?m)^\s*layout\s*=') {
|
||||
if ($block.Value -notmatch '(?m)^\s*layout\s*=\s*"batch"\s*$') { throw 'Unexpected existing MQTT layout' }
|
||||
continue
|
||||
}
|
||||
$after=$after.Replace($block.Value, $block.Value.Replace('[[outputs.mqtt]]', "[[outputs.mqtt]]`n layout = `"batch`""))
|
||||
}
|
||||
if ($after -eq $before) { @{changed=$false;mode='batch'} | ConvertTo-Json -Compress;exit 0 }
|
||||
$baselineHash=(Get-FileHash $config -Algorithm SHA256).Hash
|
||||
$scratch=Join-Path $root ('batch-update-'+[Guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory $scratch | Out-Null
|
||||
$candidate=Join-Path $scratch 'telegraf.conf'
|
||||
$backup=Join-Path $root ('telegraf-before-batch-'+$baselineHash.Substring(0,12)+'.conf')
|
||||
$changed=$false
|
||||
try {
|
||||
foreach ($entry in (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\telegraf').Environment) {
|
||||
$name,$value=$entry -split '=',2
|
||||
if ($name) { Set-Item "Env:$name" $value }
|
||||
}
|
||||
[IO.File]::WriteAllText($candidate,$after,[Text.UTF8Encoding]::new($false))
|
||||
$probe=Start-Process $exe -ArgumentList @('--config',('"'+$candidate+'"'),'--test') -PassThru -NoNewWindow -RedirectStandardOutput (Join-Path $scratch 'out.log') -RedirectStandardError (Join-Path $scratch 'error.log')
|
||||
$probeHandle=$probe.Handle
|
||||
if (-not $probe.WaitForExit(30000)) { $probe.Kill();throw 'Agent validation timed out' }
|
||||
if ($probe.ExitCode -ne 0) { throw 'Agent configuration validation failed' }
|
||||
if ((Get-FileHash $config -Algorithm SHA256).Hash -ne $baselineHash) { throw 'Configuration changed during validation' }
|
||||
if (-not (Test-Path $backup)) { Copy-Item $config $backup }
|
||||
Stop-Service telegraf
|
||||
(Get-Service telegraf).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Stopped,[TimeSpan]::FromSeconds(20))
|
||||
$changed=$true
|
||||
Copy-Item $candidate $config -Force
|
||||
Start-Service telegraf
|
||||
(Get-Service telegraf).WaitForStatus([ServiceProcess.ServiceControllerStatus]::Running,[TimeSpan]::FromSeconds(20))
|
||||
@{changed=$true;mode='batch';backup=$backup;sha256=(Get-FileHash $config -Algorithm SHA256).Hash}|ConvertTo-Json -Compress
|
||||
} catch {
|
||||
if ($changed) {
|
||||
Stop-Service telegraf -ErrorAction SilentlyContinue
|
||||
Copy-Item $backup $config -Force
|
||||
}
|
||||
if ((Get-Service telegraf).Status -eq 'Stopped') { Start-Service telegraf }
|
||||
throw
|
||||
} finally { Remove-Item $scratch -Recurse -Force }
|
||||
@@ -29,6 +29,7 @@
|
||||
total = true
|
||||
|
||||
[[outputs.mqtt]]
|
||||
layout = "batch"
|
||||
startup_error_behavior = "retry"
|
||||
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
|
||||
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/host"
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
data_type = "string"
|
||||
|
||||
[[outputs.mqtt]]
|
||||
layout = "batch"
|
||||
startup_error_behavior = "retry"
|
||||
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
|
||||
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/host"
|
||||
@@ -91,6 +92,7 @@
|
||||
namedrop = ["missioncore_pipeline", "missioncore_pipeline_event"]
|
||||
|
||||
[[outputs.mqtt]]
|
||||
layout = "batch"
|
||||
startup_error_behavior = "retry"
|
||||
servers = ["tcp://${MISSIONCORE_MQTT_HOST}:${MISSIONCORE_MQTT_PORT}"]
|
||||
topic = "mission-core/v1/contours/${MISSIONCORE_CONTOUR_ID}/agents/${MISSIONCORE_AGENT_ID}/pipeline"
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
# Worker connections
|
||||
|
||||
Status: 2026-11-09. The existing Worker 006 uses the installed Tailscale
|
||||
connection registry and four supervised channels. The first operator LTE check showed incomplete telemetry; returning to Wi-Fi
|
||||
restored it. After the transport repair below, repeat LTE acceptance is pending. WireGuard worker provisioning and clean-machine
|
||||
enrollment are not accepted capabilities of this increment.
|
||||
|
||||
## Ownership and boundaries
|
||||
|
||||
- A network profile describes a VPN network, not a physical computer.
|
||||
- A worker has an immutable contour identity and a pinned SSH host public key.
|
||||
A prepared transport binding additionally fixes its hostname, OS, authentication
|
||||
alias and permitted channels. VPN peer identity and physical host identity are
|
||||
both checked; selecting an address does not grant trust.
|
||||
- A worker may have several connections. Adding one does not activate it.
|
||||
The operator selects an already verified connection for that worker alone.
|
||||
- Tailscale remains primary for the current worker. Its endpoint is the peer's
|
||||
stable VPN DNS name, not the operator's Wi-Fi address. HTTP and MQTT currently
|
||||
travel through authenticated SSH forwarding inside the VPN; SSH has not been
|
||||
eliminated or replaced by a newly deployed worker control service.
|
||||
- There is no automatic switching between VPN providers. Existing Tailscale
|
||||
routing/reconnection and the channel supervisors handle temporary interruption.
|
||||
- Board profiles and board power control are not changed by worker selection.
|
||||
|
||||
## Components
|
||||
|
||||
| Component | Authority |
|
||||
| --- | --- |
|
||||
| `src/k1link/compute_connections/store.py` | Atomic registry, revisions, enrollment and selection |
|
||||
| `src/k1link/compute_connections/transport.py` | Private prepared bindings, VPN validation, strict host-key checks |
|
||||
| `src/k1link/compute_connections/service.py` | Discovery, verification, admission and manual activation |
|
||||
| `src/k1link/compute_connections/link.py` | One supervised authenticated forwarding channel |
|
||||
| `src/k1link/web/compute_connection_api.py` | Loopback operator API and short-lived power confirmation |
|
||||
| `scripts/install_compute_connection_links.py` | Versioned adoption of enumerated existing LaunchAgents and rollback |
|
||||
| `apps/control-station/src/components/system/WorkerConnectionSettings.tsx` | Connection selection and prepared-worker enrollment |
|
||||
| `apps/control-station/src/components/system/SharedNetworkProfiles.tsx` | Shared profile inventory; reuses existing WireGuard import |
|
||||
| `apps/control-station/src/components/system/useWorkerPower.tsx` | Confirmed worker shutdown |
|
||||
|
||||
The existing compute-contour catalog projects admitted identity/address from the
|
||||
connection registry, retaining display-name and polling preferences. New LAB
|
||||
agent code accepts an explicit contour identity throughout claims and heartbeats;
|
||||
this does not itself deploy per-worker API credentials or additional agents.
|
||||
|
||||
## Runtime state and channel contract
|
||||
|
||||
Private state lives under `.runtime/system`:
|
||||
|
||||
- `device-connections.json`: profile references, worker identities, connections,
|
||||
active selection and revisions; no credentials.
|
||||
- `worker-bindings/<binding>.json` and `.known_hosts`: installer-owned private
|
||||
transport configuration and pinned public keys; never browser-editable.
|
||||
- `connection-status/<contour>/<channel>.json`: bounded latest status, replaced
|
||||
atomically, stale after six seconds. It is not historical telemetry.
|
||||
- `connection-migrations/<binding>/`: exact prior LaunchAgent files for rollback.
|
||||
|
||||
The adopted channels preserve existing loopback-only endpoints:
|
||||
|
||||
| Channel | Direction | Endpoints |
|
||||
| --- | --- | --- |
|
||||
| LAB jobs | Worker → Core | Worker `127.0.0.1:18080` → Core `127.0.0.1:8000` |
|
||||
| Telemetry | Worker → Core | Worker `127.0.0.1:1883` → Core `127.0.0.1:1883` |
|
||||
| Gaussian Pipeline | Core → Worker | Core `127.0.0.1:18090` → Worker `127.0.0.1:18090` |
|
||||
| LAB results | Core → Worker | Core `127.0.0.1:19087` → Worker `127.0.0.1:19087` |
|
||||
|
||||
Supervisors reread active selection and pinned identity, keep one child process,
|
||||
and reconnect forwarding only. A running indicator requires authenticated SSH
|
||||
master setup, not simply an open local port. It does not establish model/runtime
|
||||
readiness or successful transfer of a whole result. Applications retain their
|
||||
own readiness and retry semantics. Activation waits for all configured channels;
|
||||
on failure it restores the previous desired connection. Recovery of that
|
||||
previous connection remains independently observable.
|
||||
|
||||
The old telemetry installer refuses to overwrite an adopted connection. Its
|
||||
normal receiver reconciliation remains available. Other legacy planners are not
|
||||
the authority for migrated channels; use the connection installer. The LAB
|
||||
operator-link installer already refuses replacement of a different installed file.
|
||||
|
||||
## Power control
|
||||
|
||||
The local operator API verifies the worker before offering confirmation. The
|
||||
30-second nonce is bound to the worker, connection revision, selected connection
|
||||
and pinned key, and consumed before execution. A fresh check precedes one fixed
|
||||
Windows shutdown command. No durable queue or automatic resend exists. A missing
|
||||
reply is reported as uncertain, not as a proven failure to execute. Linux worker
|
||||
power control is not admitted by this implementation. Physical shutdown has not
|
||||
been performed as part of connection testing; the UI confirmation was cancelled.
|
||||
|
||||
## Installation and acceptance
|
||||
|
||||
Use the adoption script's `--plan <private-plan.json>` first, then `--apply`.
|
||||
The plan enumerates existing owned labels and exact channel specifications. It
|
||||
does not install VPN clients, distribute credentials, provision models or alter
|
||||
the board. `--rollback` with the same plan restores prior LaunchAgent files;
|
||||
registry records remain and must not be mistaken for live supervisor acceptance.
|
||||
Keep the original plan/backups private. Do not create a second Core service.
|
||||
|
||||
WireGuard profiles reuse the existing fleet profile inventory, but current VPS
|
||||
provisioning only prepares core/board roles. A worker needs an explicit worker
|
||||
peer and routing policy plus a client before that path can pass verification.
|
||||
The UI displays the provider registry and explicitly distinguishes it from a
|
||||
network scan; it does not accept a board profile as an equivalent worker. Tailscale network selection occurs in its installed
|
||||
client; this UI does not log into multiple tailnets on the operator's behalf.
|
||||
|
||||
Acceptance before declaring field readiness:
|
||||
|
||||
1. Check identity and four channels in Worker settings; observe fresh telemetry.
|
||||
2. Move the Mac to an independent LTE connection, retaining Tailscale and Worker
|
||||
power. Wait for recovery; check again without editing IPs or restarting Core.
|
||||
3. Retrieve a result that is not already cached; local playback alone cannot prove
|
||||
Worker reachability. Confirm byte integrity through the existing result path.
|
||||
4. Return to the original network and repeat the connectivity check.
|
||||
5. Separately qualify interrupted transfer/retry and sustained operation before
|
||||
promising arbitrary-network or field-workload reliability.
|
||||
|
||||
Local evidence: `outputs/worker-connections-20261109/REPORT.md`.
|
||||
|
||||
|
||||
## Telemetry batching and truthful status — 2026-11-09 follow-up
|
||||
|
||||
A settings check verifies pinned host identity and authenticated forwarding. It
|
||||
cannot establish fresh CPU/memory data or readiness of every model. The UI now
|
||||
labels these results as established connections and directs telemetry inspection
|
||||
to Modules. If the host responds only with pipeline data, the Core reports
|
||||
`telemetry-host-incomplete`; Modules/Network show a warning, not green online with
|
||||
empty hardware. Missing network interfaces produce unknown values, not invented
|
||||
zero traffic. Source timestamps and the 30-second query freshness limit remain.
|
||||
|
||||
The installed Telegraf 1.38.4 MQTT non-batch output waits for QoS 1 confirmation
|
||||
for each metric. With dozens of metrics this scales with round-trip latency.
|
||||
Host and pipeline outputs now use `layout="batch"`, grouping metrics per topic.
|
||||
The normalizer accepts both single messages and `{"metrics":[...]}` envelopes,
|
||||
validates the entire message before admission, and retains each sample's own
|
||||
series identity and timestamp. Bounds: 1 MiB/message, 1–512 metrics/batch; malformed
|
||||
or nested batches are rejected. Existing TTL, agent ACLs and memory limits remain.
|
||||
|
||||
Update the normalizer before enabling batching on an existing agent. New agent
|
||||
configurations use the Windows/Linux templates. For the managed Windows host,
|
||||
`deploy/telemetry-plane/telegraf/Enable-NdcMissionCoreTelemetryBatch.ps1` validates
|
||||
the expected node, current service/configuration and candidate Telegraf config,
|
||||
keeps a hash-addressed backup, and rolls back on failed service restart. It changes
|
||||
neither credentials nor the endpoint. Current Worker 006 receipt and backup path:
|
||||
`outputs/worker-connections-20261109/telemetry-batch-install.json`.
|
||||
For manual rollback restore that exact configuration backup and restart only
|
||||
Telegraf; the normalizer remains compatible with single messages.
|
||||
|
||||
On Worker 006 an isolated benchmark used the installed Telegraf binary, 128
|
||||
synthetic metrics and a loopback MQTT receiver delaying each PUBACK by 150 ms:
|
||||
20.106 s with 128 messages versus 0.169 s with one batch. This proves the transport
|
||||
latency defect, not the exact cause of every symptom during the earlier LTE test.
|
||||
A controlled 38-second loss of the telemetry SSH channel expired stale readings;
|
||||
resuming its supervisor restored fresh readings in 26.29 seconds. Both are bounded
|
||||
controlled tests, not a successful Wi-Fi/LTE handover or a recovery-time guarantee.
|
||||
|
||||
## Operator connection workflow and remaining gap
|
||||
|
||||
The add window follows VPN type → network → device. It lists actual provider
|
||||
peers, marks enrolled/offline devices, and explains when a visible device lacks a
|
||||
Mission Core binding. It no longer requires selection from an unexplained empty
|
||||
“prepared worker” list or displays Worker 006's identity for a new worker.
|
||||
Name matching selects a unique prepared binding only; server-side pinned key,
|
||||
physical host and VPN peer verification remain mandatory admission gates.
|
||||
|
||||
WireGuard imports use the existing NODE.DC server connection JSON, not an exported
|
||||
WireGuard `.conf` tunnel. The UI states this and explains that profile IPs identify
|
||||
VPN servers. Full enrollment of an unprepared computer is still unavailable: it
|
||||
needs agent installation, scoped credentials and trusted binding provisioning.
|
||||
Do not represent clearer selection UI as an accepted clean-host installer.
|
||||
|
||||
System navigation contains Workers and VPS catalogs. A selected worker opens
|
||||
Modules and Network. The static Integrations and Audit
|
||||
placeholder pages were removed; operational APIs and actual logs were preserved.
|
||||
|
||||
## Native VPN client handoff — 2026-11-09
|
||||
|
||||
Core detects the installed Tailscale client and reads `status --json`. On macOS
|
||||
it prefers the official application bundle's own CLI, so an independently
|
||||
installed newer client does not require replacing it with a bundled old version.
|
||||
CLI subprocesses set `TAILSCALE_BE_CLI=1`, as documented in the
|
||||
[official CLI reference](https://tailscale.com/docs/reference/tailscale-cli?tab=macos).
|
||||
Without this flag the bundle can select GUI mode in a non-interactive service;
|
||||
changing the executable's letter case alone does not resolve that condition.
|
||||
An unknown response/state remains unavailable; there is no version-number guess
|
||||
that declares an untested version compatible. Version is diagnostic metadata.
|
||||
|
||||
The connection window distinguishes missing client, login required, stopped,
|
||||
starting, pending administrator approval and connected. Missing client links to
|
||||
the official download. Login/open launches the installed native application;
|
||||
when that client has already issued an official login URL, the same action opens
|
||||
it. Core never receives passwords, switches accounts, forces logout or executes
|
||||
`tailscale up/login/switch`. Account management stays in the official app.
|
||||
The loopback-only open API accepts no executable, command or URL from the browser.
|
||||
|
||||
While settings are visible, discovery refreshes every five seconds and when
|
||||
focus returns from the VPN app. Only one request runs at a time. Hidden/closed
|
||||
windows stop polling, closing aborts the request, and checks/mutations suspend
|
||||
automatic refresh. Still-available selections survive refresh; stale peer/network
|
||||
selections are cleared after an external account change. This does not rebind an
|
||||
existing worker to a newly visible network automatically.
|
||||
|
||||
### Where the WireGuard import comes from
|
||||
|
||||
The NODE.DC VPS installer produces
|
||||
`/var/lib/ndc-wireguard-vps/mission-core-wireguard.json` on the VPN server.
|
||||
From the directory containing the deployed installer package, its administrator
|
||||
can issue a fresh invitation with:
|
||||
|
||||
```sh
|
||||
sudo python3 mission-core-wireguard-vps-0.1.1.pyz connection
|
||||
```
|
||||
|
||||
Transfer that private JSON to the operator and use the existing import action.
|
||||
The invitation expires after 24 hours; this is not an expiry of an already
|
||||
admitted connection. Keep invitation contents out of logs and normal Git.
|
||||
Source authority is the separate `NODEDC_MISSION_CORE_ARNAVI-VPS` repository:
|
||||
`wireguard_vps/state.py:State.export`, `wireguard_vps/installer.py:main` and
|
||||
`docs/WIREGUARD_FLEET_OPERATIONS.md`. A `.conf` exported from the native WireGuard
|
||||
app has a different purpose and is not this server-management invitation.
|
||||
|
||||
Current VPS enrollment accepts `core` and `node` (board), not `worker`; its
|
||||
firewall policy is also board-oriented. Therefore importing a server profile
|
||||
does not prepare Worker 006 on WireGuard. Worker peer admission and routing need
|
||||
a separate communications change, independent of the deferred LAB/Docker setup.
|
||||
No VPS profile, board tunnel or active Worker connection was changed here.
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Adopt already installed SSH links into identity-bound connection routing.
|
||||
|
||||
Default is a read-only plan. This does not install VPNs, grant credentials,
|
||||
change the board network, or provision model runtimes. Rollback retains the
|
||||
exact previous launchd files. Only enumerated existing labels may be replaced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import ConnectionStore, WorkerBinding
|
||||
from k1link.compute_connections.transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
bounded_run,
|
||||
tailscale_profile,
|
||||
tailscale_status,
|
||||
)
|
||||
|
||||
|
||||
def atomic(path: Path, data: bytes):
|
||||
temporary = path.with_suffix(".install.tmp")
|
||||
with temporary.open("xb") as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def bootstrap(domain: str, path: Path):
|
||||
# bootout is asynchronous: wait for launchd to finish retiring the old job.
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
result = subprocess.run(
|
||||
["/bin/launchctl", "bootstrap", domain, str(path)], capture_output=True, check=False
|
||||
)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("launchd did not accept the service after retirement")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--plan", type=Path, required=True)
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
parser.add_argument("--rollback", action="store_true")
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
system = root / ".runtime/system"
|
||||
plan = json.loads(args.plan.read_bytes())
|
||||
labels = plan.pop("launchd_labels")
|
||||
contour = plan["contour_id"]
|
||||
alias = plan["ssh_alias"]
|
||||
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}", alias):
|
||||
raise ValueError("Invalid installed SSH alias")
|
||||
config = bounded_run(["/usr/bin/ssh", "-G", alias]).decode().splitlines()
|
||||
values = dict(line.split(" ", 1) for line in config if " " in line)
|
||||
known_alias = values.get("hostkeyalias") or values["hostname"]
|
||||
if known_alias == "none":
|
||||
known_alias = values["hostname"]
|
||||
known_files = shlex.split(values.get("userknownhostsfile", ""))
|
||||
if len(known_files) != 1:
|
||||
raise ValueError("One explicit installed known-hosts file is required")
|
||||
known = Path(known_files[0]).expanduser()
|
||||
keys = (
|
||||
bounded_run(["/usr/bin/ssh-keygen", "-F", known_alias, "-f", str(known)])
|
||||
.decode()
|
||||
.splitlines()
|
||||
)
|
||||
keys = [
|
||||
" ".join(line.split()[1:3])
|
||||
for line in keys
|
||||
if not line.startswith("#") and " ssh-ed25519 " in line
|
||||
]
|
||||
if len(set(keys)) != 1:
|
||||
raise ValueError("Exactly one already trusted Ed25519 host key is required")
|
||||
binding = TransportBinding(**plan, host_key=keys[0])
|
||||
if set(labels) != {x.id for x in binding.channels}:
|
||||
raise ValueError("Every installed channel needs exactly one existing launchd label")
|
||||
status = tailscale_status()
|
||||
profile = tailscale_profile(status)
|
||||
peer = next(
|
||||
x
|
||||
for x in status["Peer"].values()
|
||||
if str(x.get("DNSName", "")).rstrip(".") == values["hostname"]
|
||||
)
|
||||
service = ConnectionService(system, wireguard=lambda: [], tailscale=lambda: status)
|
||||
_, connection = service.candidate(profile.id, peer["ID"])
|
||||
worker = WorkerBinding(
|
||||
contour_id=contour,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
plists = []
|
||||
for channel in binding.channels:
|
||||
label = labels[channel.id]
|
||||
if not re.fullmatch(r"com\.nodedc\.[A-Za-z0-9.-]+", label):
|
||||
raise ValueError("Only owned NODE.DC labels can be migrated")
|
||||
path = Path.home() / "Library/LaunchAgents" / (label + ".plist")
|
||||
if path.is_symlink():
|
||||
raise ValueError("Symlink service definition refused")
|
||||
original = path.read_bytes()
|
||||
document = plistlib.loads(original)
|
||||
argv = document["ProgramArguments"]
|
||||
if document["Label"] != label or "k1link.rotating_process" not in argv or "--" not in argv:
|
||||
raise ValueError("Only existing managed SSH links can be adopted")
|
||||
child = argv[argv.index("--") + 1 :]
|
||||
already = "k1link.compute_connections.link" in child
|
||||
if not already and (
|
||||
child[0] != "/usr/bin/ssh" or child[-1] != alias or channel.arguments[1] not in child
|
||||
):
|
||||
raise ValueError("Installed forward differs from the reviewed plan")
|
||||
document["ProgramArguments"] = argv[: argv.index("--") + 1] + [
|
||||
str(root / ".venv/bin/python"),
|
||||
"-m",
|
||||
"k1link.compute_connections.link",
|
||||
"--root",
|
||||
str(system),
|
||||
"--contour",
|
||||
contour,
|
||||
"--channel",
|
||||
channel.id,
|
||||
]
|
||||
plists.append((path, original, plistlib.dumps(document), label))
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
contour=contour,
|
||||
network=profile.name,
|
||||
identity=binding.fingerprint,
|
||||
channels=len(plists),
|
||||
action="rollback" if args.rollback else "apply" if args.apply else "plan",
|
||||
)
|
||||
)
|
||||
)
|
||||
if not (args.apply or args.rollback):
|
||||
return
|
||||
backup = system / "connection-migrations" / binding.id
|
||||
backup.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
transport_root = system / "worker-bindings"
|
||||
transport_root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if not args.rollback:
|
||||
target = transport_root / (binding.id + ".json")
|
||||
if target.exists() and target.read_bytes() != binding.model_dump_json(indent=2).encode():
|
||||
raise ValueError("A different installed binding exists; refusing overwrite")
|
||||
if not target.exists():
|
||||
atomic(target, binding.model_dump_json(indent=2).encode())
|
||||
trust = transport_root / (binding.id + ".known_hosts")
|
||||
content = (binding.id + " " + binding.host_key + "\n").encode()
|
||||
if trust.exists() and trust.read_bytes() != content:
|
||||
raise ValueError("Installed trust changed")
|
||||
if not trust.exists():
|
||||
atomic(trust, content)
|
||||
SshTransport(transport_root).probe(worker, connection)
|
||||
store = ConnectionStore(system)
|
||||
current = store.read()
|
||||
existing = next((x for x in current.workers if x.contour_id == contour), None)
|
||||
if existing is None:
|
||||
store.enroll(profile, worker, expected_revision=current.revision)
|
||||
elif existing.host_key_sha256 != worker.host_key_sha256:
|
||||
raise ValueError("Existing device identity differs")
|
||||
domain = f"gui/{os.getuid()}"
|
||||
changed = []
|
||||
try:
|
||||
for path, original, replacement, label in plists:
|
||||
saved = backup / path.name
|
||||
if not saved.exists():
|
||||
atomic(saved, original)
|
||||
desired = saved.read_bytes() if args.rollback else replacement
|
||||
if path.read_bytes() != original:
|
||||
raise ValueError("Service changed concurrently")
|
||||
subprocess.run(
|
||||
["/bin/launchctl", "bootout", domain + "/" + label],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
)
|
||||
atomic(path, desired)
|
||||
changed.append((path, original, label))
|
||||
bootstrap(domain, path)
|
||||
if not args.rollback:
|
||||
deadline = time.monotonic() + 35
|
||||
while time.monotonic() < deadline:
|
||||
states = service.link_states(service.store.read().worker(contour))
|
||||
if states and all(x["connected"] for x in states):
|
||||
print(json.dumps(dict(state="connected", channels=states)))
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("Link acceptance failed")
|
||||
except BaseException:
|
||||
for path, original, label in reversed(changed):
|
||||
subprocess.run(
|
||||
["/bin/launchctl", "bootout", domain + "/" + label],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
)
|
||||
atomic(path, original)
|
||||
bootstrap(domain, path)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -115,6 +115,13 @@ def private_file(path):
|
||||
|
||||
|
||||
def plan(stack: Path, ssh_alias: str, repository: Path, agents: Path):
|
||||
existing_tunnel = agents / (TUNNEL + ".plist")
|
||||
if existing_tunnel.exists():
|
||||
installed = plistlib.loads(private_file(existing_tunnel))
|
||||
if "k1link.compute_connections.link" in installed.get("ProgramArguments", []):
|
||||
raise ValueError(
|
||||
"Connection registry owns this tunnel; use install_compute_connection_links.py"
|
||||
)
|
||||
if not stack.is_absolute() or stack.resolve() != stack or not repository.is_absolute():
|
||||
raise ValueError("Canonical absolute installation paths required")
|
||||
if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]{0,80}", ssh_alias) is None:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Device identity, network attachments and verified connection selection.
|
||||
|
||||
VPN membership and application capabilities are independent. An address is
|
||||
never a device identity; changing a path never grants a new execution capability.
|
||||
"""
|
||||
@@ -0,0 +1,164 @@
|
||||
"""One installed channel, following a device's active connection.
|
||||
|
||||
Launchd/systemd owns this process. No commands are queued or retried here: only
|
||||
authenticated TCP forwarding is re-established. Every retry re-reads identity.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from .store import ConnectionError, ConnectionStore
|
||||
from .transport import SshTransport, bounded_run, validate_path
|
||||
|
||||
|
||||
def read_wireguard_profile(root: Path, network_id: str) -> dict | None:
|
||||
path = root.parent / "mission-core/fleet/networks/profiles.json"
|
||||
try:
|
||||
value = json.loads(path.read_bytes()).get(network_id)
|
||||
if isinstance(value, dict):
|
||||
# Only provider identity and public peer addresses enter this layer.
|
||||
return {key: value.get(key) for key in ("server_id", "subnet", "status")}
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def selected(store: ConnectionStore, contour_id: str):
|
||||
registry = store.read()
|
||||
worker = registry.worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == worker.active_connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Активное подключение не выбрано.")
|
||||
return worker, connection, registry.profile(connection.profile_id)
|
||||
|
||||
|
||||
def write_state(path: Path, value: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps({**value, "observed_at": time.time(), "pid": os.getpid()}))
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def stop_child(child: subprocess.Popen | None) -> None:
|
||||
if child is None or child.poll() is not None:
|
||||
return
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=4)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
child.wait(timeout=2)
|
||||
|
||||
|
||||
def run(root: Path, contour_id: str, channel_id: str, stop: Event) -> None:
|
||||
store = ConnectionStore(root)
|
||||
transport = SshTransport(root / "worker-bindings")
|
||||
path = root / "connection-status" / contour_id / f"{channel_id}.json"
|
||||
child = None
|
||||
while not stop.is_set():
|
||||
connection_id = None
|
||||
control_dir = None
|
||||
try:
|
||||
worker, connection, profile = selected(store, contour_id)
|
||||
connection_id = connection.id
|
||||
validate_path(
|
||||
profile,
|
||||
connection,
|
||||
wireguard_profile=read_wireguard_profile(root, profile.network_id),
|
||||
)
|
||||
binding = transport.binding(worker)
|
||||
channel = next(x for x in binding.channels if x.id == channel_id)
|
||||
arguments = transport.arguments(worker, connection)
|
||||
control_dir = tempfile.TemporaryDirectory(prefix="ndc-link-", dir="/tmp")
|
||||
control_path = str(Path(control_dir.name) / "control")
|
||||
child = subprocess.Popen(
|
||||
[
|
||||
arguments[0],
|
||||
"-o",
|
||||
"ControlMaster=yes",
|
||||
"-o",
|
||||
"ControlPath=" + control_path,
|
||||
*arguments[1:-1],
|
||||
"-N",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
*channel.arguments,
|
||||
arguments[-1],
|
||||
],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
started = time.monotonic()
|
||||
while not stop.wait(1):
|
||||
if child.poll() is not None:
|
||||
raise ConnectionError("Канал восстанавливается.")
|
||||
current, active, _ = selected(store, contour_id)
|
||||
if active.id != connection.id or current.host_key_sha256 != worker.host_key_sha256:
|
||||
break
|
||||
# Control master appears only after authenticated setup and forward binding.
|
||||
try:
|
||||
bounded_run(
|
||||
[
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
"/dev/null",
|
||||
"-S",
|
||||
control_path,
|
||||
"-O",
|
||||
"check",
|
||||
binding.ssh_alias,
|
||||
],
|
||||
timeout=2,
|
||||
)
|
||||
except ConnectionError:
|
||||
if time.monotonic() - started >= 15:
|
||||
raise
|
||||
write_state(path, {"connection_id": connection.id, "state": "connecting"})
|
||||
continue
|
||||
write_state(
|
||||
path,
|
||||
{
|
||||
"connection_id": connection.id,
|
||||
"state": "running",
|
||||
"uptime_seconds": round(time.monotonic() - started),
|
||||
},
|
||||
)
|
||||
except (OSError, ValueError, StopIteration):
|
||||
write_state(path, {"connection_id": connection_id, "state": "reconnecting"})
|
||||
stop.wait(3)
|
||||
finally:
|
||||
stop_child(child)
|
||||
child = None
|
||||
if control_dir is not None:
|
||||
control_dir.cleanup()
|
||||
write_state(path, {"connection_id": None, "state": "stopped"})
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--contour", required=True)
|
||||
parser.add_argument("--channel", required=True)
|
||||
args = parser.parse_args()
|
||||
stop = Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
run(args.root, args.contour, args.channel, stop)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Provider discovery, identity-bound admission and verified path selection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from .store import Connection, ConnectionError, ConnectionStore, NetworkProfile, WorkerBinding
|
||||
from .tailscale_client import ClientUnavailable, describe
|
||||
from .transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
tailscale_profile,
|
||||
tailscale_status,
|
||||
validate_path,
|
||||
)
|
||||
|
||||
|
||||
class ConnectionService:
|
||||
def __init__(
|
||||
self,
|
||||
root: Path,
|
||||
*,
|
||||
wireguard: Callable[[], list[dict]],
|
||||
tailscale: Callable[[], dict] = tailscale_status,
|
||||
transport: SshTransport | None = None,
|
||||
):
|
||||
self.store = ConnectionStore(root)
|
||||
self.transport = transport or SshTransport(root / "worker-bindings")
|
||||
self.wireguard = wireguard
|
||||
self.tailscale = tailscale
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def networks(self) -> tuple[list[NetworkProfile], dict | None, list[dict], str | None, dict]:
|
||||
profiles = []
|
||||
status = None
|
||||
message = None
|
||||
client = describe(state="unavailable")
|
||||
try:
|
||||
status = self.tailscale()
|
||||
profiles.append(tailscale_profile(status))
|
||||
client = describe(status)
|
||||
except ClientUnavailable as exc:
|
||||
message = str(exc)
|
||||
client = exc.client
|
||||
except ConnectionError as exc:
|
||||
message = str(exc)
|
||||
rows = self.wireguard()
|
||||
for row in rows:
|
||||
profiles.append(
|
||||
NetworkProfile(
|
||||
id="wg-" + hashlib.sha256(row["server_id"].encode()).hexdigest()[:24],
|
||||
name=row.get("name") or "WireGuard",
|
||||
provider="wireguard",
|
||||
network_id=row["server_id"],
|
||||
)
|
||||
)
|
||||
return profiles, status, rows, message, client
|
||||
|
||||
def catalog(self) -> dict:
|
||||
registry = self.store.read()
|
||||
profiles, status, rows, message, client = self.networks()
|
||||
peers = []
|
||||
for profile in profiles:
|
||||
if profile.provider == "tailscale" and status:
|
||||
for peer in (status.get("Peer") or {}).values():
|
||||
if peer.get("ID") and peer.get("DNSName"):
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["ID"],
|
||||
name=peer.get("HostName") or peer["DNSName"],
|
||||
online=bool(peer.get("Online")),
|
||||
)
|
||||
)
|
||||
elif profile.provider == "wireguard":
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
for peer in row.get("status", {}).get("peers", []):
|
||||
if peer.get("kind") == "worker":
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["id"],
|
||||
name=peer.get("name") or peer["id"],
|
||||
online=None,
|
||||
)
|
||||
)
|
||||
prepared = []
|
||||
for path in sorted(self.transport.root.glob("*.json")):
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
continue
|
||||
try:
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != path.stem:
|
||||
continue
|
||||
prepared.append(
|
||||
dict(
|
||||
id=binding.id,
|
||||
contour_id=binding.contour_id,
|
||||
name=binding.display_name,
|
||||
hostname=binding.expected_hostname,
|
||||
platform=binding.platform,
|
||||
)
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
known = {x.id: x for x in registry.profiles}
|
||||
known.update({x.id: x for x in profiles})
|
||||
return dict(
|
||||
revision=registry.revision,
|
||||
profiles=[x.model_dump() for x in known.values()],
|
||||
available_profile_ids=[x.id for x in profiles],
|
||||
peers=peers,
|
||||
workers=[x.model_dump() for x in registry.workers],
|
||||
prepared=prepared,
|
||||
notice=message,
|
||||
tailscale_client=client,
|
||||
)
|
||||
|
||||
def candidate(self, profile_id: str, peer_id: str) -> tuple[NetworkProfile, Connection]:
|
||||
profiles, status, rows, _, _ = self.networks()
|
||||
profile = next((x for x in profiles if x.id == profile_id), None)
|
||||
if profile is None:
|
||||
raise ConnectionError("Подключите выбранную VPN-сеть на этом компьютере.")
|
||||
row = None
|
||||
if profile.provider == "tailscale":
|
||||
peer = next(
|
||||
(x for x in (status or {}).get("Peer", {}).values() if x.get("ID") == peer_id), None
|
||||
)
|
||||
endpoint = str((peer or {}).get("DNSName", "")).rstrip(".")
|
||||
else:
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == peer_id and x.get("kind") == "worker"
|
||||
),
|
||||
None,
|
||||
)
|
||||
endpoint = (peer or {}).get("address", "")
|
||||
if not endpoint:
|
||||
raise ConnectionError("Подготовленный воркер не найден в выбранной сети.")
|
||||
connection = Connection(
|
||||
id="path-" + hashlib.sha256((profile_id + peer_id).encode()).hexdigest()[:24],
|
||||
profile_id=profile.id,
|
||||
peer_id=peer_id,
|
||||
endpoint=endpoint,
|
||||
)
|
||||
validate_path(profile, connection, status=status, wireguard_profile=row)
|
||||
return profile, connection
|
||||
|
||||
def verify(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
profile, candidate = self.candidate(connection.profile_id, connection.peer_id)
|
||||
if candidate.endpoint != connection.endpoint:
|
||||
raise ConnectionError("Адрес устройства изменился. Повторите привязку подключения.")
|
||||
return self.transport.probe(worker, connection)
|
||||
|
||||
def enroll(
|
||||
self, binding_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
# binding_id is schema-validated by the API; private files are installer-owned.
|
||||
with self.lock:
|
||||
path = self.transport.root / (binding_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Привязка устройства ещё не подготовлена.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != binding_id:
|
||||
raise ConnectionError("Некорректная привязка устройства.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
worker = WorkerBinding(
|
||||
contour_id=binding.contour_id,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
self.transport.probe(worker, connection)
|
||||
self.store.enroll(profile, worker, expected_revision=revision)
|
||||
return worker
|
||||
|
||||
def attach(
|
||||
self, contour_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
self.transport.probe(worker, connection)
|
||||
return self.store.attach(contour_id, profile, connection, expected_revision=revision)
|
||||
|
||||
def link_states(self, worker: WorkerBinding) -> list[dict]:
|
||||
binding = self.transport.binding(worker)
|
||||
states = []
|
||||
for channel in binding.channels:
|
||||
path = (
|
||||
self.store.root / "connection-status" / worker.contour_id / (channel.id + ".json")
|
||||
)
|
||||
try:
|
||||
value = json.loads(path.read_bytes())
|
||||
alive = (
|
||||
0 <= time.time() - value["observed_at"] < 6
|
||||
and value.get("connection_id") == worker.active_connection_id
|
||||
and value.get("state") == "running"
|
||||
)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
alive = False
|
||||
states.append(dict(id=channel.id, label=channel.label, connected=alive))
|
||||
return states
|
||||
|
||||
def check(self, contour_id: str, connection_id: str) -> dict:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
identity = self.verify(worker, connection)
|
||||
return dict(
|
||||
identity=identity,
|
||||
channels=self.link_states(worker),
|
||||
active=worker.active_connection_id == connection_id,
|
||||
)
|
||||
|
||||
def activate(self, contour_id: str, connection_id: str, revision: int) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
self.verify(worker, connection)
|
||||
if worker.active_connection_id == connection_id:
|
||||
return worker
|
||||
channels = self.transport.binding(worker).channels
|
||||
if not channels:
|
||||
raise ConnectionError("Рабочие каналы ещё не установлены на этом компьютере.")
|
||||
# Supervisors follow one atomic selection; all paths retain the same host key.
|
||||
updated = self.store.select(contour_id, connection_id, expected_revision=revision)
|
||||
deadline = time.monotonic() + 18
|
||||
while time.monotonic() < deadline:
|
||||
states = self.link_states(updated)
|
||||
if states and all(x["connected"] for x in states):
|
||||
return updated
|
||||
time.sleep(0.4)
|
||||
if worker.active_connection_id is not None:
|
||||
self.store.select(
|
||||
contour_id, worker.active_connection_id, expected_revision=updated.revision
|
||||
)
|
||||
raise ConnectionError(
|
||||
"Рабочие каналы не восстановились. Возвращено прежнее подключение."
|
||||
)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Atomic operator-owned registry. No credentials or observed health on disk."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
ID = r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$"
|
||||
|
||||
|
||||
class ConnectionError(ValueError):
|
||||
"""A bounded product failure; never substitute an empty registry."""
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
|
||||
class NetworkProfile(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
provider: Literal["tailscale", "wireguard"]
|
||||
# Provider identity, not an account password or a bootstrap credential.
|
||||
network_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
|
||||
class Connection(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
profile_id: str = Field(pattern=ID)
|
||||
endpoint: str = Field(min_length=1, max_length=253)
|
||||
# Different network paths of one host must all prove this same host key.
|
||||
peer_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
@field_validator("endpoint")
|
||||
@classmethod
|
||||
def safe_endpoint(cls, value: str) -> str:
|
||||
if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9.:-]{0,252}", value) is None:
|
||||
raise ValueError("Invalid connection endpoint")
|
||||
return value
|
||||
|
||||
|
||||
class WorkerBinding(Record):
|
||||
contour_id: str = Field(pattern=ID)
|
||||
host_key_sha256: str = Field(pattern=r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||
# Owned transport binding, resolved server-side; never executable user input.
|
||||
transport_id: str = Field(pattern=ID)
|
||||
connections: tuple[Connection, ...] = ()
|
||||
active_connection_id: str | None = None
|
||||
revision: int = Field(default=0, ge=0)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_connections(self) -> WorkerBinding:
|
||||
ids = [x.id for x in self.connections]
|
||||
profiles = [x.profile_id for x in self.connections]
|
||||
if len(set(ids)) != len(ids) or len(set(profiles)) != len(profiles):
|
||||
raise ValueError("Duplicate device connection")
|
||||
if self.active_connection_id is not None and self.active_connection_id not in ids:
|
||||
raise ValueError("Active connection is not attached")
|
||||
return self
|
||||
|
||||
|
||||
class Registry(Record):
|
||||
schema_version: Literal["missioncore.device-connections/v1"] = (
|
||||
"missioncore.device-connections/v1"
|
||||
)
|
||||
revision: int = Field(default=0, ge=0)
|
||||
profiles: tuple[NetworkProfile, ...] = ()
|
||||
workers: tuple[WorkerBinding, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def references(self) -> Registry:
|
||||
profiles = {x.id for x in self.profiles}
|
||||
if len(profiles) != len(self.profiles):
|
||||
raise ValueError("Duplicate network profile")
|
||||
if len({x.contour_id for x in self.workers}) != len(self.workers):
|
||||
raise ValueError("Duplicate worker binding")
|
||||
for worker in self.workers:
|
||||
if any(x.profile_id not in profiles for x in worker.connections):
|
||||
raise ValueError("Connection references a missing network profile")
|
||||
return self
|
||||
|
||||
def worker(self, contour_id: str) -> WorkerBinding:
|
||||
for worker in self.workers:
|
||||
if worker.contour_id == contour_id:
|
||||
return worker
|
||||
raise ConnectionError("Воркер ещё не привязан. Подключите подготовленное устройство.")
|
||||
|
||||
def profile(self, profile_id: str) -> NetworkProfile:
|
||||
for profile in self.profiles:
|
||||
if profile.id == profile_id:
|
||||
return profile
|
||||
raise ConnectionError("Сетевой профиль отсутствует.")
|
||||
|
||||
|
||||
class ConnectionStore:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
self.path = root / "device-connections.json"
|
||||
|
||||
@contextmanager
|
||||
def locked(self):
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
lock = self.root / "device-connections.lock"
|
||||
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
|
||||
def read(self) -> Registry:
|
||||
if self.path.is_symlink():
|
||||
raise ConnectionError("Хранилище подключений требует проверки.")
|
||||
try:
|
||||
return Registry.model_validate_json(self.path.read_bytes())
|
||||
except FileNotFoundError:
|
||||
return Registry()
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось прочитать подключения. Сохранённые данные не изменены."
|
||||
) from exc
|
||||
|
||||
def _write(self, registry: Registry) -> Registry:
|
||||
Registry.model_validate(registry.model_dump())
|
||||
fd, name = tempfile.mkstemp(prefix=".device-connections-", dir=self.root)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
stream.write(registry.model_dump_json(indent=2))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(name, self.path)
|
||||
directory = os.open(self.root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
return registry
|
||||
|
||||
def enroll(
|
||||
self, profile: NetworkProfile, binding: WorkerBinding, *, expected_revision: int
|
||||
) -> Registry:
|
||||
"""Caller must first verify the transport and obtain operator enrollment."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
if current.revision != expected_revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
for existing in current.workers:
|
||||
if existing.contour_id == binding.contour_id:
|
||||
raise ConnectionError("Воркер уже привязан; повторная регистрация запрещена.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
return self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=(*current.workers, binding),
|
||||
)
|
||||
)
|
||||
|
||||
def attach(
|
||||
self,
|
||||
contour_id: str,
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
expected_revision: int,
|
||||
) -> WorkerBinding:
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection.profile_id != profile.id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"connections": [*worker.connections, connection],
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
def select(
|
||||
self, contour_id: str, connection_id: str, *, expected_revision: int
|
||||
) -> WorkerBinding:
|
||||
"""Called only after a successful path transaction; never implies health."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection_id not in {x.id for x in worker.connections}:
|
||||
raise ConnectionError("Подключение не подготовлено на этом устройстве.")
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"active_connection_id": connection_id,
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=current.profiles,
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Observe the operator's official client; authentication stays with Tailscale."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .store import ConnectionError
|
||||
|
||||
APP_IDS = {"io.tailscale.ipn.macsys", "io.tailscale.ipn.macos"}
|
||||
MESSAGES = {
|
||||
"not_installed": "Tailscale не установлен на этом компьютере.",
|
||||
"unavailable": (
|
||||
"Tailscale установлен, но не отвечает. Откройте приложение и проверьте подключение."
|
||||
),
|
||||
"needs_login": (
|
||||
"Войдите в Tailscale. После подключения сеть и устройства появятся здесь автоматически."
|
||||
),
|
||||
"stopped": "Tailscale отключён. Включите подключение в приложении.",
|
||||
"needs_approval": (
|
||||
"Доступ этого компьютера ожидает подтверждения администратора сети Tailscale."
|
||||
),
|
||||
"starting": "Tailscale запускается. Список обновится автоматически.",
|
||||
"connected": "",
|
||||
}
|
||||
|
||||
|
||||
def installed_client(
|
||||
*, app_dirs: tuple[Path, ...] | None = None
|
||||
) -> tuple[Path | None, str | None, str | None]:
|
||||
"""Prefer the installed app's own CLI; no install, downgrade or second daemon."""
|
||||
app = None
|
||||
version = None
|
||||
if sys.platform == "darwin":
|
||||
for directory in app_dirs or (Path("/Applications"), Path.home() / "Applications"):
|
||||
candidate = directory / "Tailscale.app"
|
||||
try:
|
||||
info = plistlib.loads((candidate / "Contents/Info.plist").read_bytes())
|
||||
if info.get("CFBundleIdentifier") not in APP_IDS:
|
||||
continue
|
||||
app = candidate
|
||||
value = info.get("CFBundleShortVersionString")
|
||||
version = value[:80] if isinstance(value, str) else None
|
||||
break
|
||||
except (OSError, ValueError, plistlib.InvalidFileException):
|
||||
continue
|
||||
candidates = ([app / "Contents/MacOS/Tailscale"] if app else []) + [
|
||||
Path("/usr/local/bin/tailscale"),
|
||||
Path("/opt/homebrew/bin/tailscale"),
|
||||
]
|
||||
found = shutil.which("tailscale")
|
||||
if found:
|
||||
candidates.append(Path(found))
|
||||
binary = next((str(p) for p in candidates if p.is_file() and os.access(p, os.X_OK)), None)
|
||||
return app, binary, version
|
||||
|
||||
|
||||
def run(args: list[str], *, cli: bool = False) -> bytes:
|
||||
# Official Tailscale CLI contract: force CLI mode in non-interactive hosts.
|
||||
# Do not propagate it to the explicit native-app /usr/bin/open action.
|
||||
env = {**os.environ, "TAILSCALE_BE_CLI": "1"} if cli else None
|
||||
result = subprocess.run(args, capture_output=True, timeout=4, check=False, env=env)
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ValueError("Client command failed")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def describe(
|
||||
status: dict[str, Any] | None = None, *, state: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
app, _, version = installed_client()
|
||||
states = {
|
||||
"Running": "connected",
|
||||
"NeedsLogin": "needs_login",
|
||||
"Stopped": "stopped",
|
||||
"NeedsMachineAuth": "needs_approval",
|
||||
"Starting": "starting",
|
||||
"NoState": "starting",
|
||||
}
|
||||
backend = (status or {}).get("BackendState")
|
||||
state = state or (
|
||||
states.get(backend, "unavailable") if isinstance(backend, str) else "unavailable"
|
||||
)
|
||||
daemon_version = (status or {}).get("Version")
|
||||
return dict(
|
||||
state=state,
|
||||
message=MESSAGES[state],
|
||||
can_open=app is not None,
|
||||
version=version or (daemon_version[:80] if isinstance(daemon_version, str) else None),
|
||||
)
|
||||
|
||||
|
||||
def observe() -> tuple[dict[str, Any], dict[str, Any] | None]:
|
||||
app, binary, _ = installed_client()
|
||||
if binary is None:
|
||||
return describe(state="unavailable" if app else "not_installed"), None
|
||||
try:
|
||||
status = json.loads(run([binary, "status", "--json"], cli=True))
|
||||
if not isinstance(status, dict):
|
||||
raise ValueError("Invalid client response")
|
||||
return describe(status), status
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||
return describe(state="unavailable"), None
|
||||
|
||||
|
||||
class ClientUnavailable(ConnectionError):
|
||||
def __init__(self, client: dict[str, Any]):
|
||||
super().__init__(client["message"])
|
||||
self.client = client
|
||||
|
||||
|
||||
def running_status() -> dict[str, Any]:
|
||||
client, status = observe()
|
||||
if client["state"] != "connected" or status is None:
|
||||
raise ClientUnavailable(client)
|
||||
return status
|
||||
|
||||
|
||||
def open_client() -> dict[str, str]:
|
||||
app, _, _ = installed_client()
|
||||
if app is None:
|
||||
raise ConnectionError("Приложение Tailscale не найдено на этом компьютере.")
|
||||
try:
|
||||
# Reopening an existing app does not switch accounts, reset routes or force login.
|
||||
run(["/usr/bin/open", "-a", str(app)])
|
||||
client, status = observe()
|
||||
if client["state"] == "needs_login":
|
||||
url = (status or {}).get("AuthURL")
|
||||
parsed = urlsplit(url) if isinstance(url, str) and len(url) <= 2048 else None
|
||||
if (
|
||||
isinstance(url, str)
|
||||
and parsed
|
||||
and parsed.scheme == "https"
|
||||
and parsed.netloc == "login.tailscale.com"
|
||||
and parsed.path.startswith("/a/")
|
||||
and not parsed.fragment
|
||||
):
|
||||
run(["/usr/bin/open", url])
|
||||
return dict(state="opened")
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось открыть Tailscale. Запустите его из списка приложений."
|
||||
) from exc
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Existing SSH transport behind enrolled identities and provider-owned paths.
|
||||
|
||||
SSH is an explicit migration adapter, not a VPN provider. Credentials and host
|
||||
trust belong to the installed binding. UI requests cannot supply commands,
|
||||
users, private keys or arbitrary destination addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from .store import ID, Connection, ConnectionError, NetworkProfile, Record, WorkerBinding
|
||||
from .tailscale_client import running_status
|
||||
|
||||
|
||||
class Channel(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
direction: Literal["local", "remote"]
|
||||
listen_port: int = Field(ge=1, le=65535)
|
||||
target_port: int = Field(ge=1, le=65535)
|
||||
|
||||
@property
|
||||
def arguments(self) -> list[str]:
|
||||
return [
|
||||
"-L" if self.direction == "local" else "-R",
|
||||
f"127.0.0.1:{self.listen_port}:127.0.0.1:{self.target_port}",
|
||||
]
|
||||
|
||||
|
||||
class TransportBinding(Record):
|
||||
schema_version: Literal["missioncore.worker-ssh-binding/v1"] = (
|
||||
"missioncore.worker-ssh-binding/v1"
|
||||
)
|
||||
id: str = Field(pattern=ID)
|
||||
contour_id: str = Field(pattern=ID)
|
||||
display_name: str = Field(min_length=1, max_length=80)
|
||||
expected_hostname: str = Field(min_length=1, max_length=128)
|
||||
ssh_alias: str = Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$")
|
||||
platform: Literal["windows", "linux"]
|
||||
host_key: str = Field(min_length=20, max_length=4096)
|
||||
ssh_port: int = Field(default=22, ge=1, le=65535)
|
||||
channels: tuple[Channel, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_channels(self) -> TransportBinding:
|
||||
if len({x.id for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate channel")
|
||||
if len({(x.direction, x.listen_port) for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate listener")
|
||||
return self
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
try:
|
||||
algorithm, encoded = self.host_key.split()
|
||||
if algorithm != "ssh-ed25519":
|
||||
raise ValueError
|
||||
key = base64.b64decode(encoded, validate=True)
|
||||
# SSH wire blob: string algorithm + string 32-byte key.
|
||||
if len(key) != 51 or key[:19] != b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20":
|
||||
raise ValueError
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ConnectionError("Повреждён ключ привязки воркера.") from exc
|
||||
return "SHA256:" + base64.b64encode(hashlib.sha256(key).digest()).decode().rstrip("=")
|
||||
|
||||
|
||||
def bounded_run(args: list[str], *, data: bytes | None = None, timeout: float = 8) -> bytes:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
input=data,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise ConnectionError("Устройство недоступно. Проверьте сетевое подключение.") from exc
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ConnectionError("Подключение не подтверждено. Сохранённый профиль не изменён.")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def tailscale_status() -> dict:
|
||||
return running_status()
|
||||
|
||||
|
||||
def tailscale_profile(status: dict) -> NetworkProfile:
|
||||
network = status.get("CurrentTailnet", {}).get("MagicDNSSuffix")
|
||||
if not isinstance(network, str) or not network.endswith(".ts.net"):
|
||||
raise ConnectionError("Tailscale не подтвердил идентичность сети.")
|
||||
return NetworkProfile(
|
||||
id="ts-" + hashlib.sha256(network.encode()).hexdigest()[:24],
|
||||
name="Tailscale · " + network,
|
||||
provider="tailscale",
|
||||
network_id=network,
|
||||
)
|
||||
|
||||
|
||||
def validate_path(
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
status: dict | None = None,
|
||||
wireguard_profile: dict | None = None,
|
||||
) -> None:
|
||||
if profile.id != connection.profile_id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
if profile.provider == "tailscale":
|
||||
status = tailscale_status() if status is None else status
|
||||
if tailscale_profile(status).network_id != profile.network_id:
|
||||
raise ConnectionError("На этом компьютере выбрана другая сеть Tailscale.")
|
||||
peers = status.get("Peer") or {}
|
||||
peer = next((x for x in peers.values() if x.get("ID") == connection.peer_id), None)
|
||||
if not peer or not peer.get("Online"):
|
||||
raise ConnectionError("Устройство недоступно в выбранной сети Tailscale.")
|
||||
names = {str(peer.get("DNSName", "")).rstrip("."), *peer.get("TailscaleIPs", [])}
|
||||
if connection.endpoint not in names:
|
||||
raise ConnectionError("Адрес больше не принадлежит привязанному устройству.")
|
||||
else:
|
||||
row = wireguard_profile
|
||||
if not row or row.get("server_id") != profile.network_id:
|
||||
raise ConnectionError("Профиль WireGuard не найден.")
|
||||
try:
|
||||
network = ipaddress.ip_network(row["subnet"])
|
||||
if ipaddress.ip_address(connection.endpoint) not in network:
|
||||
raise ValueError
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == connection.peer_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not peer or peer.get("address") != connection.endpoint:
|
||||
raise ValueError
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Устройство ещё не зарегистрировано в этом WireGuard-профиле."
|
||||
) from exc
|
||||
|
||||
|
||||
WINDOWS_IDENTITY = (
|
||||
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; "
|
||||
"$ErrorActionPreference='Stop'; "
|
||||
"@{hostname=$env:COMPUTERNAME;platform='windows'} | ConvertTo-Json -Compress"
|
||||
)
|
||||
LINUX_IDENTITY = (
|
||||
"python3 -c 'import json,socket; "
|
||||
'print(json.dumps(dict(hostname=socket.gethostname(),platform="linux")))\''
|
||||
)
|
||||
|
||||
|
||||
class SshTransport:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
|
||||
def binding(self, worker: WorkerBinding) -> TransportBinding:
|
||||
path = self.root / (worker.transport_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Права привязки воркера требуют проверки.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if (
|
||||
binding.id != worker.transport_id
|
||||
or binding.contour_id != worker.contour_id
|
||||
or binding.fingerprint != worker.host_key_sha256
|
||||
):
|
||||
raise ConnectionError("Идентичность воркера изменилась. Переключение запрещено.")
|
||||
return binding
|
||||
|
||||
def arguments(self, worker: WorkerBinding, connection: Connection) -> list[str]:
|
||||
binding = self.binding(worker)
|
||||
known = self.root / (binding.id + ".known_hosts")
|
||||
expected = (binding.id + " " + binding.host_key + "\n").encode()
|
||||
if known.is_symlink() or known.read_bytes() != expected:
|
||||
raise ConnectionError("Ключ подключения не совпал с привязкой воркера.")
|
||||
return [
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
str(Path.home() / ".ssh/config"),
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=yes",
|
||||
"-o",
|
||||
"UserKnownHostsFile=" + str(known),
|
||||
"-o",
|
||||
"GlobalKnownHostsFile=/dev/null",
|
||||
"-o",
|
||||
"HostKeyAlias=" + binding.id,
|
||||
"-o",
|
||||
"HostKeyAlgorithms=ssh-ed25519",
|
||||
"-o",
|
||||
"UpdateHostKeys=no",
|
||||
"-o",
|
||||
"ForwardAgent=no",
|
||||
"-o",
|
||||
"PermitLocalCommand=no",
|
||||
"-o",
|
||||
"ControlMaster=no",
|
||||
"-o",
|
||||
"ControlPath=none",
|
||||
"-o",
|
||||
"RequestTTY=no",
|
||||
"-o",
|
||||
"ProxyCommand=none",
|
||||
"-o",
|
||||
"ProxyJump=none",
|
||||
"-o",
|
||||
"ConnectTimeout=8",
|
||||
"-o",
|
||||
"ServerAliveInterval=10",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"HostName=" + connection.endpoint,
|
||||
"-p",
|
||||
str(binding.ssh_port),
|
||||
binding.ssh_alias,
|
||||
]
|
||||
|
||||
def execute(self, worker: WorkerBinding, connection: Connection, command: str) -> bytes:
|
||||
# Commands are constants owned by this adapter, never request fields.
|
||||
binding = self.binding(worker)
|
||||
if binding.platform == "windows":
|
||||
command = (
|
||||
"powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "
|
||||
+ base64.b64encode(command.encode("utf-16le")).decode()
|
||||
)
|
||||
return bounded_run(
|
||||
[
|
||||
*self.arguments(worker, connection)[:-1],
|
||||
"-o",
|
||||
"ClearAllForwardings=yes",
|
||||
binding.ssh_alias,
|
||||
command,
|
||||
],
|
||||
timeout=12,
|
||||
)
|
||||
|
||||
def probe(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
binding = self.binding(worker)
|
||||
command = WINDOWS_IDENTITY if binding.platform == "windows" else LINUX_IDENTITY
|
||||
try:
|
||||
value = json.loads(self.execute(worker, connection, command))
|
||||
if (
|
||||
value.get("platform") != binding.platform
|
||||
or value.get("hostname", "").casefold() != binding.expected_hostname.casefold()
|
||||
):
|
||||
raise ValueError
|
||||
except (ValueError, OSError) as exc:
|
||||
raise ConnectionError("Устройство не подтвердило свою конфигурацию.") from exc
|
||||
return {
|
||||
"hostname": value["hostname"],
|
||||
"platform": value["platform"],
|
||||
"host_key_sha256": binding.fingerprint,
|
||||
}
|
||||
@@ -391,7 +391,7 @@ class _ValidatedClaim:
|
||||
|
||||
|
||||
class ObservatoryWorkerAgent:
|
||||
"""Runs at most one sealed recorded-job claim at a time on Worker 006."""
|
||||
"""Runs one sealed job at a time under the enrolled Worker identity."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -401,6 +401,7 @@ class ObservatoryWorkerAgent:
|
||||
claim_request_id_factory: Callable[[], str] | None = None,
|
||||
heartbeat_interval_seconds: float | None = None,
|
||||
heartbeat_stop_timeout_seconds: float = 5.0,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
) -> None:
|
||||
if heartbeat_interval_seconds is not None and not (
|
||||
0.01 <= heartbeat_interval_seconds <= 300.0
|
||||
@@ -408,9 +409,12 @@ class ObservatoryWorkerAgent:
|
||||
raise ValueError("Worker heartbeat interval is invalid")
|
||||
if not 0.1 <= heartbeat_stop_timeout_seconds <= 300.0:
|
||||
raise ValueError("Worker heartbeat stop timeout is invalid")
|
||||
self._contour_id = validate_worker_contour_id(contour_id)
|
||||
self._transport = transport
|
||||
self._executors = executors
|
||||
self._claim_request_id_factory = claim_request_id_factory or _default_claim_request_id
|
||||
self._claim_request_id_factory = claim_request_id_factory or (
|
||||
lambda: _default_claim_request_id(self._contour_id)
|
||||
)
|
||||
self._heartbeat_interval_seconds = heartbeat_interval_seconds
|
||||
self._heartbeat_stop_timeout_seconds = heartbeat_stop_timeout_seconds
|
||||
self._cycle_lock = threading.Lock()
|
||||
@@ -419,7 +423,7 @@ class ObservatoryWorkerAgent:
|
||||
"""Claim, validate, execute, and seal one durable job if available."""
|
||||
|
||||
if not self._cycle_lock.acquire(blocking=False):
|
||||
raise ObservatoryWorkerAgentBusyError("Worker 006 already owns an active claim cycle")
|
||||
raise ObservatoryWorkerAgentBusyError("Worker already owns an active claim cycle")
|
||||
try:
|
||||
return self._run_once_locked()
|
||||
finally:
|
||||
@@ -430,7 +434,7 @@ class ObservatoryWorkerAgent:
|
||||
if _CLAIM_REQUEST_ID.fullmatch(claim_request_id) is None:
|
||||
raise ValueError("Worker claim request id is invalid")
|
||||
payload = self._transport.claim_next(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
claim_request_id=claim_request_id,
|
||||
supported_executor_identities=self._executors.supported_identities,
|
||||
)
|
||||
@@ -442,6 +446,7 @@ class ObservatoryWorkerAgent:
|
||||
try:
|
||||
claim = _validate_claim(
|
||||
payload,
|
||||
contour_id=self._contour_id,
|
||||
claim_request_id=claim_request_id,
|
||||
supported_executor_identities=self._executors.supported_identities,
|
||||
)
|
||||
@@ -457,11 +462,11 @@ class ObservatoryWorkerAgent:
|
||||
except ObservatoryWorkerExecutorUnavailableError:
|
||||
failure_code = "executor-not-allowlisted"
|
||||
acknowledgement = self._transport.fail(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
error_code=failure_code,
|
||||
message="Exact executor identity is not installed on Worker 006.",
|
||||
message="Exact executor identity is not installed on this Worker.",
|
||||
)
|
||||
_validate_transition_acknowledgement(
|
||||
acknowledgement,
|
||||
@@ -476,7 +481,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
|
||||
started_payload = self._transport.start(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
)
|
||||
@@ -495,6 +500,7 @@ class ObservatoryWorkerAgent:
|
||||
active_job = _seal_job(started)
|
||||
heartbeat = _ClaimHeartbeat(
|
||||
transport=self._transport,
|
||||
contour_id=self._contour_id,
|
||||
job=active_job,
|
||||
claim_token=claim.claim_token,
|
||||
interval_seconds=(
|
||||
@@ -544,7 +550,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
failure_code = "executor-error"
|
||||
acknowledgement = self._transport.fail(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
error_code=failure_code,
|
||||
@@ -572,7 +578,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
|
||||
acknowledgement = self._transport.succeed(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
result_id=result.result_id,
|
||||
@@ -614,9 +620,11 @@ class _ClaimHeartbeat:
|
||||
interval_seconds: float,
|
||||
stop_timeout_seconds: float,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
) -> None:
|
||||
if interval_seconds <= 0:
|
||||
raise ValueError("Worker heartbeat interval must be positive")
|
||||
self._contour_id = validate_worker_contour_id(contour_id)
|
||||
self._transport = transport
|
||||
self._job = job
|
||||
self._claim_token = claim_token
|
||||
@@ -671,7 +679,7 @@ class _ClaimHeartbeat:
|
||||
"Worker heartbeat lease budget expired"
|
||||
)
|
||||
acknowledgement = self._transport.renew_claim(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=self._job.job_id,
|
||||
claim_token=self._claim_token,
|
||||
claim_generation=self._job.claim_generation,
|
||||
@@ -756,19 +764,20 @@ def _validate_claim(
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
claim_request_id: str,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
supported_executor_identities: tuple[ObservatoryWorkerExecutorIdentity, ...],
|
||||
) -> _ValidatedClaim:
|
||||
try:
|
||||
claim = _RecordedClaimPayload.model_validate(dict(payload))
|
||||
if claim.claim_request_id != claim_request_id:
|
||||
raise ObservatoryWorkerClaimRejectedError("Worker claim request identity changed")
|
||||
if claim.claimant_id != WORKER_006_CONTOUR_ID:
|
||||
if claim.claimant_id != contour_id:
|
||||
raise ObservatoryWorkerClaimRejectedError("Worker claim belongs to another claimant")
|
||||
expected_claim_request_sha256 = _sha256_document(
|
||||
{
|
||||
"schema_version": OBSERVATORY_RECORDED_CLAIM_SCHEMA,
|
||||
"claim_request_id": claim_request_id,
|
||||
"claimant_id": WORKER_006_CONTOUR_ID,
|
||||
"claimant_id": contour_id,
|
||||
"supported_executor_identities": [
|
||||
identity.as_dict() for identity in sorted(supported_executor_identities)
|
||||
],
|
||||
@@ -963,8 +972,17 @@ def _validate_transition_acknowledgement(
|
||||
return acknowledgement
|
||||
|
||||
|
||||
def _default_claim_request_id() -> str:
|
||||
return f"worker-006:{uuid4().hex}"
|
||||
def validate_worker_contour_id(value: str) -> str:
|
||||
if (
|
||||
not isinstance(value, str)
|
||||
or re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?", value) is None
|
||||
):
|
||||
raise ValueError("Worker contour identity is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _default_claim_request_id(contour_id: str = WORKER_006_CONTOUR_ID) -> str:
|
||||
return f"{contour_id}:{uuid4().hex}"
|
||||
|
||||
|
||||
def _default_heartbeat_interval(job: SealedObservatoryRecordedJob) -> float:
|
||||
|
||||
@@ -59,6 +59,7 @@ from k1link.observatory.worker_agent import (
|
||||
ObservatoryWorkerTransientTransportError,
|
||||
ObservatoryWorkerTransport,
|
||||
SealedObservatoryRecordedJob,
|
||||
validate_worker_contour_id,
|
||||
)
|
||||
from k1link.observatory.worker_source_cache import WorkerSourceCache, WorkerSourceCacheError
|
||||
|
||||
@@ -177,8 +178,7 @@ class ObservatoryWorkerHttpGateway(ObservatoryWorkerTransport):
|
||||
self._base_url = _validated_base_url(base_url)
|
||||
if _TOKEN.fullmatch(bearer_token) is None:
|
||||
raise ValueError("Worker bearer credential format is invalid")
|
||||
if contour_id != WORKER_006_CONTOUR_ID:
|
||||
raise ValueError("portable Worker gateway is pinned to Worker 006")
|
||||
self.contour_id = validate_worker_contour_id(contour_id)
|
||||
if not 1 <= timeout_seconds <= 300:
|
||||
raise ValueError("Worker HTTP timeout is invalid")
|
||||
self._headers = {
|
||||
@@ -865,9 +865,8 @@ class ObservatoryWorkerHttpGateway(ObservatoryWorkerTransport):
|
||||
_CLAIM_GENERATION_HEADER: str(context.claim_generation),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _require_claimant(claimant_id: str) -> None:
|
||||
if claimant_id != WORKER_006_CONTOUR_ID:
|
||||
def _require_claimant(self, claimant_id: str) -> None:
|
||||
if claimant_id != self.contour_id:
|
||||
raise ObservatoryWorkerHttpError("Worker claimant identity changed")
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -142,8 +142,12 @@ class ObservatoryWorkerServiceConfiguration:
|
||||
transport_backoff_seconds: float = DEFAULT_OBSERVATORY_WORKER_TRANSPORT_BACKOFF_SECONDS
|
||||
max_consecutive_transport_failures: int = DEFAULT_OBSERVATORY_WORKER_MAX_TRANSPORT_FAILURES
|
||||
source_cache_root: Path | None = None
|
||||
contour_id: str = "worker-006"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
from k1link.observatory.worker_agent import validate_worker_contour_id
|
||||
|
||||
validate_worker_contour_id(self.contour_id)
|
||||
_validate_worker_base_url(self.base_url)
|
||||
_absolute_path(self.bearer_token_file, "Worker bearer token file")
|
||||
_absolute_path(self.work_root, "Worker work root")
|
||||
@@ -177,6 +181,7 @@ class ObservatoryWorkerServiceConfiguration:
|
||||
OBSERVATORY_WORKER_BASE_URL_ENV,
|
||||
DEFAULT_OBSERVATORY_WORKER_BASE_URL,
|
||||
),
|
||||
contour_id=values.get("MISSIONCORE_CONTOUR_ID", "worker-006"),
|
||||
bearer_token_file=token_file,
|
||||
work_root=work_root,
|
||||
source_cache_root=(
|
||||
@@ -271,6 +276,7 @@ def compose_installed_observatory_worker_service(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -283,7 +289,9 @@ def compose_installed_observatory_worker_service(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -309,6 +317,7 @@ def compose_installed_observatory_worker_service_from_builders(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -325,7 +334,9 @@ def compose_installed_observatory_worker_service_from_builders(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
if gateway is not None:
|
||||
@@ -351,6 +362,7 @@ def compose_installed_observatory_worker_service_from_packages(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -368,7 +380,9 @@ def compose_installed_observatory_worker_service_from_packages(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
if gateway is not None:
|
||||
|
||||
@@ -106,6 +106,7 @@ from k1link.simulation.projects import SimulationProjectService, SimulationProje
|
||||
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
||||
from k1link.web.artifact_health_api import build_artifact_health_router
|
||||
from k1link.web.compute_contour_api import build_compute_contour_router
|
||||
from k1link.web.compute_connection_api import build_compute_connection_router
|
||||
from k1link.web.device_plugin_composition import load_installed_device_plugins
|
||||
from k1link.web.environment_api import build_environment_router
|
||||
from k1link.web.equipment_firmware_api import router as equipment_firmware_router
|
||||
@@ -1156,6 +1157,9 @@ app.include_router(
|
||||
)
|
||||
)
|
||||
app.include_router(build_simulation_world_provider_router())
|
||||
app.include_router(build_compute_connection_router(
|
||||
root_provider=lambda: REPOSITORY_ROOT / ".runtime" / "system",
|
||||
))
|
||||
app.include_router(
|
||||
build_simulation_projects_router(
|
||||
store=simulation_project_store,
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Local operator API. Never accepts credentials, shell commands or arbitrary IPs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import Field
|
||||
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import ID, ConnectionError, Record
|
||||
from k1link.compute_connections.tailscale_client import open_client
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
|
||||
class Attach(Record):
|
||||
profile_id: str = Field(pattern=ID)
|
||||
peer_id: str = Field(min_length=1, max_length=180)
|
||||
revision: int = Field(ge=0)
|
||||
|
||||
|
||||
class Enroll(Attach):
|
||||
binding_id: str = Field(pattern=ID)
|
||||
|
||||
|
||||
class SelectConnection(Record):
|
||||
connection_id: str = Field(pattern=ID)
|
||||
revision: int = Field(ge=0)
|
||||
|
||||
|
||||
class Shutdown(Record):
|
||||
confirmation: str = Field(min_length=43, max_length=43)
|
||||
|
||||
|
||||
def build_compute_connection_router(root_provider: Callable[[], Path]) -> APIRouter:
|
||||
router = APIRouter(prefix="/api/v1/system/connections", tags=["compute-connections"])
|
||||
holder: list[ConnectionService] = []
|
||||
confirmations: dict[str, tuple] = {}
|
||||
initialization = threading.Lock()
|
||||
|
||||
operator_dependency = Depends(local_operator)
|
||||
|
||||
def service(fleet=operator_dependency) -> ConnectionService:
|
||||
with initialization:
|
||||
if not holder:
|
||||
|
||||
def profiles():
|
||||
with fleet.network_profiles.lock:
|
||||
return [
|
||||
{key: row.get(key) for key in ("server_id", "name", "subnet", "status")}
|
||||
for row in fleet.network_profiles.profiles.values()
|
||||
]
|
||||
|
||||
holder.append(ConnectionService(root_provider(), wireguard=profiles))
|
||||
return holder[0]
|
||||
|
||||
def operation(function, *args):
|
||||
try:
|
||||
return function(*args)
|
||||
except ConnectionError as exc:
|
||||
raise HTTPException(409, str(exc)) from None
|
||||
except (OSError, ValueError, KeyError):
|
||||
raise HTTPException(
|
||||
409, "Не удалось подтвердить подключение. Сохранённая привязка защищена."
|
||||
) from None
|
||||
|
||||
service_dependency = Depends(service)
|
||||
|
||||
@router.get("")
|
||||
def catalog(manager=service_dependency):
|
||||
return operation(manager.catalog)
|
||||
|
||||
@router.post("/tailscale/open", dependencies=[operator_dependency])
|
||||
def open_tailscale():
|
||||
return operation(open_client)
|
||||
|
||||
@router.post("/enroll")
|
||||
def enroll(body: Enroll, manager=service_dependency):
|
||||
worker = operation(
|
||||
manager.enroll, body.binding_id, body.profile_id, body.peer_id, body.revision
|
||||
)
|
||||
return worker
|
||||
|
||||
@router.post("/{contour_id}/attach")
|
||||
def attach(contour_id: str, body: Attach, manager=service_dependency):
|
||||
return operation(manager.attach, contour_id, body.profile_id, body.peer_id, body.revision)
|
||||
|
||||
@router.post("/{contour_id}/activate")
|
||||
def activate(contour_id: str, body: SelectConnection, manager=service_dependency):
|
||||
return operation(manager.activate, contour_id, body.connection_id, body.revision)
|
||||
|
||||
@router.get("/{contour_id}/status")
|
||||
def status(contour_id: str, manager=service_dependency):
|
||||
worker = operation(lambda: manager.store.read().worker(contour_id))
|
||||
return dict(channels=operation(manager.link_states, worker))
|
||||
|
||||
@router.post("/{contour_id}/check")
|
||||
def check(contour_id: str, body: SelectConnection, manager=service_dependency):
|
||||
return operation(manager.check, contour_id, body.connection_id)
|
||||
|
||||
@router.post("/{contour_id}/power/prepare")
|
||||
def prepare_shutdown(contour_id: str, manager=service_dependency):
|
||||
with manager.lock:
|
||||
worker = operation(lambda: manager.store.read().worker(contour_id))
|
||||
binding = manager.transport.binding(worker)
|
||||
if binding.platform != "windows":
|
||||
raise HTTPException(
|
||||
409, "Управление питанием ещё не подготовлено для этого устройства."
|
||||
)
|
||||
operation(manager.check, contour_id, worker.active_connection_id)
|
||||
now = time.monotonic()
|
||||
for key, value in list(confirmations.items()):
|
||||
if now - value[0] > 30 or value[1] == contour_id:
|
||||
confirmations.pop(key, None)
|
||||
token = secrets.token_urlsafe(32)
|
||||
confirmations[token] = (
|
||||
now,
|
||||
worker.contour_id,
|
||||
worker.revision,
|
||||
worker.active_connection_id,
|
||||
worker.host_key_sha256,
|
||||
)
|
||||
return dict(confirmation=token, expires_in_seconds=30)
|
||||
|
||||
@router.post("/{contour_id}/power/shutdown")
|
||||
def shutdown(contour_id: str, body: Shutdown, manager=service_dependency):
|
||||
with manager.lock:
|
||||
confirmation = confirmations.pop(body.confirmation, None)
|
||||
worker = operation(lambda: manager.store.read().worker(contour_id))
|
||||
identity = (
|
||||
worker.contour_id,
|
||||
worker.revision,
|
||||
worker.active_connection_id,
|
||||
worker.host_key_sha256,
|
||||
)
|
||||
if (
|
||||
not confirmation
|
||||
or time.monotonic() - confirmation[0] > 30
|
||||
or confirmation[1:] != identity
|
||||
):
|
||||
raise HTTPException(
|
||||
409,
|
||||
"Подтверждение истекло или подключение изменилось. "
|
||||
"Проверьте устройство ещё раз.",
|
||||
)
|
||||
connection = next(x for x in worker.connections if x.id == worker.active_connection_id)
|
||||
operation(manager.verify, worker, connection)
|
||||
if time.monotonic() - confirmation[0] > 30:
|
||||
raise HTTPException(409, "Подтверждение истекло. Повторите проверку.")
|
||||
# Single attempt, no durable queue and no retry after disconnect.
|
||||
command = (
|
||||
"$ErrorActionPreference='Stop'; & shutdown.exe /s /t 5; "
|
||||
"if ($LASTEXITCODE -ne 0) {exit 1}; Write-Output 'accepted'"
|
||||
)
|
||||
try:
|
||||
result = manager.transport.execute(worker, connection, command)
|
||||
except ConnectionError:
|
||||
raise HTTPException(
|
||||
409,
|
||||
"Ответ не получен. Команда могла дойти; "
|
||||
"повторно автоматически не отправляется.",
|
||||
) from None
|
||||
if result.strip() != b"accepted":
|
||||
raise HTTPException(
|
||||
409, "Воркер не подтвердил команду. Повторная отправка не выполняется."
|
||||
)
|
||||
return dict(
|
||||
state="accepted",
|
||||
message=(
|
||||
"Воркер принял команду выключения. "
|
||||
"Для включения потребуется доступ к компьютеру."
|
||||
),
|
||||
)
|
||||
|
||||
return router
|
||||
@@ -197,7 +197,32 @@ class ComputeContourStore:
|
||||
|
||||
def list_contours(self) -> list[ComputeContour]:
|
||||
with self._lock:
|
||||
return self._read_unlocked()
|
||||
return self._with_connections(self._read_unlocked())
|
||||
|
||||
def _with_connections(self, contours: list[ComputeContour]) -> list[ComputeContour]:
|
||||
"""Project enrolled identities; the connection registry owns routing."""
|
||||
from k1link.compute_connections.store import ConnectionStore
|
||||
from k1link.compute_connections.transport import SshTransport
|
||||
|
||||
registry = ConnectionStore(self.root).read()
|
||||
transport = SshTransport(self.root / "worker-bindings")
|
||||
rows = {item.contour_id: item for item in contours}
|
||||
for worker in registry.workers:
|
||||
binding = transport.binding(worker)
|
||||
connection = next(
|
||||
(x for x in worker.connections if x.id == worker.active_connection_id), None
|
||||
)
|
||||
prior = rows.get(worker.contour_id)
|
||||
fields = prior.model_dump() if prior else {
|
||||
"contour_id": worker.contour_id, "agent_id": worker.contour_id,
|
||||
"display_name": binding.display_name,
|
||||
}
|
||||
rows[worker.contour_id] = ComputeContour.model_validate({
|
||||
**fields, "expected_node_id": binding.expected_hostname,
|
||||
"platform": binding.platform, "ssh_port": binding.ssh_port,
|
||||
"address": connection.endpoint if connection else "",
|
||||
})
|
||||
return list(rows.values())
|
||||
|
||||
def create(self, request: ComputeContourCreate) -> ComputeContour:
|
||||
with self._lock:
|
||||
@@ -230,7 +255,7 @@ class ComputeContourStore:
|
||||
|
||||
def update(self, contour_id: str, request: ComputeContourPut) -> ComputeContour:
|
||||
with self._lock:
|
||||
contours = self._read_unlocked()
|
||||
contours = self._with_connections(self._read_unlocked())
|
||||
for index, current in enumerate(contours):
|
||||
if current.contour_id != contour_id:
|
||||
continue
|
||||
|
||||
@@ -1105,6 +1105,13 @@ class WorkerTelemetryService:
|
||||
memory = _mapping(raw.get("memory"))
|
||||
memory_total = _number(memory.get("total_bytes"))
|
||||
memory_free = _number(memory.get("free_bytes"))
|
||||
if (
|
||||
_number(_mapping(raw.get("cpu")).get("load_percent")) is None
|
||||
or memory_total is None
|
||||
or memory_free is None
|
||||
):
|
||||
# A pipeline heartbeat proves identity, not current host telemetry.
|
||||
public_probe["error_code"] = "telemetry-host-incomplete"
|
||||
memory_used = (
|
||||
memory_total - memory_free
|
||||
if memory_total is not None and memory_free is not None
|
||||
@@ -1137,7 +1144,11 @@ class WorkerTelemetryService:
|
||||
raw_observed_at if isinstance(raw_observed_at, str) else _utc_now()
|
||||
)
|
||||
receive_rate, send_rate = self._latest_network_rates
|
||||
if observed_at != self._last_history_observed_at:
|
||||
if not interfaces:
|
||||
self._previous_network = None
|
||||
self._latest_network_rates = (None, None)
|
||||
receive_rate, send_rate = None, None
|
||||
elif observed_at != self._last_history_observed_at:
|
||||
receive_rate = None
|
||||
send_rate = None
|
||||
if self._previous_network is not None:
|
||||
@@ -1196,7 +1207,7 @@ class WorkerTelemetryService:
|
||||
"sent_bytes": sent,
|
||||
"receive_bytes_per_second": receive_rate,
|
||||
"send_bytes_per_second": send_rate,
|
||||
},
|
||||
} if interfaces else None,
|
||||
}
|
||||
history_row = {
|
||||
"observed_at_utc": observed_at,
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
from threading import RLock
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import k1link.web.compute_connection_api as api
|
||||
from k1link.compute_connections.store import Connection, NetworkProfile, Registry, WorkerBinding
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def operator(tmp_path, monkeypatch):
|
||||
profile = NetworkProfile(
|
||||
id="network-one", name="Test", provider="tailscale", network_id="test.ts.net"
|
||||
)
|
||||
path = Connection(
|
||||
id="path-one", profile_id=profile.id, endpoint="worker.test.ts.net", peer_id="peer-one"
|
||||
)
|
||||
worker = WorkerBinding(
|
||||
contour_id="worker-seven",
|
||||
transport_id="worker-key",
|
||||
host_key_sha256="SHA256:" + "x" * 43,
|
||||
connections=(path,),
|
||||
active_connection_id=path.id,
|
||||
)
|
||||
registry = Registry(profiles=(profile,), workers=(worker,))
|
||||
manager = SimpleNamespace(
|
||||
lock=RLock(),
|
||||
store=SimpleNamespace(read=Mock(return_value=registry)),
|
||||
transport=SimpleNamespace(
|
||||
binding=Mock(return_value=SimpleNamespace(platform="windows")),
|
||||
execute=Mock(return_value=b"accepted\r\n"),
|
||||
),
|
||||
check=Mock(return_value={}),
|
||||
verify=Mock(return_value={}),
|
||||
catalog=Mock(return_value={}),
|
||||
)
|
||||
monkeypatch.setattr(api, "ConnectionService", lambda *_a, **_kw: manager)
|
||||
clock = [100.0]
|
||||
monkeypatch.setattr(api.time, "monotonic", lambda: clock[0])
|
||||
app = FastAPI()
|
||||
app.include_router(api.build_compute_connection_router(lambda: tmp_path))
|
||||
app.dependency_overrides[local_operator] = lambda: SimpleNamespace()
|
||||
with TestClient(app) as client:
|
||||
yield client, manager, worker, registry, clock, app
|
||||
|
||||
|
||||
def prepare(client):
|
||||
response = client.post("/api/v1/system/connections/worker-seven/power/prepare", json={})
|
||||
assert response.status_code == 200
|
||||
return response.json()["confirmation"]
|
||||
|
||||
|
||||
def test_shutdown_is_single_attempt(operator):
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
request = dict(confirmation=token)
|
||||
url = "/api/v1/system/connections/worker-seven/power/shutdown"
|
||||
assert client.post(url, json=request).json()["state"] == "accepted"
|
||||
assert client.post(url, json=request).status_code == 409
|
||||
manager.transport.execute.assert_called_once()
|
||||
|
||||
|
||||
def test_shutdown_expired_confirmation_never_executes(operator):
|
||||
client, manager, _, _, clock, _ = operator
|
||||
token = prepare(client)
|
||||
clock[0] += 31
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_rebinding_invalidates_confirmation(operator):
|
||||
client, manager, worker, registry, *_ = operator
|
||||
token = prepare(client)
|
||||
manager.store.read.return_value = registry.model_copy(
|
||||
update={"workers": (worker.model_copy(update={"revision": 1}),)}
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_wrong_worker_is_rejected(operator):
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/worker-other/power/shutdown", json=dict(confirmation=token)
|
||||
).status_code
|
||||
== 409
|
||||
)
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_uncertain_shutdown_has_no_retry(operator):
|
||||
from k1link.compute_connections.store import ConnectionError
|
||||
|
||||
client, manager, *_ = operator
|
||||
token = prepare(client)
|
||||
manager.transport.execute.side_effect = ConnectionError("Lost response")
|
||||
for _ in range(2):
|
||||
response = client.post(
|
||||
"/api/v1/system/connections/worker-seven/power/shutdown", json=dict(confirmation=token)
|
||||
)
|
||||
assert response.status_code == 409
|
||||
manager.transport.execute.assert_called_once()
|
||||
|
||||
|
||||
def test_worker_api_rejects_foreign_origin_and_non_loopback(operator):
|
||||
_, manager, _, _, _, app = operator
|
||||
app.dependency_overrides.clear()
|
||||
app.state.fleet = SimpleNamespace()
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 3000)) as client:
|
||||
assert (
|
||||
client.get(
|
||||
"/api/v1/system/connections", headers={"Origin": "https://foreign.test"}
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert client.get("/api/v1/system/connections").status_code == 200
|
||||
with TestClient(app, base_url="http://localhost", client=("10.1.2.3", 3000)) as client:
|
||||
assert client.get("/api/v1/system/connections").status_code == 403
|
||||
manager.transport.execute.assert_not_called()
|
||||
|
||||
|
||||
def test_open_client_requires_local_operator_and_is_never_called_by_catalog(operator, monkeypatch):
|
||||
_, _, _, _, _, app = operator
|
||||
opened = Mock(return_value={"state": "opened"})
|
||||
monkeypatch.setattr(api, "open_client", opened)
|
||||
app.dependency_overrides.clear()
|
||||
app.state.fleet = SimpleNamespace()
|
||||
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 3000)) as client:
|
||||
assert client.get("/api/v1/system/connections").status_code == 200
|
||||
opened.assert_not_called()
|
||||
assert (
|
||||
client.post(
|
||||
"/api/v1/system/connections/tailscale/open",
|
||||
json={},
|
||||
headers={"Origin": "https://foreign.test"},
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
opened.assert_not_called()
|
||||
assert client.post("/api/v1/system/connections/tailscale/open", json={}).json() == {
|
||||
"state": "opened"
|
||||
}
|
||||
opened.assert_called_once()
|
||||
@@ -0,0 +1,187 @@
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import (
|
||||
Connection,
|
||||
ConnectionError,
|
||||
ConnectionStore,
|
||||
NetworkProfile,
|
||||
WorkerBinding,
|
||||
)
|
||||
from k1link.compute_connections.transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
tailscale_profile,
|
||||
validate_path,
|
||||
)
|
||||
|
||||
KEY = (
|
||||
"ssh-ed25519 "
|
||||
+ base64.b64encode(b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20" + b"x" * 32).decode()
|
||||
)
|
||||
STATUS = dict(
|
||||
BackendState="Running",
|
||||
CurrentTailnet=dict(MagicDNSSuffix="test.ts.net"),
|
||||
Peer={"pk": dict(ID="peer-one", DNSName="worker.test.ts.net.", HostName="WORKER", Online=True)},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
profile = tailscale_profile(STATUS)
|
||||
connection = Connection(
|
||||
id="path-one", profile_id=profile.id, endpoint="worker.test.ts.net", peer_id="peer-one"
|
||||
)
|
||||
binding = TransportBinding(
|
||||
id="trusted-worker",
|
||||
contour_id="worker-seven",
|
||||
display_name="Worker seven",
|
||||
expected_hostname="WORKER",
|
||||
platform="windows",
|
||||
ssh_alias="prepared-worker",
|
||||
host_key=KEY,
|
||||
)
|
||||
worker = WorkerBinding(
|
||||
contour_id=binding.contour_id,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
root = tmp_path / "worker-bindings"
|
||||
root.mkdir(mode=0o700)
|
||||
private = root / (binding.id + ".json")
|
||||
private.write_text(binding.model_dump_json())
|
||||
private.chmod(0o600)
|
||||
(root / (binding.id + ".known_hosts")).write_text(binding.id + " " + KEY + "\n")
|
||||
return profile, connection, binding, worker
|
||||
|
||||
|
||||
def test_registry_rejects_corruption_and_stale_mutation(tmp_path, setup):
|
||||
profile, connection, _, worker = setup
|
||||
store = ConnectionStore(tmp_path)
|
||||
store.enroll(profile, worker, expected_revision=0)
|
||||
with pytest.raises(ConnectionError, match="изменились"):
|
||||
store.enroll(profile, worker, expected_revision=0)
|
||||
before = store.path.read_bytes()
|
||||
with pytest.raises(ConnectionError, match="не подготовлено"):
|
||||
store.select(worker.contour_id, "unknown", expected_revision=0)
|
||||
assert store.path.read_bytes() == before
|
||||
store.path.write_text("{broken")
|
||||
with pytest.raises(ConnectionError, match="прочитать"):
|
||||
store.read()
|
||||
assert store.path.read_text() == "{broken"
|
||||
|
||||
|
||||
def test_tailscale_requires_same_network_and_peer_address(setup):
|
||||
profile, connection, _, _ = setup
|
||||
validate_path(profile, connection, status=STATUS)
|
||||
for status in [
|
||||
dict(STATUS, CurrentTailnet=dict(MagicDNSSuffix="other.ts.net")),
|
||||
dict(STATUS, Peer={}),
|
||||
dict(STATUS, Peer={"pk": dict(STATUS["Peer"]["pk"], Online=False)}),
|
||||
]:
|
||||
with pytest.raises(ConnectionError):
|
||||
validate_path(profile, connection, status=status)
|
||||
wrong = connection.model_copy(update={"endpoint": "unrelated.test.ts.net"})
|
||||
with pytest.raises(ConnectionError, match="не принадлежит"):
|
||||
validate_path(profile, wrong, status=STATUS)
|
||||
|
||||
|
||||
def test_binding_pins_key_and_endpoint_without_shell_interpolation(tmp_path, setup):
|
||||
_, connection, binding, worker = setup
|
||||
transport = SshTransport(tmp_path / "worker-bindings")
|
||||
args = transport.arguments(worker, connection)
|
||||
assert "HostName=worker.test.ts.net" in args
|
||||
assert "StrictHostKeyChecking=yes" in args
|
||||
assert "HostKeyAlias=trusted-worker" in args
|
||||
assert args[-1] == "prepared-worker"
|
||||
path = transport.root / (binding.id + ".known_hosts")
|
||||
path.write_text("other-key\n")
|
||||
with pytest.raises(ConnectionError, match="Ключ"):
|
||||
transport.arguments(worker, connection)
|
||||
|
||||
|
||||
def test_attach_does_not_activate_or_touch_other_worker(tmp_path, setup, monkeypatch):
|
||||
profile, connection, _, worker = setup
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [], tailscale=lambda: STATUS)
|
||||
manager.store.enroll(profile, worker, expected_revision=0)
|
||||
other = worker.model_copy(update={"contour_id": "worker-eight"})
|
||||
manager.store.enroll(profile, other, expected_revision=1)
|
||||
reserve = NetworkProfile(
|
||||
id="wg-reserve", name="Reserve", provider="wireguard", network_id="server-two"
|
||||
)
|
||||
path = Connection(
|
||||
id="path-two", profile_id=reserve.id, endpoint="10.203.1.3", peer_id="worker-seven"
|
||||
)
|
||||
monkeypatch.setattr(manager, "candidate", lambda *_: (reserve, path))
|
||||
monkeypatch.setattr(manager.transport, "probe", lambda *_: {})
|
||||
updated = manager.attach(worker.contour_id, reserve.id, path.peer_id, 0)
|
||||
assert updated.active_connection_id == connection.id
|
||||
assert len(updated.connections) == 2
|
||||
assert manager.store.read().worker(other.contour_id) == other
|
||||
|
||||
|
||||
def test_failed_identity_never_attaches_or_switches(tmp_path, setup, monkeypatch):
|
||||
profile, _, _, worker = setup
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [], tailscale=lambda: STATUS)
|
||||
manager.store.enroll(profile, worker, expected_revision=0)
|
||||
before = manager.store.path.read_bytes()
|
||||
|
||||
def mismatch(*_):
|
||||
raise ConnectionError("Identity mismatch")
|
||||
|
||||
monkeypatch.setattr(manager.transport, "probe", mismatch)
|
||||
with pytest.raises(ConnectionError, match="mismatch"):
|
||||
manager.attach(worker.contour_id, profile.id, "peer-one", 0)
|
||||
assert manager.store.path.read_bytes() == before
|
||||
|
||||
|
||||
def test_catalog_never_discloses_provider_credentials(tmp_path, setup):
|
||||
manager = ConnectionService(
|
||||
tmp_path,
|
||||
wireguard=lambda: [
|
||||
dict(
|
||||
server_id="wg_one",
|
||||
name="VPS",
|
||||
subnet="10.203.1.0/24",
|
||||
status={"peers": []},
|
||||
token="DO-NOT-RETURN",
|
||||
)
|
||||
],
|
||||
tailscale=lambda: STATUS,
|
||||
)
|
||||
catalog = json.dumps(manager.catalog())
|
||||
assert "DO-NOT-RETURN" not in catalog
|
||||
assert "host_key" not in catalog
|
||||
assert "prepared-worker" not in catalog
|
||||
assert "Worker seven" in catalog
|
||||
|
||||
|
||||
def test_wireguard_does_not_admit_board_as_worker(tmp_path, setup):
|
||||
manager = ConnectionService(
|
||||
tmp_path,
|
||||
wireguard=lambda: [
|
||||
dict(
|
||||
server_id="wg_one",
|
||||
name="VPS",
|
||||
subnet="10.203.1.0/24",
|
||||
status={"peers": [dict(id="board", kind="node", address="10.203.1.3")]},
|
||||
)
|
||||
],
|
||||
tailscale=lambda: STATUS,
|
||||
)
|
||||
profile = next(x for x in manager.catalog()["profiles"] if x["provider"] == "wireguard")
|
||||
with pytest.raises(ConnectionError, match="воркер не найден"):
|
||||
manager.candidate(profile["id"], "board")
|
||||
|
||||
|
||||
def test_private_binding_permission_enforced(tmp_path, setup):
|
||||
_, _, binding, worker = setup
|
||||
transport = SshTransport(tmp_path / "worker-bindings")
|
||||
(transport.root / (binding.id + ".json")).chmod(0o644)
|
||||
with pytest.raises(ConnectionError, match="Права"):
|
||||
transport.binding(worker)
|
||||
@@ -108,6 +108,7 @@ class FakeTransport:
|
||||
failures: list[tuple[str, str, str]] = field(default_factory=list)
|
||||
renewals: list[int] = field(default_factory=list)
|
||||
renewed: Event | None = None
|
||||
contour_id: str = WORKER_006_CONTOUR_ID
|
||||
|
||||
def claim_next(
|
||||
self,
|
||||
@@ -133,7 +134,7 @@ class FakeTransport:
|
||||
job_id: str,
|
||||
claim_token: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.starts.append(job_id)
|
||||
return self.queue.start(job_id, claim_token=claim_token).as_dict()
|
||||
|
||||
@@ -146,7 +147,7 @@ class FakeTransport:
|
||||
claim_generation: int,
|
||||
heartbeat_sequence: int,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
renewed = self.queue.renew_claim(
|
||||
job_id,
|
||||
claim_token=claim_token,
|
||||
@@ -167,7 +168,7 @@ class FakeTransport:
|
||||
result_id: str,
|
||||
result_sha256: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.successes.append((job_id, result_id, result_sha256))
|
||||
return self.queue.succeed(
|
||||
job_id,
|
||||
@@ -185,7 +186,7 @@ class FakeTransport:
|
||||
error_code: str,
|
||||
message: str,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
self.failures.append((job_id, error_code, message))
|
||||
return self.queue.fail(
|
||||
job_id,
|
||||
@@ -347,7 +348,7 @@ class FailingRenewTransport(FakeTransport):
|
||||
claim_generation: int,
|
||||
heartbeat_sequence: int,
|
||||
) -> Mapping[str, object]:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
assert job_id
|
||||
assert claim_token
|
||||
assert claim_generation == 1
|
||||
@@ -515,6 +516,7 @@ def test_executor_error_is_reported_as_bounded_failure(tmp_path: Path) -> None:
|
||||
class BlockingEmptyTransport:
|
||||
entered: Event
|
||||
release: Event
|
||||
contour_id: str = "worker-006"
|
||||
|
||||
def claim_next(
|
||||
self,
|
||||
@@ -523,7 +525,7 @@ class BlockingEmptyTransport:
|
||||
claim_request_id: str,
|
||||
supported_executor_identities: tuple[ObservatoryWorkerExecutorIdentity, ...],
|
||||
) -> Mapping[str, object] | None:
|
||||
assert claimant_id == WORKER_006_CONTOUR_ID
|
||||
assert claimant_id == self.contour_id
|
||||
assert claim_request_id == "worker-006:overlap-test"
|
||||
assert supported_executor_identities == ()
|
||||
self.entered.set()
|
||||
@@ -594,3 +596,41 @@ def test_worker_agent_allows_only_one_claim_cycle_at_a_time() -> None:
|
||||
|
||||
assert not first.is_alive()
|
||||
assert len(reports) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("contour_id", ["worker-007", "field-compute-20"])
|
||||
def test_enrolled_worker_executes_without_006_identity(tmp_path: Path, contour_id: str) -> None:
|
||||
queue = _queue(tmp_path)
|
||||
job_id = _enqueue(queue)
|
||||
transport = FakeTransport(queue, contour_id=contour_id)
|
||||
executor = FakeExecutor()
|
||||
agent = ObservatoryWorkerAgent(
|
||||
transport=transport,
|
||||
executors=ObservatoryWorkerExecutorRegistry((
|
||||
ObservatoryWorkerExecutorRegistration(identity=_identity(), adapter=executor),
|
||||
)),
|
||||
contour_id=contour_id,
|
||||
)
|
||||
report = agent.run_once()
|
||||
assert report.state == "succeeded"
|
||||
assert report.job_id == job_id
|
||||
assert report.claim_request_id.startswith(contour_id + ":")
|
||||
assert transport.starts == [job_id]
|
||||
|
||||
|
||||
def test_enrolled_worker_rejects_a_different_claimant(tmp_path: Path) -> None:
|
||||
queue = _queue(tmp_path)
|
||||
_enqueue(queue)
|
||||
def substitute(payload):
|
||||
return {**payload, "claimant_id": "worker-006"}
|
||||
transport = FakeTransport(queue, contour_id="worker-007", claim_mutator=substitute)
|
||||
executor = FakeExecutor()
|
||||
agent = ObservatoryWorkerAgent(
|
||||
transport=transport,
|
||||
executors=ObservatoryWorkerExecutorRegistry((
|
||||
ObservatoryWorkerExecutorRegistration(identity=_identity(), adapter=executor),
|
||||
)),
|
||||
contour_id="worker-007",
|
||||
)
|
||||
assert agent.run_once().state == "rejected"
|
||||
assert not executor.jobs
|
||||
|
||||
@@ -36,6 +36,17 @@ def _endpoint(router: APIRouter, path: str, method: str) -> Callable[..., Any]:
|
||||
raise AssertionError(f"{method} {path} route is missing")
|
||||
|
||||
|
||||
def test_pipeline_only_snapshot_does_not_claim_host_metrics_or_zero_network(tmp_path):
|
||||
service = WorkerTelemetryService(WorkerProfileStore(tmp_path))
|
||||
probe = _probe()
|
||||
probe["raw"] = {"node_id": EXPECTED_NODE_ID, "observed_at_utc": "2026-07-27T12:00:00Z"}
|
||||
snapshot = service._telemetry_document(service.store.read(), probe, 1.0)
|
||||
assert snapshot["connection"]["reachable"] is True
|
||||
assert snapshot["connection"]["error_code"] == "telemetry-host-incomplete"
|
||||
assert snapshot["network"]["aggregate"] is None
|
||||
assert snapshot["node"]["memory"]["used_percent"] is None
|
||||
|
||||
|
||||
def _probe(
|
||||
*,
|
||||
node_id: str = EXPECTED_NODE_ID,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import json
|
||||
import plistlib
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.compute_connections import tailscale_client as client
|
||||
from k1link.compute_connections.service import ConnectionService
|
||||
from k1link.compute_connections.store import ConnectionError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installed(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
client,
|
||||
"installed_client",
|
||||
lambda: (Path("/Applications/Tailscale.app"), "/client", "1.102.3"),
|
||||
)
|
||||
command = Mock(
|
||||
return_value=b'{"BackendState":"Running","CurrentTailnet":{"MagicDNSSuffix":"one.ts.net"}}'
|
||||
)
|
||||
monkeypatch.setattr(client, "run", command)
|
||||
return command
|
||||
|
||||
|
||||
def test_bundled_cli_discovery_without_path_integration(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(client.sys, "platform", "darwin")
|
||||
app = tmp_path / "Tailscale.app"
|
||||
executable = app / "Contents/MacOS/Tailscale"
|
||||
executable.parent.mkdir(parents=True)
|
||||
executable.write_bytes(b"synthetic executable; never run")
|
||||
executable.chmod(0o700)
|
||||
(app / "Contents/Info.plist").write_bytes(
|
||||
plistlib.dumps(
|
||||
{
|
||||
"CFBundleIdentifier": "io.tailscale.ipn.macsys",
|
||||
"CFBundleShortVersionString": "9.99.1",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert client.installed_client(app_dirs=(tmp_path,)) == (app, str(executable), "9.99.1")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"backend,state",
|
||||
[
|
||||
("Running", "connected"),
|
||||
("NeedsLogin", "needs_login"),
|
||||
("Stopped", "stopped"),
|
||||
("NeedsMachineAuth", "needs_approval"),
|
||||
("Starting", "starting"),
|
||||
("UnknownFutureState", "unavailable"),
|
||||
],
|
||||
)
|
||||
def test_client_states_and_no_automatic_mutations(installed, backend, state):
|
||||
installed.return_value = json.dumps(
|
||||
{"BackendState": backend, "AuthURL": "PRIVATE-LOGIN"}
|
||||
).encode()
|
||||
summary, _ = client.observe()
|
||||
assert summary["state"] == state
|
||||
assert "PRIVATE-LOGIN" not in json.dumps(summary)
|
||||
installed.assert_called_once_with(["/client", "status", "--json"], cli=True)
|
||||
|
||||
|
||||
def test_noninteractive_cli_mode_is_explicit_and_does_not_replace_parent_environment(monkeypatch):
|
||||
process = Mock(return_value=subprocess.CompletedProcess([], 0, b"{}", b""))
|
||||
monkeypatch.setattr(client.subprocess, "run", process)
|
||||
monkeypatch.delenv("TAILSCALE_BE_CLI", raising=False)
|
||||
monkeypatch.setenv("TEST_EXISTING_ENV", "preserve")
|
||||
client.run(["/client", "status", "--json"], cli=True)
|
||||
env = process.call_args.kwargs["env"]
|
||||
assert env["TAILSCALE_BE_CLI"] == "1"
|
||||
assert env["TEST_EXISTING_ENV"] == "preserve"
|
||||
assert "TAILSCALE_BE_CLI" not in client.os.environ
|
||||
client.run(["/usr/bin/open", "-a", "/Applications/Tailscale.app"])
|
||||
assert process.call_args.kwargs["env"] is None
|
||||
|
||||
|
||||
def test_missing_client_is_not_logged_out(monkeypatch):
|
||||
monkeypatch.setattr(client, "installed_client", lambda: (None, None, None))
|
||||
command = Mock()
|
||||
monkeypatch.setattr(client, "run", command)
|
||||
summary, status = client.observe()
|
||||
assert summary["state"] == "not_installed" and not summary["can_open"] and status is None
|
||||
command.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response", [b"not JSON", b"[]", subprocess.TimeoutExpired("client", 4)])
|
||||
def test_failed_probe_is_bounded_and_unavailable(installed, response):
|
||||
if isinstance(response, Exception):
|
||||
installed.side_effect = response
|
||||
else:
|
||||
installed.return_value = response
|
||||
assert client.observe()[0]["state"] == "unavailable"
|
||||
|
||||
|
||||
def test_reopen_running_client_never_logs_out_or_switches(installed):
|
||||
assert client.open_client() == {"state": "opened"}
|
||||
assert [c.args[0] for c in installed.call_args_list] == [
|
||||
["/usr/bin/open", "-a", "/Applications/Tailscale.app"],
|
||||
["/client", "status", "--json"],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url,opened",
|
||||
[
|
||||
("https://login.tailscale.com/a/synthetic", True),
|
||||
("https://foreign.test/a/synthetic", False),
|
||||
("https://login.tailscale.com@foreign.test/a/synthetic", False),
|
||||
("file:///tmp/untrusted", False),
|
||||
],
|
||||
)
|
||||
def test_auth_reuses_only_official_client_login_url(installed, url, opened):
|
||||
installed.return_value = json.dumps({"BackendState": "NeedsLogin", "AuthURL": url}).encode()
|
||||
client.open_client()
|
||||
assert (["/usr/bin/open", url] in [c.args[0] for c in installed.call_args_list]) is opened
|
||||
|
||||
|
||||
def test_catalog_refresh_new_peer_and_account_change_without_store_mutation(tmp_path, installed):
|
||||
manager = ConnectionService(tmp_path, wireguard=lambda: [])
|
||||
first = manager.catalog()
|
||||
assert first["peers"] == [] and first["tailscale_client"]["state"] == "connected"
|
||||
installed.return_value = json.dumps(
|
||||
{
|
||||
"BackendState": "Running",
|
||||
"CurrentTailnet": {"MagicDNSSuffix": "one.ts.net"},
|
||||
"Peer": {"key": {"ID": "one", "DNSName": "worker.one.ts.net.", "Online": True}},
|
||||
}
|
||||
).encode()
|
||||
assert len(manager.catalog()["peers"]) == 1
|
||||
installed.return_value = (
|
||||
b'{"BackendState":"Running","CurrentTailnet":{"MagicDNSSuffix":"two.ts.net"}}'
|
||||
)
|
||||
assert manager.catalog()["available_profile_ids"] != first["available_profile_ids"]
|
||||
assert manager.catalog()["workers"] == []
|
||||
installed.return_value = b'{"BackendState":"NeedsLogin"}'
|
||||
logged_out = manager.catalog()
|
||||
assert logged_out["peers"] == [] and logged_out["available_profile_ids"] == []
|
||||
assert logged_out["tailscale_client"]["state"] == "needs_login"
|
||||
with pytest.raises(ConnectionError):
|
||||
client.running_status()
|
||||
@@ -54,6 +54,28 @@ def test_normalizer_accepts_native_telegraf_host_metric() -> None:
|
||||
assert row[7] == "telegraf.metric-json/v1"
|
||||
|
||||
|
||||
def test_topic_batch_preserves_individual_measurements_and_timestamps() -> None:
|
||||
normalizer = _normalizer()
|
||||
topic = "mission-core/v1/contours/test/agents/test/host"
|
||||
metrics = [
|
||||
{"name": name, "fields": {"value": i}, "tags": {"node_id": "test"},
|
||||
"timestamp": 1_785_179_600 + i}
|
||||
for i, name in enumerate(("cpu", "mem", "net"))
|
||||
]
|
||||
rows = normalizer.normalize_message(topic, json.dumps({"metrics": metrics}).encode())
|
||||
assert rows == [normalizer._normalize(topic, json.dumps(x).encode()) for x in metrics]
|
||||
assert normalizer.normalize_message(topic, json.dumps(metrics[0]).encode()) == [rows[0]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metrics", [[], [None], [{"metrics": []}], [{}] * 513])
|
||||
def test_invalid_batches_are_rejected(metrics) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
_normalizer().normalize_message(
|
||||
"mission-core/v1/contours/test/agents/test/host",
|
||||
json.dumps({"metrics": metrics}).encode(),
|
||||
)
|
||||
|
||||
|
||||
def test_normalizer_keeps_same_timestamp_host_measurements_distinct() -> None:
|
||||
normalizer = _normalizer()
|
||||
rows = [
|
||||
|
||||
@@ -120,6 +120,21 @@ def test_ready_receiver_is_not_restarted(monkeypatch, tmp_path):
|
||||
assert manager.reconcile(tmp_path) == "ready"
|
||||
|
||||
|
||||
def test_old_installer_cannot_replace_managed_connection(tmp_path, monkeypatch):
|
||||
stack, repo, agents = setup(tmp_path, monkeypatch)
|
||||
tunnel = agents / (manager.TUNNEL + ".plist")
|
||||
payload = plistlib.dumps(
|
||||
{
|
||||
"Label": manager.TUNNEL,
|
||||
"ProgramArguments": ["python", "-m", "k1link.compute_connections.link"],
|
||||
}
|
||||
)
|
||||
tunnel.write_bytes(payload)
|
||||
with pytest.raises(ValueError, match="Connection registry owns"):
|
||||
manager.plan(stack, "worker-test", repo, agents)
|
||||
assert tunnel.read_bytes() == payload
|
||||
|
||||
|
||||
def test_old_lan_binding_is_reconciled_even_when_receiver_healthy(monkeypatch, tmp_path):
|
||||
calls = []
|
||||
bindings = iter((False, True))
|
||||
|
||||
Reference in New Issue
Block a user