diff --git a/README.md b/README.md index 4f392e5..de2b119 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Dockge · Weapie-Fork -Dockge verwaltet Docker-Compose-Stacks über eine Weboberfläche. Dieser Fork des ursprünglichen Dockge von Louis Lam wird von **Weapie** weitergepflegt. Er verwendet shadcn-vue mit Nova, Mist und Phosphor-Icons. [Ursprüngliches Dockge](https://github.com/louislam/dockge) · [UI-Konfiguration](components.json) +Dockge verwaltet Docker-Compose-Stacks über eine Weboberfläche. Dieser Fork des ursprünglichen Dockge von Louis Lam wird von **Weapie** weitergepflegt. Die Oberfläche verwendet shadcn-vue mit dem Preset `b4a7LsmarT`. [Ursprüngliches Dockge](https://github.com/louislam/dockge) · [UI-Konfiguration](components.json) ![Stack-Übersicht mit zwei laufenden Diensten im Demo-Stack](docs/images/stack-uebersicht.png) @@ -42,7 +42,7 @@ Für weitere PowerShell-Sitzungen kannst du den Wert von `$env:DOCKGE_STACKS_DIR ### Erster Start 1. Öffne [http://127.0.0.1:5001](http://127.0.0.1:5001) und erstelle dein Dockge-Konto. -2. Wähle **New stack**, vergib einen Namen und hinterlege eine `compose.yaml`. Für einen ersten Test eignet sich dieser Stack. +2. Wähle **Neuer Stack**, vergib einen Namen und hinterlege eine `compose.yaml`. Für einen ersten Test eignet sich dieser Stack. ~~~yaml services: @@ -53,17 +53,20 @@ Für weitere PowerShell-Sitzungen kannst du den Wert von `$env:DOCKGE_STACKS_DIR - "127.0.0.1:8081:80" ~~~ -3. Klicke auf **Deployen**. Sobald der Container läuft, erreichst du die Beispielseite unter [http://127.0.0.1:8081](http://127.0.0.1:8081). +3. Klicke auf **Deployment prüfen**. Dockge validiert die Compose-Datei, bereitet benötigte Images vor und zeigt die geplanten Änderungen. Bestätige anschließend mit **Ja, starten**. Sobald der Container läuft, erreichst du die Beispielseite unter [http://127.0.0.1:8081](http://127.0.0.1:8081). Dockge bindet die Oberfläche standardmäßig an `127.0.0.1:5001`. Der eingebundene Docker-Socket gibt Dockge weitreichenden Zugriff auf den Host. Beschränke den Zugang auf vertrauenswürdige Personen. Wenn du die Oberfläche über einen Reverse Proxy bereitstellst, verwende HTTPS und leite WebSocket-Verbindungen weiter. [Docker Engine und Sicherheit](https://docs.docker.com/engine/security/) ## Stacks verwalten -- **Übersicht** zeigt Dienste, Status, Ports und die CPU- und Speicherauslastung laufender Container. Du kannst Stacks starten, stoppen, neu starten und Images manuell aktualisieren. -- **Konfiguration** öffnet `compose.yaml` und die Stack-`.env` im Editor mit Suche, Zeilenumbruch und Vollbildansicht. +- **Übersicht** zeigt Dienste, Container-Instanzen, Ports und Ressourcenauslastung. In den Containerdetails findest du Healthcheck-Status, Neustarts, Netzwerke und Mounts. +- **Klick-Editor** bietet Formulare für Image und Build, Ports, Volumes, Umgebungsvariablen, Startbefehle, Healthchecks, Abhängigkeiten und Ressourcenlimits. **Stack-Ressourcen** verwaltet benannte Netzwerke, Volumes und Links. +- **YAML / .env** öffnet die Stack-Dateien im Editor mit Suche, Zeilenumbruch und Vollbildansicht. - **Protokolle** zeigt laufende Stack-Logs. Über die Aktionen eines Dienstes erreichst du dessen Logs, Terminal und Datei-Explorer. - **Wartung** bündelt den Update-Zeitplan und die Schwachstellenscans. +Die Startseite zeigt unter **Benötigt Aufmerksamkeit** ausstehende Freigaben, fehlgeschlagene Vorgänge, Container mit Healthcheck-Fehlern und kritische Scan-Funde. Der **Deployment-Verlauf** zeigt Ergebnisse und die verwendeten Image-IDs. Eine frühere Compose- und `.env`-Version kannst du als Entwurf wiederherstellen. + Für vorhandene Compose-Stacks erwartet Dockge je einen Unterordner im Stack-Verzeichnis, etwa `/opt/stacks/web/compose.yaml`. Lege die zugehörige `.env` und Dateien für relative Bind-Mounts in der bestehenden Verzeichnisstruktur ab. Wähle danach **Stacks-Ordner durchsuchen** im Kontomenü. Bei laufenden Projekten sollten Projektname und Arbeitsverzeichnis zur vorhandenen Bereitstellung passen. Prüfe diese vor dem erneuten Bereitstellen, damit Docker Compose das richtige Projekt anspricht. Über **Einstellungen → Global .env** kannst du die Datei `global.env` im Stack-Verzeichnis pflegen. Docker Compose verwendet sie zur Variablenauflösung, wobei die `.env` des jeweiligen Stacks Vorrang hat. Auf der Startseite lässt sich auch ein `docker run`-Befehl in Compose-YAML umwandeln. @@ -76,7 +79,8 @@ Starte auf jedem zusätzlichen Host eine Dockge-Instanz mit Zugriff auf dessen D ![Stack-Wartung mit Uhrzeit, Wartezeit und Grype-Scanbericht](docs/images/wartung.png) -- **Automatische Image-Updates** sind pro Stack aktivierbar. Wähle unter **Wartung** die tägliche Uhrzeit und eine Zeitzone wie `Europe/Berlin`. Die optionale Wartezeit zählt ab der ersten Erkennung der konkreten neuen Image-Version. Nach Ablauf kann Dockge sie beim nächsten geplanten Lauf bereitstellen. Dockge lädt das neue Image schon beim Erkennen herunter und wartet mit dem Austausch des laufenden Containers. Dienste mit lokalen Builds oder noch nicht bereitgestellten Konfigurationsänderungen werden übersprungen. +- **Automatische Image-Updates** prüfen laufende Dienste täglich zur gewählten Uhrzeit und Zeitzone. Dockge lädt neue Images, scannt sie und legt eine Freigabe an. Die optionale Wartezeit beginnt beim Erkennen der neuen Version. Nach Ablauf kannst du das Update freigeben. Dienste mit lokalen Builds oder noch nicht bereitgestellten Konfigurationsänderungen werden übersprungen. +- **Freigabe nach dem Pull** zeigt die Ergebnisse von Grype vor dem Start. **Ja, starten** verwendet die geprüfte Image-ID und wartet auf den Containerzustand oder vorhandene Healthchecks. **Nein, abbrechen** entfernt die eigens für diesen Vorgang geladenen Images, soweit Docker sie entfernen kann. Bei einem fehlgeschlagenen Scan bleibt die Freigabe gesperrt. - **Images prüfen** scannt die lokalen Image-IDs der Container dieses Stacks. Der Bericht zeigt die Funde nach Schweregrad, betroffene Pakete, gemeldete korrigierte Versionen und den Stand der Datenbank. Der Erstimport der Grype-Datenbank kann einige Minuten dauern. Scanberichte bleiben bis zum Dockge-Neustart im Arbeitsspeicher. - **Grype** prüft auf unterstützten Linux-Architekturen unabhängig vom Dockge-Image regelmäßig auf neue Versionen. Vor jedem Scanbericht aktualisiert Dockge die Schwachstellendatenbank und kann bei einem fehlgeschlagenen Abruf eine weiterhin gültige lokale Datenbank verwenden. [Grype-Datenbank](https://oss.anchore.com/docs/guides/vulnerability/database/) @@ -90,9 +94,9 @@ Unter **Einstellungen → Volumes** siehst du den Treiber, den Nutzungsstatus un ![Volume-Verwaltung mit verwendetem und ungenutztem Volume](docs/images/volumes.png) -Ungenutzte Einträge lassen sich einzeln löschen. **Alle ungenutzten löschen** bereinigt den gesamten gewählten Docker-Host. Die sichtbaren Suchfilter beeinflussen diese Aktion nicht. Für Images und Volumes gibt es jeweils einen eigenen täglichen Zeitplan mit Uhrzeit und Zeitzone. Beide Bereinigungen sind standardmäßig deaktiviert. +Ungenutzte Einträge lassen sich einzeln löschen. **Bereinigung prüfen** zeigt die Kandidaten des gewählten Hosts und markiert geschützte Ressourcen. Für Images und Volumes gibt es jeweils einen eigenen täglichen Zeitplan mit Uhrzeit, Zeitzone, Mindestalter und Ausschlussliste. Beide Bereinigungen sind standardmäßig deaktiviert. -> **Volumes enthalten Anwendungsdaten.** Docker kann auch benannte lokale Volumes löschen, wenn kein Container sie referenziert. Ein Verweis allein in einer gespeicherten Compose-Datei schützt das Volume nicht. Sichere wichtige Volumes, bevor du eine Bereinigung aktivierst. [Docker-Bereinigung](https://docs.docker.com/engine/manage-resources/pruning/) +> **Volumes enthalten Anwendungsdaten.** Die Massenbereinigung prüft Deklarationen in gespeicherten Stacks und schützt die erkannten Volumes. Sichere wichtige Volumes, bevor du eine Bereinigung aktivierst. [Docker-Bereinigung](https://docs.docker.com/engine/manage-resources/pruning/) ## Datei-Explorer diff --git a/backend/agent-socket-handlers/container-management-socket-handler.ts b/backend/agent-socket-handlers/container-management-socket-handler.ts index 61803d8..c43f63b 100644 --- a/backend/agent-socket-handlers/container-management-socket-handler.ts +++ b/backend/agent-socket-handlers/container-management-socket-handler.ts @@ -22,6 +22,7 @@ export class ContainerManagementSocketHandler extends AgentSocketHandler { }; on("listHostContainers", "containerInventoryFailed", async () => ({ items: await server.containerManagement.list() })); + on("getHostContainerDetails", "containerDetailsFailed", async id => ({ details: await server.containerManagement.details(id) })); on("containerFiles", "containerFileFailed", request => server.containerFileExplorer.request(socket.id, request)); socket.on("disconnect", () => server.containerFileExplorer.disconnect(socket.id)); } diff --git a/backend/agent-socket-handlers/docker-socket-handler.ts b/backend/agent-socket-handlers/docker-socket-handler.ts index 32c0601..ff6b944 100644 --- a/backend/agent-socket-handlers/docker-socket-handler.ts +++ b/backend/agent-socket-handlers/docker-socket-handler.ts @@ -8,6 +8,42 @@ export class DockerSocketHandler extends AgentSocketHandler { create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) { // Do not call super.create() + const onDeployment = (event: string, handler: (...args: unknown[]) => Promise) => { + agentSocket.on(event, async (...args: unknown[]) => { + const callback = args.pop(); + if (typeof callback !== "function") { + return; + } + try { + checkLogin(socket); + callbackResult({ ok: true, + ...await handler(...args) }, callback); + } catch (error) { + callbackError(error instanceof ValidationError ? error : new ValidationError("deployOperationFailed"), callback); + } + }); + }; + + onDeployment("deployStack", async (name, yaml, env, isAdd, revision) => ({ deployment: + await server.stackDeployments.prepare(name, "deploy", { yaml, + env, + isAdd, + revision }) })); + onDeployment("startStack", async name => ({ deployment: await server.stackDeployments.prepare(name, "start") })); + onDeployment("updateStack", async name => ({ deployment: await server.stackDeployments.prepare(name, "update") })); + onDeployment("startService", async (name, service) => ({ deployment: await server.stackDeployments.prepare(name, "service", undefined, service) })); + onDeployment("prepareStackDeployment", async (name, mode, draft, service) => { + if (mode !== "deploy" && mode !== "start" && mode !== "update" && mode !== "service") { + throw new ValidationError("deployInvalidRequest"); + } + return { deployment: await server.stackDeployments.prepare(name, mode, draft, service) }; + }); + onDeployment("getStackDeployments", name => server.stackDeployments.status(name)); + onDeployment("decideStackDeployment", async (name, id, approve) => ({ deployment: + await server.stackDeployments.decide(name, id, approve) })); + onDeployment("restoreStackDeployment", (name, id) => server.stackDeployments.restore(name, id)); + onDeployment("getHostAttention", () => server.getHostAttention()); + const onStackMutation = (event: string, handler: (...args: unknown[]) => Promise) => { agentSocket.on(event, async (...args: unknown[]) => { try { @@ -24,24 +60,6 @@ export class DockerSocketHandler extends AgentSocketHandler { }); }; - onStackMutation("deployStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revisionOrCallback, acknowledgement) => { - const callback = typeof revisionOrCallback === "function" ? revisionOrCallback : acknowledgement; - const revision = typeof revisionOrCallback === "function" ? undefined : revisionOrCallback; - try { - const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision); - await stack.deploy(socket); - server.sendStackList(); - callbackResult({ - ok: true, - msg: "Deployed", - msgi18n: true, - }, callback); - stack.joinCombinedTerminal(socket); - } catch (e) { - callbackError(e, callback); - } - }); - onStackMutation("saveStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revisionOrCallback, acknowledgement) => { const callback = typeof revisionOrCallback === "function" ? revisionOrCallback : acknowledgement; const revision = typeof revisionOrCallback === "function" ? undefined : revisionOrCallback; @@ -64,6 +82,10 @@ export class DockerSocketHandler extends AgentSocketHandler { if (typeof(name) !== "string") { throw new ValidationError("Name must be a string"); } + + if ((await server.stackDeployments.status(name)).pending) { + throw new ValidationError("deployAlreadyPending"); + } const stack = await Stack.getStack(server, name); try { @@ -74,6 +96,7 @@ export class DockerSocketHandler extends AgentSocketHandler { } server.imageVulnerabilityScan.forget(name); + await server.stackDeployments.forget(name); server.sendStackList(); callbackResult({ ok: true, @@ -173,30 +196,6 @@ export class DockerSocketHandler extends AgentSocketHandler { } }); - // startStack - onStackMutation("startStack", async (stackName : unknown, callback) => { - try { - - if (typeof(stackName) !== "string") { - throw new ValidationError("Stack name must be a string"); - } - - const stack = await Stack.getStack(server, stackName); - await stack.start(socket); - callbackResult({ - ok: true, - msg: "Started", - msgi18n: true, - }, callback); - server.sendStackList(); - - stack.joinCombinedTerminal(socket); - - } catch (e) { - callbackError(e, callback); - } - }); - // stopStack onStackMutation("stopStack", async (stackName : unknown, callback) => { try { @@ -241,27 +240,6 @@ export class DockerSocketHandler extends AgentSocketHandler { } }); - // updateStack - onStackMutation("updateStack", async (stackName : unknown, callback) => { - try { - - if (typeof(stackName) !== "string") { - throw new ValidationError("Stack name must be a string"); - } - - const stack = await Stack.getStack(server, stackName); - await stack.update(socket); - callbackResult({ - ok: true, - msg: "Updated", - msgi18n: true, - }, callback); - server.sendStackList(); - } catch (e) { - callbackError(e, callback); - } - }); - agentSocket.on("getStackAutoUpdate", async (name: unknown, callback) => { try { checkLogin(socket); @@ -344,27 +322,6 @@ export class DockerSocketHandler extends AgentSocketHandler { } }); - // Start a service - onStackMutation("startService", async (stackName: unknown, serviceName: unknown, callback) => { - try { - - if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") { - throw new ValidationError("Stack name and service name must be strings"); - } - - const stack = await Stack.getStack(server, stackName); - await stack.startService(socket, serviceName); - stack.joinCombinedTerminal(socket); // Ensure the combined terminal is joined - callbackResult({ - ok: true, - msg: "Service " + serviceName + " started" - }, callback); - server.sendStackList(); - } catch (e) { - callbackError(e, callback); - } - }); - // Stop a service onStackMutation("stopService", async (stackName: unknown, serviceName: unknown, callback) => { try { diff --git a/backend/agent-socket-handlers/resource-socket-handler.ts b/backend/agent-socket-handlers/resource-socket-handler.ts index 1ca7fb7..55fffe0 100644 --- a/backend/agent-socket-handlers/resource-socket-handler.ts +++ b/backend/agent-socket-handlers/resource-socket-handler.ts @@ -25,14 +25,16 @@ export class ResourceSocketHandler extends AgentSocketHandler { on("setResourceCleanup", "resourceCleanupSaveFailed", async (kind, schedule) => ({ schedule: await server.resourceCleanup.set(kind, schedule), })); - on("pruneDockerResources", "resourceCleanupFailed", async kind => { - await server.resourceCleanup.prune(kind); - return { msg: "resourceCleanupCompleted", - msgi18n: true }; - }); + on("previewDockerCleanup", "resourceCleanupFailed", async kind => ({ preview: await server.resourceCleanup.preview(kind) })); + on("pruneDockerResources", "resourceCleanupFailed", async (kind, id) => ({ result: await server.resourceCleanup.prune(kind, id) })); on("checkDockerImageTag", "resourceCheckFailed", async (id, tag) => ({ status: await resources.checkImage(id, tag) })); on("removeDockerImage", "resourceDeleteFailed", async (id, tag) => { - await resources.removeImage(id, tag); + await server.stackDeployments.withImageChanges(async () => { + if (typeof id === "string" && server.stackDeployments.protectedImages().has(id)) { + throw new ValidationError("cleanupProtectedImage"); + } + await resources.removeImage(id, tag); + }); return { msg: "resourceDeleted", msgi18n: true }; }); diff --git a/backend/container-management.ts b/backend/container-management.ts index 8788cca..664f517 100644 --- a/backend/container-management.ts +++ b/backend/container-management.ts @@ -25,13 +25,51 @@ interface ContainerRow { image: string; state: string; project: string; + service: string; + ports: string; + status: string; } -const format = "{\"id\":{{json .ID}},\"name\":{{json .Names}},\"image\":{{json .Image}},\"state\":{{json .State}},\"project\":{{json (.Label \"com.docker.compose.project\")}}}"; +const listFields = [ + "\"id\":{{json .ID}}", + "\"name\":{{json .Names}}", + "\"image\":{{json .Image}}", + "\"state\":{{json .State}}", + "\"project\":{{json (.Label \"com.docker.compose.project\")}}", + "\"service\":{{json (.Label \"com.docker.compose.service\")}}", + "\"ports\":{{json .Ports}}", + "\"status\":{{json .Status}}", +]; + +const detailFields = [ + "\"name\":{{json .Name}}", + "\"imageId\":{{json .Image}}", + "\"created\":{{json .Created}}", + "\"started\":{{json .State.StartedAt}}", + "\"finished\":{{json .State.FinishedAt}}", + "\"state\":{{json .State.Status}}", + "\"health\":{{with index .State \"Health\"}}{{json .Status}}{{else}}\"\"{{end}}", + "\"exitCode\":{{json .State.ExitCode}}", + "\"restartCount\":{{json .RestartCount}}", + "\"restartPolicy\":{{json .HostConfig.RestartPolicy.Name}}", + "\"platform\":{{json .Platform}}", + "\"memoryBytes\":{{json .HostConfig.Memory}}", + "\"nanoCpus\":{{json .HostConfig.NanoCpus}}", + "\"mounts\":[{{range $i, $mount := .Mounts}}{{if $i}},{{end}}" + + "{\"type\":{{json $mount.Type}},\"name\":{{json (index $mount \"Name\")}},\"target\":{{json $mount.Destination}},\"writable\":{{json $mount.RW}}}{{end}}]", + "\"networks\":{ {{$sep := \"\"}}{{range $name, $network := index .NetworkSettings \"Networks\"}}{{$sep}}{{json $name}}:" + + "{\"ipv4\":{{json (index $network \"IPAddress\")}},\"ipv6\":{{json (index $network \"GlobalIPv6Address\")}}}{{$sep = \",\"}}{{end}} }", +]; export class ContainerManagement { async list(): Promise { - const { stdout } = await docker([ "container", "ls", "--all", "--no-trunc", "--format", format ]); + const { stdout } = await docker([ "container", "ls", "--all", "--no-trunc", "--format", `{${listFields.join(",")}}` ]); return stdout.trim().split(/\r?\n/).filter(Boolean).map(row => JSON.parse(row) as ContainerRow); } + + async details(rawId: unknown) { + const id = containerId(rawId); + const { stdout } = await docker([ "container", "inspect", "--format", `{${detailFields.join(",")}}`, "--", id ]); + return JSON.parse(stdout); + } } diff --git a/backend/dockge-server.ts b/backend/dockge-server.ts index 920c46f..a1aa75f 100644 --- a/backend/dockge-server.ts +++ b/backend/dockge-server.ts @@ -32,6 +32,7 @@ import expressStaticGzip from "express-static-gzip"; import path from "path"; import { TerminalSocketHandler } from "./agent-socket-handlers/terminal-socket-handler"; import { Stack } from "./stack"; +import { StackDeployments } from "./stack-deployments"; import { Cron } from "croner"; import gracefulShutdown from "http-graceful-shutdown"; import User from "./models/user"; @@ -94,8 +95,9 @@ export class DockgeServer { dockerResources = new DockerResources(); containerManagement = new ContainerManagement(); containerFileExplorer = new ContainerFileExplorer(); - resourceCleanup = new ResourceCleanup(); + resourceCleanup = new ResourceCleanup(this); imageVulnerabilityScan = new ImageVulnerabilityScan(this); + stackDeployments = new StackDeployments(this); /** * @@ -409,6 +411,7 @@ export class DockgeServer { this.needSetup = true; } + await this.stackDeployments.initialize(); // Listen this.httpServer.listen(this.config.port, this.config.hostname, () => { if (this.config.hostname) { @@ -637,6 +640,37 @@ export class DockgeServer { } } + async getHostAttention() { + const [ containers, stacks, imageCleanup, volumeCleanup ] = await Promise.all([ + this.containerManagement.list().catch(() => []), + Stack.getStackList(this, true).catch(() => new Map()), + this.resourceCleanup.status("images").catch(() => null), + this.resourceCleanup.status("volumes").catch(() => null), + ]); + const recent = await Promise.all(Array.from(stacks.values()).filter(stack => stack.isManagedByDockge).slice(0, 100) + .map(async stack => { + const policy = await this.stackAutoUpdate.getPolicy(stack).catch(() => null); + return policy?.lastRun?.result === "failed" ? [{ stack: stack.name, + kind: "deployAttentionUpdate" }] : []; + })); + return { + items: [ + ...this.stackDeployments.attention(), + ...containers.flatMap(item => /\(unhealthy\)|^Restarting\b/i.test(item.status) + ? [{ stack: item.project, + container: item.name, + kind: item.state === "restarting" ? "deployAttentionRestarting" : "deployAttentionUnhealthy" }] + : []), + ...recent.flat(), + ...this.imageVulnerabilityScan.attention(), + ...(imageCleanup?.lastRun?.result === "failed" ? [{ resource: "images", + kind: "deployAttentionCleanup" }] : []), + ...(volumeCleanup?.lastRun?.result === "failed" ? [{ resource: "volumes", + kind: "deployAttentionCleanup" }] : []), + ].slice(0, 100), + }; + } + async getDockerNetworkList() : Promise { let res = await childProcessAsync.spawn("docker", [ "network", "ls", "--format", "{{.Name}}" ], { encoding: "utf-8", @@ -704,7 +738,7 @@ export class DockgeServer { this.stackAutoUpdate.stop(); this.resourceCleanup.stop(); - await this.imageVulnerabilityScan.stop(); + await Promise.all([ this.imageVulnerabilityScan.stop(), this.stackDeployments.stop() ]); await Database.close(); Settings.stopCacheCleaner(); } diff --git a/backend/image-vulnerability-scan.ts b/backend/image-vulnerability-scan.ts index 9d19bf9..ab8777c 100644 --- a/backend/image-vulnerability-scan.ts +++ b/backend/image-vulnerability-scan.ts @@ -42,7 +42,7 @@ interface Finding { fixedVersions: string[]; } -interface ImageScan { +export interface ImageScan { id: string; references: string[]; services: string[]; @@ -170,7 +170,7 @@ export class ImageVulnerabilityScan { constructor(private readonly server: DockgeServer) {} /** Start one bounded scan per host without waiting for Docker or Grype to finish. */ - start(stack: Stack) { + start(stack: Stack, images?: ImageScan[]) { if (this.active) { if (this.active.stackName === stack.name && this.reports.has(stack.name)) { return this.summary(stack.name); @@ -191,10 +191,35 @@ export class ImageVulnerabilityScan { this.reports.delete(oldest); } this.active = report; - this.activeRun = this.run(stack, report); + this.activeRun = this.run(stack, report, images); return this.summary(stack.name); } + /** Scan the exact local images prepared for a deployment, before any container starts. */ + async scanPrepared(stack: Stack, images: ImageScan[]) { + if (!images.length) { + return { images: [] }; + } + if (images.length > maxImages) { + throw new ValidationError("imageScanTooManyImages"); + } + while (this.active && !this.shutdown.signal.aborted) { + await this.activeRun; + } + if (this.shutdown.signal.aborted) { + throw new ValidationError("imageScanFailed"); + } + this.start(stack, images); + const report = this.active!; + await this.activeRun; + return { + id: report.id, + error: report.error, + images: report.images.map(image => ({ ...image, + findings: image.findings.slice(0, 8) })), + }; + } + /** Return progress and counts without sending package details over the socket. */ summary(stackName: string) { const report = this.reports.get(stackName); @@ -207,6 +232,15 @@ export class ImageVulnerabilityScan { }; } + attention() { + return Array.from(this.reports.values()).flatMap(report => { + const count = report.images.reduce((total, image) => total + (image.counts?.critical || 0), 0); + return count ? [{ stack: report.stackName, + kind: "deployAttentionCritical", + count }] : []; + }); + } + /** Page through retained findings for the requested immutable image and report. */ page(stackName: string, reportId: unknown, imageId: unknown, severity: unknown, offset: unknown) { if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 || offset > maxFindings @@ -230,8 +264,10 @@ export class ImageVulnerabilityScan { } /** Forget reports for a deleted stack, including one still being scanned. */ - forget(stackName: string) { - this.reports.delete(stackName); + forget(stackName: string, reportId?: string) { + if (!reportId || this.reports.get(stackName)?.id === reportId) { + this.reports.delete(stackName); + } } private get scanner() { @@ -251,9 +287,9 @@ export class ImageVulnerabilityScan { } /** Scan each immutable image once and keep the successful partial results. */ - private async run(stack: Stack, report: ScanReport) { + private async run(stack: Stack, report: ScanReport, images?: ImageScan[]) { try { - report.images = await this.discoverImages(stack); + report.images = images ?? await this.discoverImages(stack); if (report.images.length) { report.preparingDatabase = true; try { @@ -337,14 +373,14 @@ export class ImageVulnerabilityScan { /** Export only the immutable local image and remove the archive on every exit path. */ private async scanImage(stack: Stack, id: string) { - const size = Number(await this.docker(stack, [ "image", "inspect", "--format", "{{.Size}}", "--", id ])); + const size = Number(await this.docker(stack, [ "image", "inspect", "--format", "{{.Size}}", "--", id ], os.tmpdir())); if (!Number.isSafeInteger(size) || size < 0 || size > maxImageBytes) { throw new ValidationError("imageScanImageTooLarge"); } const directory = await fs.mkdtemp(path.join(os.tmpdir(), "dockge-image-scan-")); try { const archive = path.join(directory, "image.tar"); - await this.saveImage(stack, id, archive); + await this.saveImage(id, archive); const stdout = await this.runGrype([ `docker-archive:${archive}`, "-o", "json" ], directory, 5 * 60 * 1000); try { return normalizeFindings(stdout); @@ -360,7 +396,7 @@ export class ImageVulnerabilityScan { } /** Stream Docker's export to disk with a hard archive limit and a timeout. */ - private async saveImage(stack: Stack, id: string, archive: string) { + private async saveImage(id: string, archive: string) { let bytes = 0; const limit = new Transform({ transform(chunk, encoding, callback) { @@ -373,7 +409,7 @@ export class ImageVulnerabilityScan { }, }); const child = spawn("docker", [ "image", "save", "--", id ], { - cwd: stack.path, + cwd: os.tmpdir(), stdio: [ "ignore", "pipe", "ignore" ], timeout: 120000, signal: this.shutdown.signal, @@ -401,9 +437,9 @@ export class ImageVulnerabilityScan { } /** Run Docker without exposing raw CLI errors to the browser. */ - private async docker(stack: Stack, args: string[]): Promise { + private async docker(stack: Stack, args: string[], cwd = stack.path): Promise { const { stdout } = await exec("docker", args, { - cwd: stack.path, + cwd, timeout: 30000, maxBuffer: 2 * 1024 * 1024, signal: this.shutdown.signal, diff --git a/backend/resource-cleanup.ts b/backend/resource-cleanup.ts index 22ef82e..c8f44b1 100644 --- a/backend/resource-cleanup.ts +++ b/backend/resource-cleanup.ts @@ -1,8 +1,16 @@ +import { randomUUID } from "node:crypto"; import { execFile } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; import { promisify } from "node:util"; import { Cron } from "croner"; +import dotenv from "dotenv"; +import yaml from "yaml"; +import { envsubstYAML } from "../common/util-common"; +import type { DockgeServer } from "./dockge-server"; import { log } from "./log"; import { Settings } from "./settings"; +import { Stack } from "./stack"; import { ValidationError } from "./util-server"; const exec = promisify(execFile); @@ -10,8 +18,11 @@ const kinds = [ "images", "volumes" ] as const; type Kind = typeof kinds[number]; const defaults = { enabled: false, time: "04:00", - timezone: "UTC" }; + timezone: "UTC", + minAgeHours: 0, + excludes: [] as string[] }; type Schedule = typeof defaults; +type Resource = { id: string; name: string; tags?: string[]; created: string | null; size?: number | null; driver?: string; reason?: string }; function resourceKind(value: unknown): Kind { if (value !== "images" && value !== "volumes") { @@ -27,6 +38,11 @@ function validSchedule(value: unknown): value is Schedule { || typeof schedule.timezone !== "string" || !/^[A-Za-z][A-Za-z0-9_+/-]{0,99}$/.test(schedule.timezone)) { return false; } + if (!Number.isSafeInteger(schedule.minAgeHours) || schedule.minAgeHours! < 0 || schedule.minAgeHours! > 87600 + || !Array.isArray(schedule.excludes) || schedule.excludes.length > 200 + || schedule.excludes.some(item => typeof item !== "string" || !item.trim() || item.length > 512 || /[\r\n\0]/.test(item))) { + return false; + } try { new Intl.DateTimeFormat("en-CA", { timeZone: schedule.timezone }); return true; @@ -41,6 +57,9 @@ export class ResourceCleanup { private readonly saving = new Set(); private readonly shutdown = new AbortController(); private initialization?: Promise; + private readonly previews = new Map }>(); + + constructor(private readonly server: DockgeServer) {} start() { this.initialization ??= this.initialize(); @@ -63,7 +82,9 @@ export class ResourceCleanup { private async read(kind: Kind): Promise { const value = await Settings.get(`resourceCleanup:${kind}`, false); - return validSchedule(value) ? value : { ...defaults }; + const schedule = { ...defaults, + ...value }; + return validSchedule(schedule) ? schedule : { ...defaults }; } async status(value: unknown) { @@ -88,10 +109,12 @@ export class ResourceCleanup { } this.saving.add(kind); try { - const { enabled, time, timezone } = schedule; + const { enabled, time, timezone, minAgeHours, excludes } = schedule; await Settings.set(`resourceCleanup:${kind}`, { enabled, time, - timezone }); + timezone, + minAgeHours, + excludes: Array.from(new Set(excludes.map(item => item.trim()))) }); this.schedule(kind, schedule); return await this.status(kind); } finally { @@ -129,7 +152,10 @@ export class ResourceCleanup { result: "started" }); let result = "success"; try { - await this.prune(kind); + const result = await this.prune(kind, undefined, true); + if (result.failed) { + throw new Error("Could not remove some resources"); + } } catch { result = "failed"; } @@ -144,20 +170,168 @@ export class ResourceCleanup { } } - async prune(value: unknown) { + async preview(value: unknown) { + const kind = resourceKind(value); + const items = await this.inventory(kind); + const id = randomUUID(); + const now = Date.now(); + for (const [ key, preview ] of this.previews) { + if (preview.expires <= now) { + this.previews.delete(key); + } + } + if (this.previews.size >= 24) { + this.previews.delete(this.previews.keys().next().value!); + } + this.previews.set(id, { kind, + expires: now + 5 * 60 * 1000, + resources: new Set(items.filter(item => !item.reason).map(item => this.resourceKey(item))) }); + return { id, + items }; + } + + private resourceKey(item: Resource) { + return JSON.stringify([ item.id, item.created ]); + } + + private async inventory(kind: Kind): Promise { + const schedule = await this.read(kind); + const exclusions = new Set(schedule.excludes); + const now = Date.now(); + const resources: Resource[] = []; + const protectedImages = this.server.stackDeployments.protectedImages(); + if (kind === "images") { + const images = await this.server.dockerResources.listImages(); + for (const item of images) { + if (!item.containers.length && !item.referenceOnly) { + resources.push({ id: item.id, + name: item.tags[0] || item.id, + tags: item.tags, + created: item.created, + size: item.size, + reason: protectedImages.has(item.id) ? "cleanupProtectedImage" : undefined }); + } + } + } else { + const [ volumes, declarations ] = await Promise.all([ this.server.dockerResources.listVolumes(), this.volumeDeclarations() ]); + for (const item of volumes) { + if (!item.containers.length) { + const reason = declarations.names.has(item.name) ? "cleanupDeclaredVolume" + : declarations.unresolved.some(prefix => item.name.startsWith(prefix)) ? "cleanupUnresolvedVolume" + : item.driver !== "local" ? "cleanupExternalVolume" : undefined; + resources.push({ id: item.name, + name: item.name, + created: item.created, + driver: item.driver, + reason }); + } + } + } + for (const item of resources) { + if (item.reason) { + continue; + } + if (exclusions.has(item.id) || item.tags?.some(tag => exclusions.has(tag))) { + item.reason = "cleanupExcluded"; + } else if (schedule.minAgeHours && (!item.created || !Number.isFinite(Date.parse(item.created)) + || now - Date.parse(item.created) < schedule.minAgeHours * 3600000)) { + item.reason = "cleanupTooNew"; + } + } + return resources.sort((a, b) => a.name.localeCompare(b.name)); + } + + private async volumeDeclarations() { + const names = new Set(); + const unresolved: string[] = []; + const directory = this.server.stacksDir; + const global = await fs.readFile(path.join(directory, "global.env"), "utf8").catch(() => ""); + const entries = (await fs.readdir(directory, { withFileTypes: true })) + .filter(entry => entry.isDirectory() && /^[a-z0-9_-]+$/.test(entry.name)); + const add = async (stack: Stack) => { + if (!stack.composeYAML) { + return; + } + try { + const args = stack.getComposeOptions("config", "--format", "json", "--no-env-resolution"); + args.splice(1, 0, "--all-resources"); + const { stdout } = await exec("docker", args, { + cwd: stack.fullPath, + timeout: 10000, + maxBuffer: 4 * 1024 * 1024, + signal: this.shutdown.signal, + windowsHide: true, + }); + const config = JSON.parse(stdout); + for (const [ key, value ] of Object.entries(config.volumes || {})) { + const volume = value as { name?: string; external?: boolean } | null; + names.add(volume?.name || (volume?.external ? key : `${config.name || stack.name}_${key}`)); + } + return; + } catch { + unresolved.push(stack.name + "_"); + } + try { + const env = { ...dotenv.parse(global), + ...dotenv.parse(stack.composeENV) }; + const config = yaml.parse(envsubstYAML(stack.composeYAML, env), { merge: true }); + const project = config?.name || env.COMPOSE_PROJECT_NAME || stack.name; + for (const [ key, value ] of Object.entries(config?.volumes || {})) { + const volume = value as { name?: string; external?: boolean | { name?: string } } | null; + const externalName = typeof volume?.external === "object" ? volume.external?.name : undefined; + names.add(volume?.name || externalName || (volume?.external ? key : `${project}_${key}`)); + } + } catch { + // Keep the default project prefix if even the raw draft is invalid. + } + }; + for (let index = 0; index < entries.length; index += 6) { + await Promise.all(entries.slice(index, index + 6).map(entry => add(new Stack(this.server, entry.name)))); + } + return { names, + unresolved }; + } + + async prune(value: unknown, id?: unknown, scheduled = false) { const kind = resourceKind(value); if (this.running.has(kind) || this.shutdown.signal.aborted) { throw new ValidationError("resourceCleanupBusy"); } + const approval = typeof id === "string" ? this.previews.get(id) : undefined; + if (!scheduled && (!approval || approval.kind !== kind || approval.expires <= Date.now())) { + throw new ValidationError("cleanupPreviewExpired"); + } + if (typeof id === "string") { + this.previews.delete(id); + } this.running.add(kind); try { - // The Docker daemon determines which resources are currently unreferenced. - await exec("docker", [ kind === "images" ? "image" : "volume", "prune", "--all", "--force" ], { - timeout: 120000, - maxBuffer: 8 * 1024 * 1024, - signal: this.shutdown.signal, - windowsHide: true, - }); + const remove = async () => { + let removed = 0; + let failed = 0; + const items = await this.inventory(kind); + for (const item of items) { + if (this.shutdown.signal.aborted || item.reason || (approval && !approval.resources.has(this.resourceKey(item)))) { + continue; + } + try { + if (kind === "images") { + for (const tag of item.tags?.length ? item.tags : [ "" ]) { + await this.server.dockerResources.removeImage(item.id, tag); + } + } else { + await this.server.dockerResources.removeVolume(item.id, item.created); + } + removed++; + } catch { + failed++; + } + } + return { removed, + failed, + retained: Math.max(0, (approval?.resources.size ?? items.length) - removed - failed) }; + }; + return kind === "images" ? await this.server.stackDeployments.withImageChanges(remove) : await remove(); } finally { this.running.delete(kind); } diff --git a/backend/socket-handlers/agent-proxy-socket-handler.ts b/backend/socket-handlers/agent-proxy-socket-handler.ts index 426ec0f..ec8030f 100644 --- a/backend/socket-handlers/agent-proxy-socket-handler.ts +++ b/backend/socket-handlers/agent-proxy-socket-handler.ts @@ -22,7 +22,8 @@ export class AgentProxySocketHandler extends SocketHandler { } if (endpoint === ALL_ENDPOINTS) { // Send to all endpoints - if ([ "containerFiles", "listHostContainers" ].includes(eventName)) { + if ([ "containerFiles", "listHostContainers", "getHostContainerDetails", "prepareStackDeployment", + "decideStackDeployment", "restoreStackDeployment", "pruneDockerResources" ].includes(eventName)) { throw new Error("containerActionUnavailable"); } log.debug("agent", "Sending to all endpoints: " + eventName); diff --git a/backend/stack-auto-update.ts b/backend/stack-auto-update.ts index 7dbd8f9..b627f03 100644 --- a/backend/stack-auto-update.ts +++ b/backend/stack-auto-update.ts @@ -15,8 +15,8 @@ const policyFile = ".dockge-auto-update.json"; const dockgeImage = /(?:^|\/)(?:louislam\/dockge|dockge:local)(?:[:@]|$)/i; const stackName = /^[a-z0-9_-]+$/; -type Outcome = "updated" | "unchanged" | "waiting" | "skipped" | "failed"; -const outcomes: Outcome[] = [ "updated", "unchanged", "waiting", "skipped", "failed" ]; +type Outcome = "updated" | "unchanged" | "waiting" | "skipped" | "failed" | "approval"; +const outcomes: Outcome[] = [ "updated", "unchanged", "waiting", "skipped", "failed", "approval" ]; interface Schedule { enabled: boolean; @@ -322,59 +322,14 @@ export class StackAutoUpdate { } } - /** Pull and recreate only running services whose image actually changed. */ + /** Prepare changed images for review while leaving the running containers in place. */ private async update(stack: Stack, policy: Policy): Promise { - const before = await this.getCandidates(stack); - if (before.size === 0) { + const candidates = await this.getCandidates(stack); + if (!candidates.size) { return "skipped"; } - - await this.docker(stack, stack.getComposeOptions("pull", "--policy", "always", "--ignore-buildable", "--", ...before.keys())); - - const after = await this.getCandidates(stack); - const changed = new Map(); - const pending = new Map(policy.pending.map(entry => [ entry.service, entry ])); - const waiting: PendingImage[] = []; - const observedAt = new Date(); - let skipped = false; - for (const [ name, original ] of before) { - const current = after.get(name); - if (!current || original.hash !== current.hash || original.image !== current.image - || original.containers.join() !== current.containers.join()) { - skipped = true; - continue; - } - const imageId = await this.docker(stack, [ "image", "inspect", "--format", "{{.Id}}", "--", current.image ]); - if (!/^sha256:[a-f0-9]{64}$/.test(imageId)) { - throw new Error("Docker image inspect returned an invalid image ID"); - } - if (current.imageIds.every(id => id === imageId)) { - continue; - } - const previous = pending.get(name); - const entry = previous?.id === imageId && previous.image === current.image ? previous : { - service: name, - image: current.image, - id: imageId, - since: observedAt.toISOString(), - }; - waiting.push(entry); - if (observedAt.getTime() >= Date.parse(entry.since) + policy.delayHours * hourMs) { - changed.set(name, current); - } - } - - policy.pending = waiting; - if (!changed.size) { - return waiting.length ? "waiting" : (skipped ? "skipped" : "unchanged"); - } - // Keep first-seen times if deployment fails or the process stops partway through. - await this.writePolicy(stack, policy); - const scale = Array.from(changed, ([ name, service ]) => [ "--scale", `${name}=${service.containers.length}` ]).flat(); - await this.docker(stack, stack.getComposeOptions("up", "-d", "--no-deps", "--no-build", "--pull", "never", - "--wait", "--wait-timeout", "120", ...scale, "--", ...changed.keys())); - policy.pending = waiting.filter(entry => !changed.has(entry.service)); - return "updated"; + policy.pending = []; + return this.server.stackDeployments.prepareScheduled(stack, candidates, policy.delayHours); } /** Restrict candidates to unchanged, running services owned by this stack directory. */ @@ -435,7 +390,8 @@ export class StackAutoUpdate { continue; } const directory = path.resolve(stack.path); - if (!entries.every(container => container.State === "running" && container.hash === hash + if (!entries.every(container => container.State === "running" + && (container.hash === hash || this.server.stackDeployments.matchesDeployedHash(stack.name, name, hash, container.hash)) && container.directory && path.resolve(container.directory) === directory)) { continue; } diff --git a/backend/stack-deployments.ts b/backend/stack-deployments.ts new file mode 100644 index 0000000..210e89c --- /dev/null +++ b/backend/stack-deployments.ts @@ -0,0 +1,739 @@ +import { execFile } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { existsSync, promises as fs } from "node:fs"; +import path from "node:path"; +import { promisify } from "node:util"; +import { analyzeEnv } from "../common/env-file"; +import type { DockgeServer } from "./dockge-server"; +import type { ImageScan } from "./image-vulnerability-scan"; +import { log } from "./log"; +import { Stack } from "./stack"; +import { ValidationError } from "./util-server"; + +const exec = promisify(execFile); +const stackNamePattern = /^[a-z0-9_-]+$/; +const serviceNamePattern = /^[a-zA-Z0-9_.-]+$/; +const imageIdPattern = /^sha256:[a-f0-9]{64}$/; +const historyLimit = 12; +const maximumConfigSize = 2 * 1024 * 1024; + +type Phase = "preparing" | "pulling" | "scanning" | "ready" | "applying" | "deployed" | "rejected" | "failed"; +type Mode = "deploy" | "start" | "update" | "service" | "scheduled"; +type Draft = { yaml: string; env: string; isAdd: boolean; revision?: string }; +type Service = { image?: string; build?: unknown; platform?: string; pull_policy?: string; depends_on?: Record | string[] }; +type Config = { name: string; services: Record; [key: string]: unknown }; +type Runtime = { id: string; name: string; service: string; image: string; hash: string; state: string; health: string }; +type Candidate = { imageIds: string[]; containers: string[] }; +type PreparedImage = { reference: string; platform?: string; id: string; previous?: string; fresh: boolean; retagged: boolean }; +type Change = { name: string; action: "create" | "recreate" | "start" | "keep" | "remove"; reference?: string; imageId?: string; previousImageIds?: string[] }; + +interface Deployment { + id: string; + name: string; + mode: Mode; + phase: Phase; + startedAt: string; + finishedAt?: string; + error?: string; + field?: string; + project?: string; + approved?: boolean; + notBefore?: string; + service?: string; + draft?: Draft; + revision?: string; + fingerprint?: string; + runtimeFingerprint?: string; + changes: Change[]; + images: PreparedImage[]; + scans: ImageScan[]; + scanReportId?: string; + sourceHashes: Record; + appliedHashes?: Record; + scale?: Record; + cleanup?: { removed: number; retained: number }; +} + +type Store = { pending?: Deployment; history: Deployment[] }; + +function digest(value: unknown) { + return createHash("sha256").update(JSON.stringify(value)).digest("hex"); +} + +function publicRecord(record: Deployment, includeScans = true) { + const { id, name, mode, phase, startedAt, finishedAt, error, field, notBefore, changes, scans, cleanup } = record; + return { id, + name, + mode, + phase, + startedAt, + finishedAt, + error, + field, + notBefore, + changes, + scans: includeScans ? scans : [], + cleanup }; +} + +class ComposeValidationError extends ValidationError { + constructor(readonly field: string | undefined) { + super("editorComposeInvalid"); + } +} + +function operationError(error: unknown, fallback: string) { + if (error instanceof ValidationError) { + return error.message; + } + const stderr = typeof error === "object" && error && "stderr" in error ? String(error.stderr) : ""; + if (/port is already allocated|address already in use/i.test(stderr)) { + return "deployPortInUse"; + } + if (/unhealthy|dependency failed to start/i.test(stderr)) { + return "deployUnhealthy"; + } + if (/no matching manifest/i.test(stderr)) { + return "deployPlatformUnavailable"; + } + return fallback; +} + +export class StackDeployments { + private readonly stores = new Map(); + private readonly jobs = new Map>(); + private readonly shutdown = new AbortController(); + private loading?: Promise; + private pullQueue: Promise = Promise.resolve(); + + constructor(private readonly server: DockgeServer) {} + + private get directory() { + return path.resolve(this.server.config.dataDir, "stack-deployments"); + } + + async initialize() { + this.loading ??= this.load(); + await this.loading; + } + + private async load() { + await fs.mkdir(this.directory, { recursive: true, + mode: 0o700 }); + for (const entry of await fs.readdir(this.directory, { withFileTypes: true })) { + const name = entry.name; + if (entry.isDirectory() && /^\.(apply|preview)-[a-zA-Z0-9]{6}$/.test(name)) { + await fs.rm(path.join(this.directory, name), { recursive: true, + force: true }).catch(() => {}); + continue; + } + if (entry.isFile() && /^[a-z0-9_-]+\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) { + await fs.rm(path.join(this.directory, name), { force: true }).catch(() => {}); + continue; + } + if (!entry.isFile() || !/^[a-z0-9_-]+\.json$/.test(name)) { + continue; + } + try { + const stack = name.slice(0, -5); + const store = JSON.parse(await fs.readFile(path.join(this.directory, name), "utf8")) as Store; + if (!Array.isArray(store.history)) { + continue; + } + this.stores.set(stack, store); + if (store.pending && ![ "ready", "failed" ].includes(store.pending.phase)) { + store.pending.phase = "failed"; + store.pending.error = "deployInterrupted"; + await this.write(stack); + } + } catch { + log.warn("deploy", "Could not load a deployment record"); + } + } + } + + async stop() { + this.shutdown.abort(); + await Promise.allSettled(this.jobs.values()); + } + + private store(name: string) { + if (!this.stores.has(name)) { + this.stores.set(name, { history: [] }); + } + return this.stores.get(name)!; + } + + private async write(name: string) { + const file = path.join(this.directory, name + ".json"); + const temp = file + "." + randomUUID() + ".tmp"; + try { + await fs.writeFile(temp, JSON.stringify(this.store(name)), { flag: "wx", + mode: 0o600 }); + await fs.rename(temp, file); + } finally { + await fs.rm(temp, { force: true }); + } + } + + private name(value: unknown) { + if (typeof value !== "string" || value.length > 128 || !stackNamePattern.test(value)) { + throw new ValidationError("deployInvalidRequest"); + } + return value; + } + + async status(value: unknown) { + await this.initialize(); + const store = this.stores.get(this.name(value)); + const record = store?.pending; + const runtime = record?.approved && record.project && record.phase === "applying" + ? await this.runtime(record.project).catch(() => []) : []; + const progress = runtime.filter(row => record?.changes.some(change => change.name === row.service && change.imageId === row.image)) + .map(({ service, state, health }) => ({ service, + state, + health })); + return { + pending: record ? { ...publicRecord(record), + progress } : null, + history: store?.history.map((item, index) => publicRecord(item, index === 0)) ?? [], + }; + } + + async restore(value: unknown, id: unknown) { + await this.initialize(); + const record = this.stores.get(this.name(value))?.history.find(item => item.id === id && item.phase === "deployed"); + if (!record?.draft) { + throw new ValidationError("deployHistoryMissing"); + } + return { yaml: record.draft.yaml, + env: record.draft.env }; + } + + async forget(value: unknown) { + await this.initialize(); + const name = this.name(value); + await fs.rm(path.join(this.directory, name + ".json"), { force: true }); + this.stores.delete(name); + } + + async prepare(value: unknown, mode: Mode, input?: unknown, service?: unknown) { + await this.initialize(); + const name = this.name(value); + let draft: Draft | undefined; + if (mode === "deploy") { + const data = input as Draft | undefined; + if (!data || typeof data.yaml !== "string" || typeof data.env !== "string" || typeof data.isAdd !== "boolean" + || (data.revision !== undefined && (typeof data.revision !== "string" || !/^[a-f0-9]{64}$/.test(data.revision))) + || Buffer.byteLength(data.yaml) + Buffer.byteLength(data.env) > maximumConfigSize) { + throw new ValidationError("deployInvalidRequest"); + } + if (analyzeEnv(data.env).some(issue => issue.severity === "error")) { + throw new ValidationError("editorInvalidEnv"); + } + draft = { yaml: data.yaml, + env: data.env, + isAdd: data.isAdd, + revision: data.revision }; + } + if (mode === "service" && (typeof service !== "string" || !serviceNamePattern.test(service))) { + throw new ValidationError("deployInvalidRequest"); + } + const record = this.create(name, mode, draft); + record.service = typeof service === "string" ? service : undefined; + this.run(record, () => Stack.withOperation(this.server, name, () => this.prepareRecord(record))); + return publicRecord(record); + } + + async prepareScheduled(stack: Stack, candidates: Map, delayHours: number) { + await this.initialize(); + const current = this.stores.get(stack.name)?.pending; + if (current) { + return current.mode === "scheduled" ? (current.phase === "failed" ? "failed" : "approval") : "skipped"; + } + const record = this.create(stack.name, "scheduled"); + this.run(record, () => this.prepareRecord(record, candidates, delayHours)); + await this.jobs.get(stack.name); + const pending = this.stores.get(stack.name)?.pending; + return pending ? (pending.phase === "failed" ? "failed" : "approval") : "unchanged"; + } + + private create(name: string, mode: Mode, draft?: Draft) { + const store = this.store(name); + if (store.pending || this.jobs.has(name) || this.shutdown.signal.aborted) { + throw new ValidationError("deployAlreadyPending"); + } + const record: Deployment = { + id: randomUUID(), + name, + mode, + draft, + phase: "preparing", + startedAt: new Date().toISOString(), + changes: [], + images: [], + scans: [], + sourceHashes: {}, + }; + store.pending = record; + return record; + } + + private run(record: Deployment, action: () => Promise) { + const job = Promise.resolve().then(action).catch(async error => { + record.phase = "failed"; + record.error = operationError(error, "deployOperationFailed"); + record.field = error instanceof ComposeValidationError ? error.field : undefined; + record.finishedAt = new Date().toISOString(); + await this.write(record.name).catch(() => {}); + log.warn("deploy", `${record.name}: ${record.error}`); + }).finally(() => { + this.jobs.delete(record.name); + }); + this.jobs.set(record.name, job); + } + + private async command(args: string[], cwd?: string, timeout = 30000) { + const { stdout } = await exec("docker", args, { + cwd, + timeout, + encoding: "utf8", + maxBuffer: 8 * 1024 * 1024, + windowsHide: true, + signal: this.shutdown.signal, + }); + return stdout.trim(); + } + + private async configure(stack: Stack, draft: Draft | undefined, action: (compose: (args: string[], timeout?: number) => Promise) => Promise) { + if (!draft) { + return action(([ command, ...args ], timeout) => this.command(stack.getComposeOptions(command, ...args), stack.fullPath, timeout)); + } + const temp = await fs.mkdtemp(path.join(this.directory, ".preview-")); + try { + const yaml = path.join(temp, "compose.yaml"); + const env = path.join(temp, ".env"); + await fs.writeFile(yaml, draft.yaml, { mode: 0o600 }); + await fs.writeFile(env, draft.env, { mode: 0o600 }); + const global = path.join(this.server.stacksDir, "global.env"); + const args = [ "compose", "--project-directory", stack.fullPath, "--file", yaml ]; + if (existsSync(global)) { + args.push("--env-file", global); + } + args.push("--env-file", env); + return await action((command, timeout) => this.command([ ...args, ...command ], undefined, timeout)); + } finally { + await fs.rm(temp, { recursive: true, + force: true }); + } + } + + private async readConfig(compose: (args: string[]) => Promise, service?: string) { + try { + const config = JSON.parse(await compose([ "config", "--format", "json", ...(service ? [ "--", service ] : []) ])) as Config; + if (!config.name || !config.services || !Object.keys(config.services).length) { + throw new Error("Empty configuration"); + } + const hashes = await compose([ "config", "--hash", "*", ...(service ? [ "--", service ] : []) ]); + return { config, + hashes: Object.fromEntries(hashes.split(/\r?\n/).filter(Boolean).map(line => line.trim().split(/\s+/, 2))) }; + } catch (error) { + const stderr = typeof error === "object" && error && "stderr" in error ? String(error.stderr) : ""; + const field = stderr.match(/\b(?:services|networks|volumes|configs|secrets)\.[a-zA-Z0-9_.-]{1,180}\b/)?.[0]; + throw new ComposeValidationError(field); + } + } + + private async runtime(project: string): Promise { + const ids = (await this.command([ "container", "ls", "--all", "--quiet", "--no-trunc", "--filter", + `label=com.docker.compose.project=${project}`, "--filter", "label=com.docker.compose.oneoff=False" ])).split(/\s+/).filter(Boolean); + if (!ids.length) { + return []; + } + if (ids.length > 500 || ids.some(id => !/^[a-f0-9]{64}$/.test(id))) { + throw new ValidationError("deployTooManyContainers"); + } + const format = "{\"id\":{{json .Id}},\"name\":{{json .Name}},\"service\":{{json (index .Config.Labels \"com.docker.compose.service\")}}," + + "\"image\":{{json .Image}},\"hash\":{{json (index .Config.Labels \"com.docker.compose.config-hash\")}},\"state\":{{json .State.Status}}," + + "\"health\":{{with index .State \"Health\"}}{{json .Status}}{{else}}\"\"{{end}}}"; + const rows = await this.command([ "container", "inspect", "--format", format, "--", ...ids ]); + return rows.split(/\r?\n/).map(row => JSON.parse(row) as Runtime).sort((a, b) => a.id.localeCompare(b.id)); + } + + private runtimeDigest(rows: Runtime[]) { + return digest(rows.map(({ id, image, hash }) => [ id, image, hash ])); + } + + private async inspect(reference: string, platform?: string) { + try { + const args = [ "image", "inspect", "--format", "{{.Id}}" ]; + if (platform) { + args.push("--platform", platform); + } + const id = await this.command([ ...args, "--", reference ]); + return imageIdPattern.test(id) ? id : undefined; + } catch { + return undefined; + } + } + + withImageChanges(action: () => Promise) { + const operation = this.pullQueue.then(action); + this.pullQueue = operation.catch(() => {}); + return operation; + } + + private async prepareRecord(record: Deployment, candidates?: Map, delayHours = 0) { + await this.write(record.name); + const stack = new Stack(this.server, record.name); + if (record.draft?.isAdd ? existsSync(stack.path) : !stack.isManagedByDockge) { + throw new ValidationError("editorConflict"); + } + record.revision = record.draft?.isAdd ? undefined : stack.revision; + if (record.draft?.revision && record.draft.revision !== record.revision) { + throw new ValidationError("editorConflict"); + } + const current = await this.configure(stack, record.draft, async compose => { + const { config, hashes } = await this.readConfig(compose, record.service); + record.sourceHashes = hashes; + record.project = config.name; + record.fingerprint = digest(config); + const runtime = await this.runtime(config.name); + record.runtimeFingerprint = this.runtimeDigest(runtime); + const selection = record.service ? this.dependencies(config, record.service) : Object.keys(config.services); + const names = candidates ? selection.filter(name => candidates.has(name)) : selection; + if (!names.length) { + throw new ValidationError("deployInvalidRequest"); + } + record.phase = "pulling"; + record.changes = this.changes(record, config, runtime, names); + await this.write(record.name); + await this.withImageChanges(() => this.pull(record, compose, config, names)); + if (candidates) { + record.changes = this.changes(record, config, runtime, names); + for (const change of record.changes) { + const existing = candidates.get(change.name); + if (!existing || existing.imageIds.every(id => id === change.imageId)) { + change.action = "keep"; + } + } + record.changes = record.changes.filter(change => change.action !== "keep"); + if (!record.changes.length) { + delete this.store(record.name).pending; + await this.write(record.name); + return null; + } + record.scale = Object.fromEntries(record.changes.map(change => [ change.name, candidates.get(change.name)!.containers.length ])); + const rejected = this.store(record.name).history.find(item => item.mode === "scheduled" && item.phase === "rejected"); + if (rejected && record.changes.every(change => rejected.changes.some(old => old.name === change.name && old.imageId === change.imageId))) { + await this.withImageChanges(() => this.removePulled(record)); + delete this.store(record.name).pending; + await this.write(record.name); + return null; + } + if (delayHours) { + record.notBefore = new Date(Date.now() + delayHours * 3600000).toISOString(); + } + } else { + const pinned = this.pin(record, config, new Set(names)); + const expected = await this.withPinnedConfig(stack, pinned, async args => { + const hashes = await this.command([ ...args, "config", "--hash", "*" ]); + return Object.fromEntries(hashes.split(/\r?\n/).filter(Boolean).map(line => line.trim().split(/\s+/, 2))); + }); + record.changes = this.changes(record, config, runtime, names, expected); + } + return config; + }); + if (!current) { + return; + } + record.phase = "scanning"; + await this.write(record.name); + const images = new Map(); + for (const change of record.changes) { + if (!change.imageId || change.action === "remove") { + continue; + } + const candidate = record.images.find(image => image.id === change.imageId); + if (change.action === "keep" && !candidate?.fresh && !candidate?.retagged) { + continue; + } + const scan = images.get(change.imageId) ?? { id: change.imageId, + references: [], + services: [], + status: "pending" as const, + findings: [] }; + scan.services.push(change.name); + if (change.reference && !scan.references.includes(change.reference)) { + scan.references.push(change.reference); + } + images.set(change.imageId, scan); + } + if (images.size) { + const scan = await this.server.imageVulnerabilityScan.scanPrepared(stack, Array.from(images.values())); + record.scans = scan.images; + record.scanReportId = scan.id; + if (scan.error || scan.images.some(image => image.status !== "scanned")) { + throw new ValidationError(scan.error || "deployScanIncomplete"); + } + } + record.phase = "ready"; + await this.write(record.name); + } + + private dependencies(config: Config, service: string, names = new Set()) { + const selected = config.services[service]; + if (!selected || !Object.hasOwn(config.services, service)) { + throw new ValidationError("deployInvalidRequest"); + } + if (!names.has(service)) { + names.add(service); + const dependencies = selected.depends_on || {}; + for (const name of Array.isArray(dependencies) ? dependencies : Object.keys(dependencies)) { + if (Object.hasOwn(config.services, name)) { + this.dependencies(config, name, names); + } + } + } + return Array.from(names); + } + + private reference(config: Config, name: string) { + return config.services[name].image || `${config.name}-${name}`; + } + + private changes(record: Deployment, config: Config, runtime: Runtime[], names: string[], targetHashes?: Record) { + const result: Change[] = names.map(name => { + const reference = this.reference(config, name); + const platform = config.services[name].platform; + const imageId = record.images.find(image => image.reference === reference && image.platform === platform)?.id; + const rows = runtime.filter(row => row.service === name); + const matches = (row: Runtime) => targetHashes ? row.hash === targetHashes[name] + : row.hash === record.sourceHashes[name] || this.matchesDeployedHash(record.name, name, record.sourceHashes[name], row.hash); + const action = !rows.length ? "create" + : rows.some(row => !matches(row) || (imageId && row.image !== imageId)) ? "recreate" + : rows.some(row => row.state !== "running") ? "start" : "keep"; + return { name, + reference, + imageId, + previousImageIds: imageId ? Array.from(new Set(rows.map(row => row.image).filter(id => id !== imageId))) : undefined, + action }; + }); + if ([ "deploy", "start", "update" ].includes(record.mode)) { + for (const row of runtime) { + if (!Object.hasOwn(config.services, row.service)) { + result.push({ name: row.name.replace(/^\//, ""), + action: "remove" }); + } + } + } + return result; + } + + matchesDeployedHash(stack: string, service: string, sourceHash: string, containerHash: string) { + return Boolean(sourceHash && containerHash && this.stores.get(stack)?.history.some(record => record.phase === "deployed" + && record.sourceHashes[service] === sourceHash && record.appliedHashes?.[service] === containerHash)); + } + + private async pull(record: Deployment, compose: (args: string[], timeout?: number) => Promise, config: Config, names: string[]) { + const initial = new Set((await this.command([ "image", "ls", "--all", "--no-trunc", "--quiet" ])).split(/\s+/)); + for (const name of names) { + const service = config.services[name]; + const reference = this.reference(config, name); + const platform = service.platform; + const existing = record.images.find(image => image.reference === reference && image.platform === platform); + if (existing) { + continue; + } + const previous = await this.inspect(reference, platform); + try { + if (service.build && (!previous || record.mode === "deploy" || record.mode === "update")) { + await compose([ "build", "--", name ], 10 * 60 * 1000); + } else if (service.image && service.pull_policy !== "never" && (!service.build || !previous) + && (!previous || service.pull_policy === "always" || record.mode === "update" || record.mode === "scheduled")) { + await compose([ "pull", "--policy", "always", "--ignore-buildable", "--", name ], 10 * 60 * 1000); + } + } finally { + const id = await this.inspect(reference, platform); + if (id) { + record.images.push({ reference, + platform, + id, + previous, + fresh: !initial.has(id), + retagged: previous !== id }); + await this.write(record.name); + } + } + if (!record.images.some(image => image.reference === reference && image.platform === platform)) { + throw new ValidationError("deployImageMissing"); + } + } + } + + async decide(value: unknown, id: unknown, approve: unknown) { + await this.initialize(); + const name = this.name(value); + const previous = this.stores.get(name)?.pending; + if (previous && previous.id === id && [ "ready", "failed" ].includes(previous.phase)) { + await this.jobs.get(name); + } + const record = this.stores.get(name)?.pending; + if (!record || record.id !== id || typeof approve !== "boolean" || this.jobs.has(name) + || ![ "ready", "failed" ].includes(record.phase)) { + throw new ValidationError("deployInvalidDecision"); + } + if (approve && (record.phase !== "ready" || (record.notBefore && Date.parse(record.notBefore) > Date.now()))) { + throw new ValidationError("deployInvalidDecision"); + } + record.phase = "applying"; + record.approved = approve; + this.run(record, () => Stack.withOperation(this.server, name, async () => { + await this.write(name); + if (approve) { + await this.apply(record); + record.phase = "deployed"; + } else { + record.cleanup = await this.withImageChanges(() => this.removePulled(record)); + if (record.scanReportId) { + this.server.imageVulnerabilityScan.forget(record.name, record.scanReportId); + } + record.phase = "rejected"; + } + record.finishedAt = new Date().toISOString(); + const store = this.store(name); + store.history.unshift(record); + store.history = store.history.slice(0, historyLimit); + delete store.pending; + await this.write(name); + void this.server.sendStackList(); + })); + return publicRecord(record); + } + + private async apply(record: Deployment) { + const stack = new Stack(this.server, record.name); + if (record.draft?.isAdd ? existsSync(stack.path) : !stack.isManagedByDockge || stack.revision !== record.revision) { + throw new ValidationError("editorConflict"); + } + const { config } = await this.configure(stack, record.draft, compose => this.readConfig(compose, record.service)); + if (digest(config) !== record.fingerprint || this.runtimeDigest(await this.runtime(config.name)) !== record.runtimeFingerprint) { + throw new ValidationError("deployPlanChanged"); + } + const names = new Set(record.changes.filter(change => change.action !== "remove").map(change => change.name)); + const pinned = this.pin(record, config, names); + for (const name of names) { + const service = config.services[name]; + const image = record.images.find(item => item.reference === this.reference(config, name) && item.platform === service.platform); + if (!image || await this.inspect(image.id, image.platform) !== image.id) { + throw new ValidationError("deployImageMissing"); + } + } + if (record.draft) { + const draft = new Stack(this.server, record.name, record.draft.yaml, record.draft.env); + await draft.save(record.draft.isAdd, record.revision); + } else { + record.draft = { yaml: stack.composeYAML, + env: stack.composeENV, + isAdd: false }; + } + await this.withPinnedConfig(stack, pinned, async args => { + const selected = record.mode === "scheduled" ? [ ...names ] : record.service ? [ record.service ] : []; + const scale = Object.entries(record.scale || {}).flatMap(([ name, count ]) => [ "--scale", `${name}=${count}` ]); + const flags = record.mode === "scheduled" ? [ "--no-deps", ...scale ] : record.service ? [] : [ "--remove-orphans" ]; + await this.command([ ...args, "up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout", "120", + ...flags, ...(selected.length ? [ "--", ...selected ] : []) ], stack.fullPath, 180000); + const runtime = await this.runtime(config.name); + record.appliedHashes = Object.fromEntries(runtime.filter(row => names.has(row.service)).map(row => [ row.service, row.hash ])); + }); + } + + private pin(record: Deployment, config: Config, names: Set) { + const services = Object.fromEntries(Object.entries(config.services).map(([ name, service ]) => { + if (!names.has(name)) { + return [ name, service ]; + } + const image = record.images.find(item => item.reference === this.reference(config, name) && item.platform === service.platform); + if (!image) { + throw new ValidationError("deployImageMissing"); + } + return [ name, { ...service, + image: image.id, + pull_policy: "never" }]; + })); + return { ...config, + services }; + } + + private async withPinnedConfig(stack: Stack, config: Config, action: (args: string[]) => Promise) { + const temp = await fs.mkdtemp(path.join(this.directory, ".apply-")); + try { + const file = path.join(temp, "compose.json"); + // The Compose config renderer already escapes literal dollars for re-reading. + await fs.writeFile(file, JSON.stringify(config), { mode: 0o600 }); + return await action([ "compose", "--project-directory", stack.fullPath, "--file", file ]); + } finally { + await fs.rm(temp, { recursive: true, + force: true }); + } + } + + private async removePulled(record: Deployment) { + const shared = this.protectedImages(record.id); + const fresh = new Set(); + for (const image of record.images) { + if (image.fresh) { + fresh.add(image.id); + } + if (!image.retagged || !image.previous || image.reference.includes("@") || imageIdPattern.test(image.reference) + || await this.inspect(image.reference, image.platform) !== image.id) { + continue; + } + await this.command([ "image", "tag", "--", image.previous, image.reference ]).catch(() => {}); + } + let removed = 0; + for (const id of fresh) { + if (shared.has(id)) { + continue; + } + try { + // Docker performs the final reference check, including stopped containers. + await this.command([ "image", "rm", "--no-prune", "--", id ]); + removed++; + } catch { + // The image may have acquired another tag or container reference. + } + } + return { removed, + retained: fresh.size - removed }; + } + + protectedImages(except?: string) { + const ids = new Set(); + for (const store of this.stores.values()) { + const deployments = store.history.filter(item => item.phase === "deployed").slice(0, 2); + if (store.pending?.id !== except && store.pending) { + deployments.push(store.pending); + } + for (const deployment of deployments) { + for (const image of deployment.images) { + ids.add(image.id); + if (image.previous && deployment === store.pending) { + ids.add(image.previous); + } + } + } + } + return ids; + } + + attention() { + return Array.from(this.stores.entries()).flatMap(([ stack, store ]) => { + if (store.pending?.phase === "ready" || store.pending?.phase === "failed") { + return [{ stack, + kind: store.pending.phase === "ready" ? "deployAttentionApproval" : "deployAttentionFailed" }]; + } + return []; + }); + } +} diff --git a/backend/stack.ts b/backend/stack.ts index 7b41a7e..4ddb204 100644 --- a/backend/stack.ts +++ b/backend/stack.ts @@ -13,7 +13,6 @@ import { CREATED_STACK, EXITED, getCombinedTerminalName, getComposeTerminalName, getContainerExecTerminalName, - PROGRESS_TERMINAL_ROWS, RUNNING, TERMINAL_ROWS, UNKNOWN } from "../common/util-common"; @@ -269,19 +268,6 @@ export class Stack { } } - async deploy(socket : DockgeSocket) : Promise { - const terminalName = getComposeTerminalName(socket.endpoint, this.name); - let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("config", "--quiet"), this.path); - if (exitCode !== 0) { - throw new ValidationError("editorComposeInvalid"); - } - exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path); - if (exitCode !== 0) { - throw new Error("Failed to deploy, please check the terminal output for more information."); - } - return exitCode; - } - async delete(socket: DockgeSocket) : Promise { const terminalName = getComposeTerminalName(socket.endpoint, this.name); let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("down", "--remove-orphans"), this.path); @@ -487,15 +473,6 @@ export class Stack { return options; } - async start(socket: DockgeSocket) { - const terminalName = getComposeTerminalName(socket.endpoint, this.name); - let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path); - if (exitCode !== 0) { - throw new Error("Failed to start, please check the terminal output for more information."); - } - return exitCode; - } - async stop(socket: DockgeSocket) : Promise { const terminalName = getComposeTerminalName(socket.endpoint, this.name); let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("stop"), this.path); @@ -523,27 +500,6 @@ export class Stack { return exitCode; } - async update(socket: DockgeSocket) { - const terminalName = getComposeTerminalName(socket.endpoint, this.name); - let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("pull"), this.path); - if (exitCode !== 0) { - throw new Error("Failed to pull, please check the terminal output for more information."); - } - - // If the stack is not running, we don't need to restart it - await this.updateStatus(); - log.debug("update", "Status: " + this.status); - if (this.status !== RUNNING) { - return exitCode; - } - - exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path); - if (exitCode !== 0) { - throw new Error("Failed to restart, please check the terminal output for more information."); - } - return exitCode; - } - async joinCombinedTerminal(socket: DockgeSocket) { const terminalName = getCombinedTerminalName(socket.endpoint, this.name); const terminal = Terminal.getOrCreateTerminal(this.server, terminalName, "docker", this.getComposeOptions("logs", "-f", "--tail", "100"), this.path); @@ -580,7 +536,7 @@ export class Stack { let statusList = new Map>(); try { - let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--no-trunc", "--orphans=false", "--format", "json"), { + let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--all", "--no-trunc", "--orphans=false", "--format", "json"), { cwd: this.path, encoding: "utf-8", }); @@ -591,7 +547,7 @@ export class Stack { let lines = res.stdout?.toString().split("\n"); - const addLine = (obj: { ID: string, Service: string, State: string, Name: string, Health: string }) => { + const addLine = (obj: { ID: string, Service: string, State: string, Name: string, Health: string, ExitCode?: number, Publishers?: unknown[] }) => { if (!statusList.has(obj.Service)) { statusList.set(obj.Service, []); } @@ -599,7 +555,9 @@ export class Stack { id: obj.ID, state: obj.State, status: obj.Health || obj.State, - name: obj.Name + name: obj.Name, + exitCode: obj.ExitCode, + ports: obj.Publishers ?? [], }); }; @@ -622,16 +580,6 @@ export class Stack { } } - async startService(socket: DockgeSocket, serviceName: string) { - const terminalName = getComposeTerminalName(socket.endpoint, this.name); - const exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", serviceName ], this.path); - if (exitCode !== 0) { - throw new Error(`Failed to start service ${serviceName}, please check logs for more information.`); - } - - return exitCode; - } - async stopService(socket: DockgeSocket, serviceName: string): Promise { const terminalName = getComposeTerminalName(socket.endpoint, this.name); const exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "stop", serviceName ], this.path); diff --git a/components.json b/components.json index 67bb0c7..6b9e535 100644 --- a/components.json +++ b/components.json @@ -5,13 +5,13 @@ "tailwind": { "config": "", "css": "frontend/src/styles/theme.css", - "baseColor": "mist", + "baseColor": "zinc", "cssVariables": true }, - "iconLibrary": "phosphor", + "iconLibrary": "remixicon", "rtl": false, - "menuColor": "default", - "menuAccent": "bold", + "menuColor": "inverted-translucent", + "menuAccent": "subtle", "aliases": { "components": "@/components", "ui": "@/components/ui", diff --git a/frontend/src/components/ActionDialog.vue b/frontend/src/components/ActionDialog.vue index 92777ac..c4b582c 100644 --- a/frontend/src/components/ActionDialog.vue +++ b/frontend/src/components/ActionDialog.vue @@ -12,7 +12,7 @@ {{ $t("cancel") }} - {{ action }} + {{ action }} @@ -28,10 +28,14 @@ export default { action: { type: String, required: true }, destructive: Boolean, + disabled: Boolean, }, emits: [ "update:modelValue", "confirm" ], methods: { confirm() { + if (this.disabled) { + return; + } this.$emit("update:modelValue", false); this.$emit("confirm"); }, diff --git a/frontend/src/components/ArrayInput.vue b/frontend/src/components/ArrayInput.vue deleted file mode 100644 index a90e66e..0000000 --- a/frontend/src/components/ArrayInput.vue +++ /dev/null @@ -1,124 +0,0 @@ - - - diff --git a/frontend/src/components/ArraySelect.vue b/frontend/src/components/ArraySelect.vue deleted file mode 100644 index 7ce7223..0000000 --- a/frontend/src/components/ArraySelect.vue +++ /dev/null @@ -1,102 +0,0 @@ - - - diff --git a/frontend/src/components/AuthCard.vue b/frontend/src/components/AuthCard.vue index 4d83926..3f8b0b7 100644 --- a/frontend/src/components/AuthCard.vue +++ b/frontend/src/components/AuthCard.vue @@ -1,13 +1,14 @@ diff --git a/frontend/src/components/ComposeCollection.vue b/frontend/src/components/ComposeCollection.vue new file mode 100644 index 0000000..e978db3 --- /dev/null +++ b/frontend/src/components/ComposeCollection.vue @@ -0,0 +1,165 @@ + + + diff --git a/frontend/src/components/ComposeField.vue b/frontend/src/components/ComposeField.vue new file mode 100644 index 0000000..50ee6b9 --- /dev/null +++ b/frontend/src/components/ComposeField.vue @@ -0,0 +1,107 @@ + + + diff --git a/frontend/src/components/Container.vue b/frontend/src/components/Container.vue index c8a8e9e..37deb40 100644 --- a/frontend/src/components/Container.vue +++ b/frontend/src/components/Container.vue @@ -1,6 +1,6 @@ - + @@ -60,30 +69,13 @@ -
-
- {{ $t("dockerImage") }} - -
-
- {{ $t("restartPolicy") }} - - - - - - -
-
-

{{ field.plural ? $tc(field.label, 2) : $t(field.label) }}

- -
-
-

{{ $tc("network", 2) }}

- {{ $t("NoNetworksAvailable") }} - -
-
+ + @@ -91,18 +83,15 @@ diff --git a/frontend/src/components/HostAttention.vue b/frontend/src/components/HostAttention.vue new file mode 100644 index 0000000..d8563ad --- /dev/null +++ b/frontend/src/components/HostAttention.vue @@ -0,0 +1,96 @@ + + + diff --git a/frontend/src/components/Login.vue b/frontend/src/components/Login.vue index c3ed575..b3f2b43 100644 --- a/frontend/src/components/Login.vue +++ b/frontend/src/components/Login.vue @@ -8,7 +8,12 @@
{{ $t("Password") }} - +
+ + + + +
@@ -35,6 +40,7 @@ export default { processing: false, username: "", password: "", + showPassword: false, token: "", res: null, tokenRequired: false, diff --git a/frontend/src/components/NetworkInput.vue b/frontend/src/components/NetworkInput.vue index 7a4e605..0ad00b8 100644 --- a/frontend/src/components/NetworkInput.vue +++ b/frontend/src/components/NetworkInput.vue @@ -1,182 +1,104 @@ diff --git a/frontend/src/components/ServiceEditor.vue b/frontend/src/components/ServiceEditor.vue new file mode 100644 index 0000000..c462ce6 --- /dev/null +++ b/frontend/src/components/ServiceEditor.vue @@ -0,0 +1,391 @@ + + + diff --git a/frontend/src/components/StackConfigEditor.vue b/frontend/src/components/StackConfigEditor.vue index 35bb716..242ce10 100644 --- a/frontend/src/components/StackConfigEditor.vue +++ b/frontend/src/components/StackConfigEditor.vue @@ -12,12 +12,6 @@ {{ envErrorCount }} -
- {{ $t("editorFind") }} - {{ $t("editorFormat") }} - {{ $t("editorWrap") }} - {{ $t(fullscreen ? "editorExitFullscreen" : "editorFullscreen") }} -
diff --git a/frontend/src/components/StackDeployments.vue b/frontend/src/components/StackDeployments.vue new file mode 100644 index 0000000..87610ff --- /dev/null +++ b/frontend/src/components/StackDeployments.vue @@ -0,0 +1,251 @@ + + + diff --git a/frontend/src/components/StackList.vue b/frontend/src/components/StackList.vue index 0bb8bff..542c83f 100644 --- a/frontend/src/components/StackList.vue +++ b/frontend/src/components/StackList.vue @@ -19,7 +19,7 @@ - + @@ -77,7 +77,7 @@ diff --git a/frontend/src/pages/ContainerFiles.vue b/frontend/src/pages/ContainerFiles.vue index 142cb65..bd8adba 100644 --- a/frontend/src/pages/ContainerFiles.vue +++ b/frontend/src/pages/ContainerFiles.vue @@ -1,12 +1,14 @@