import { useEffect, useRef, useState } from "react"; import { Link } from "react-router-dom"; import { api, type IntegrationSummary, type SemaphoreTask, type SemaphoreTemplate } from "../api/client"; import { confirmDialog } from "../utils/dialogs"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import TimeAgo from "./TimeAgo"; import { BlockSkeleton } from "./Skeleton"; import { t } from "../i18n"; interface Loaded { integration: IntegrationSummary; templates: SemaphoreTemplate[]; failed: boolean; } const STATUS_WORDS: Record = { waiting: { label: "Waiting to start", badge: "bg-secondary-lt text-secondary" }, starting: { label: "Starting", badge: "bg-blue-lt text-blue" }, running: { label: "Running", badge: "bg-blue-lt text-blue" }, waiting_confirmation: { label: "Waiting for approval in Semaphore", badge: "bg-yellow-lt text-yellow" }, confirmed: { label: "Approved", badge: "bg-blue-lt text-blue" }, rejected: { label: "Rejected in Semaphore", badge: "bg-red-lt text-red" }, stopping: { label: "Stopping", badge: "bg-yellow-lt text-yellow" }, stopped: { label: "Stopped", badge: "bg-secondary-lt text-secondary" }, success: { label: "Finished — success", badge: "bg-green-lt text-green" }, error: { label: "Finished — failed", badge: "bg-red-lt text-red" }, }; const FINISHED = new Set(["success", "error", "stopped", "rejected"]); /** * Starts a Semaphore template — optionally on this server only — and shows how the run gets on. It is the same "run" the Semaphore page * has, with the one addition that matters from a server or an alert: ansible's limit, so "apply updates" touches the one machine and * not the whole inventory. Asks first, and says plainly when there is no limit. */ export default function RunPlaybook({ serverName, defaultLimit }: { serverName: string; defaultLimit: string }) { const [loaded, setLoaded] = useState(null); const [failed, setFailed] = useState(false); const [choice, setChoice] = useState(""); const [limitOn, setLimitOn] = useState(true); const [limit, setLimit] = useState(defaultLimit); const [busy, setBusy] = useState(false); const [run, setRun] = useState<{ integrationId: number; projectId: number; name: string; limit: string; task: SemaphoreTask } | null>(null); const alive = useRef(true); useEffect(() => { alive.current = true; api.integrations .list() .then(async (res) => { const servers = res.integrations.filter((i) => i.type === "semaphore" && i.enabled); const all = await Promise.all( servers.map((integration) => api.integrations.semaphore .templates(integration.id) .then((r): Loaded => ({ integration, templates: r.templates, failed: false })) .catch((): Loaded => ({ integration, templates: [], failed: true })), ), ); if (alive.current) setLoaded(all); }) .catch(() => alive.current && setFailed(true)); return () => { alive.current = false; }; }, []); // Watch a run until it is over. useEffect(() => { if (!run || FINISHED.has(run.task.status)) return; const timer = setInterval(() => { api.integrations.semaphore .task(run.integrationId, run.projectId, run.task.id) .then((res) => alive.current && setRun((r) => (r && r.task.id === res.task.id ? { ...r, task: res.task } : r))) .catch(() => { // Keep asking: one missed answer isn't the end of the run. }); }, 3000); return () => clearInterval(timer); }, [run?.task.id, run?.task.status, run?.integrationId, run?.projectId]); const options = (loaded ?? []).flatMap((l) => l.templates.map((t) => ({ key: `${l.integration.id}:${t.projectId}:${t.id}`, integration: l.integration, template: t, label: `${t.name} — ${t.projectName}${(loaded ?? []).length > 1 ? ` (${l.integration.name})` : ""}`, })), ); const picked = options.find((o) => o.key === choice); const limitText = limitOn ? limit.trim() : ""; async function start() { if (!picked) return; const where = limitText ? `on ${limitText} only` : "on everything the playbook covers — it isn't limited to one server"; if ( !(await confirmDialog({ title: `Run ${picked.template.name}?`, message: `This starts "${picked.template.name}" in ${picked.integration.name} ${where}.`, confirmLabel: "Run it", danger: !limitText, })) ) return; setBusy(true); try { const res = await api.integrations.semaphore.run(picked.integration.id, picked.template.projectId, picked.template.id, limitText ? { limit: limitText } : undefined); setRun({ integrationId: picked.integration.id, projectId: picked.template.projectId, name: picked.template.name, limit: limitText, task: res.task }); toast.success(`Started ${picked.template.name}${limitText ? ` on ${limitText}` : ""}.`); } catch (err) { toast.error(readableError(err)); } finally { setBusy(false); } } if (failed) return
{t("Couldn't load the integrations.")}
; if (loaded === null) return ; if (loaded.length === 0) { return (
There is no Semaphore connected. Add one under {t("Integrations")} to run playbooks from here.
); } return (
{loaded.some((l) => l.failed) &&
Couldn't read the templates of {loaded.filter((l) => l.failed).map((l) => l.integration.name).join(", ")}.
} {options.length === 0 ? (
{t("No templates found in Semaphore.")}
) : ( <>
{picked?.template.lastTask && (
Last run here: {picked.template.lastTask.status} {picked.template.lastTask.end ? ( <> , ) : null}
)}
{limitOn ? (
setLimit(e.target.value)} placeholder="e.g. web01" />
) : (
Not limited: it runs on every host the playbook is set up for.
)}
)} {run && (
{run.name} {run.limit && on {run.limit}} {STATUS_WORDS[run.task.status]?.label ?? run.task.status}
Run #{run.task.id} in Semaphore{FINISHED.has(run.task.status) ? "" : " — checking every few seconds"}. The output is in Semaphore.
)}
); }