diff --git a/.dockerignore b/.dockerignore index 1adf5fe..41ce081 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,7 +9,7 @@ tmp # Docker extra docker -frontend +frontend-dist .editorconfig .eslintrc.cjs .git diff --git a/.gitea/workflows/docker-image.yml b/.gitea/workflows/docker-image.yml new file mode 100644 index 0000000..b773755 --- /dev/null +++ b/.gitea/workflows/docker-image.yml @@ -0,0 +1,46 @@ +name: Docker image + +on: + push: + branches: [master] + workflow_dispatch: + +jobs: + publish: + runs-on: ubuntu-latest + timeout-minutes: 35 + container: + image: docker:28-cli + env: + REGISTRY: git.jfritzsche.de + IMAGE: git.jfritzsche.de/jf/dockge + steps: + - name: Install checkout dependencies + run: apk add --no-cache git nodejs + + - name: Check out source + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + persist-credentials: false + + - name: Build Linux image + run: | + set -eu + docker buildx build --platform linux/amd64 --target release --load \ + --provenance=false --sbom=false \ + --label "org.opencontainers.image.source=$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" \ + --label "org.opencontainers.image.revision=$GITHUB_SHA" \ + --tag "$IMAGE:sha-$GITHUB_SHA" --tag "$IMAGE:latest" \ + --file docker/Dockerfile . + + - name: Publish commit and latest tags + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + run: | + set -eu + export DOCKER_CONFIG + DOCKER_CONFIG=$(mktemp -d) + trap 'rm -rf "$DOCKER_CONFIG"' EXIT + printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" --username jf --password-stdin + docker push "$IMAGE:sha-$GITHUB_SHA" + docker push "$IMAGE:latest" diff --git a/README.md b/README.md index 21f6de8..7a09efd 100644 --- a/README.md +++ b/README.md @@ -1,207 +1,178 @@ -
- -
+# Dockge · Weapie-Fork -# Dockge +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) -A fancy, easy-to-use and reactive self-hosted docker compose.yaml stack-oriented manager. +![Stack-Übersicht mit zwei laufenden Diensten im Demo-Stack](docs/images/stack-uebersicht.png) -[![GitHub Repo stars](https://img.shields.io/github/stars/louislam/dockge?logo=github&style=flat)](https://github.com/louislam/dockge) [![Docker Pulls](https://img.shields.io/docker/pulls/louislam/dockge?logo=docker)](https://hub.docker.com/r/louislam/dockge/tags) [![Docker Image Version (latest semver)](https://img.shields.io/docker/v/louislam/dockge/latest?label=docker%20image%20ver.)](https://hub.docker.com/r/louislam/dockge/tags) [![GitHub last commit (branch)](https://img.shields.io/github/last-commit/louislam/dockge/master?logo=github)](https://github.com/louislam/dockge/commits/master/) +[Installation](#installation) · [Stacks](#stacks-verwalten) · [Updates und Scans](#updates-und-schwachstellenscans) · [Images und Volumes](#images-und-volumes) · [Datei-Explorer](#datei-explorer) · [Betrieb](#betrieb-und-fehlerbehebung) - +## Installation -View Video: https://youtu.be/AWAlOQeNpgU?t=48 +Für die Installation brauchst du den Quellcode dieses Forks und einen erreichbaren Docker-Daemon für **Linux-Container**. Unter Linux installierst du Docker Engine mit dem Compose-Plugin. Unter Windows gehört Compose zu Docker Desktop. Der Build benötigt Internetzugriff für die Basis-Images, npm-Pakete und Grype. Das Image enthält Grype für **amd64** und **arm64**. [Docker Engine](https://docs.docker.com/engine/install/) · [Docker Compose](https://docs.docker.com/compose/install/) · [Docker Desktop für Windows](https://docs.docker.com/desktop/setup/install/windows-install/) -## ⭐ Features +Führe die Befehle im Projektordner mit der [compose.yaml](compose.yaml) aus. Compose baut aus diesem Quellcode das lokale Image `dockge:local`. -- 🧑‍💼 Manage your `compose.yaml` files - - Create/Edit/Start/Stop/Restart/Delete - - Update Docker Images -- ⌨️ Interactive Editor for `compose.yaml` -- 🦦 Interactive Web Terminal -- 🕷️ (1.4.0 🆕) Multiple agents support - You can manage multiple stacks from different Docker hosts in one single interface -- 🏪 Convert `docker run ...` commands into `compose.yaml` -- 📙 File based structure - Dockge won't kidnap your compose files, they are stored on your drive as usual. You can interact with them using normal `docker compose` commands +### Fertiges Image aus Gitea - +Für Linux auf **amd64** stellt Gitea das Image `git.jfritzsche.de/jf/dockge:latest` bereit. Führe zuerst die Vorbereitung des Stack-Verzeichnisses für dein Betriebssystem aus. Lege dann neben der `compose.yaml` eine Datei `compose.registry.yaml` mit folgendem Inhalt an. -- 🚄 Reactive - Everything is just responsive. Progress (Pull/Up/Down) and terminal output are in real-time -- 🐣 Easy-to-use & fancy UI - If you love Uptime Kuma's UI/UX, you will love this one too - -![](https://github.com/louislam/dockge/assets/1336778/89fc1023-b069-42c0-a01c-918c495f1a6a) - -## 🔧 How to Install - -Requirements: -- [Docker](https://docs.docker.com/engine/install/) 20+ / Podman -- (Podman only) podman-docker (Debian: `apt install podman-docker`) -- OS: - - Major Linux distros that can run Docker/Podman such as: - - ✅ Ubuntu - - ✅ Debian (Bullseye or newer) - - ✅ Raspbian (Bullseye or newer) - - ✅ CentOS - - ✅ Fedora - - ✅ ArchLinux - - ❌ Debian/Raspbian Buster or lower is not supported - - ❌ Windows (Will be supported later) -- Arch: armv7, arm64, amd64 (a.k.a x86_64) - -### Basic - -- Default Stacks Directory: `/opt/stacks` -- Default Port: 5001 - -``` -# Create directories that store your stacks and stores Dockge's stack -mkdir -p /opt/stacks /opt/dockge -cd /opt/dockge - -# Download the compose.yaml -curl https://raw.githubusercontent.com/louislam/dockge/master/compose.yaml --output compose.yaml - -# Start the server -docker compose up -d - -# If you are using docker-compose V1 or Podman -# docker-compose up -d -``` - -Dockge is now running on http://localhost:5001 - -### Advanced - -If you want to store your stacks in another directory, you can generate your compose.yaml file by using the following URL with custom query strings. - -``` -# Download your compose.yaml -curl "https://dockge.kuma.pet/compose.yaml?port=5001&stacksPath=/opt/stacks" --output compose.yaml -``` - -- port=`5001` -- stacksPath=`/opt/stacks` - -Also, once compose is generated/downloaded, add the `PUID` and `PGID` section below to your compose `environment:` section to set stack ownership, otherwise default is `root` - -``` - # Both PUID and PGID must be set for it to do anything - - PUID=1000 # Set the stack file/dir ownership to this user - - PGID=1000 # Set the stack file/dir ownership to this group -``` - -Interactive compose.yaml generator is available on: -https://dockge.kuma.pet - -### -OR- -Copy and paste your compose from the following: - -If you want to store your stacks in another directory, you can change the `DOCKGE_STACKS_DIR` environment variable and volumes. - -compose: -``` +~~~yaml services: dockge: - image: louislam/dockge:1 - restart: unless-stopped - ports: - # Host Port:Container Port - - 5001:5001 - volumes: - - /var/run/docker.sock:/var/run/docker.sock - - ./data:/app/data - - # If you want to use private registries, you need to share the auth file with Dockge: - # - /root/.docker/:/root/.docker + image: git.jfritzsche.de/jf/dockge:latest +~~~ - # Stacks Directory - # Your stacks directory in the host (The paths inside container must be the same as the host) - # ⚠️ If you did it wrong, your data could end up be written into a wrong path. - # ✔️ CORRECT EXAMPLE: - /my-stacks:/my-stacks (Both paths match) - # ❌ WRONG EXAMPLE: - /docker:/my-stacks (Both paths do not match) - - /opt/stacks:/opt/stacks - environment: - # Tell Dockge where your stacks directory is - - DOCKGE_STACKS_DIR=/opt/stacks - # Both PUID and PGID must be set for it to do anything - - PUID=1000 # Set the stack file/dir ownership to this user - - PGID=1000 # Set the stack file/dir ownership to this group -``` +~~~sh +docker compose -f compose.yaml -f compose.registry.yaml pull dockge +docker compose -f compose.yaml -f compose.registry.yaml up -d --no-build +~~~ -## How to Update +Mit denselben Befehlen aktualisierst du später die Installation. Der [Gitea-Workflow](.gitea/workflows/docker-image.yml) veröffentlicht bei Änderungen an `master` die Tags `latest` und `sha-`. Mit einem Commit-Tag kannst du einen bestimmten Build installieren. [Gitea Container Registry](https://docs.gitea.com/usage/packages/container/) -```bash -cd /opt/dockge -docker compose pull && docker compose up -d -``` +### Linux -## Screenshots +Das Stack-Verzeichnis ist standardmäßig `/opt/stacks`. Verwende bei einer bestehenden Installation den bisherigen absoluten Pfad. -![](https://github.com/louislam/dockge/assets/1336778/e7ff0222-af2e-405c-b533-4eab04791b40) +~~~bash +docker version +docker compose version +sudo mkdir -p /opt/stacks +docker compose config --quiet +docker compose up -d --build +docker compose ps +~~~ +### Windows mit Docker Desktop -![](https://github.com/louislam/dockge/assets/1336778/7139e88c-77ed-4d45-96e3-00b66d36d871) +Starte Docker Desktop mit dem WSL-2-Backend im Modus für Linux-Container. Öffne PowerShell im Projektordner auf einem lokalen Laufwerk, das Docker Desktop einbinden kann. Das Beispiel legt `stacks` neben die Compose-Datei und verwendet den Linux-Pfad, unter dem Docker Desktop das Windows-Laufwerk im Daemon bereitstellt. -![](https://github.com/louislam/dockge/assets/1336778/f019944c-0e87-405b-a1b8-625b35de1eeb) +~~~powershell +docker version +docker compose version -![](https://github.com/louislam/dockge/assets/1336778/a4478d23-b1c4-4991-8768-1a7cad3472e3) +$projectPath = (Get-Location).Path +$drive = $projectPath.Substring(0, 1).ToLowerInvariant() +$pathOnDrive = $projectPath.Substring(2).Replace('\', '/').TrimEnd('/') +New-Item -ItemType Directory -Path (Join-Path $projectPath 'stacks') -Force | Out-Null +$env:DOCKGE_STACKS_DIR = "/run/desktop/mnt/host/$drive$pathOnDrive/stacks" +docker compose config --quiet +docker compose up -d --build +docker compose ps +~~~ -## Motivations +Für weitere PowerShell-Sitzungen kannst du den Wert von `$env:DOCKGE_STACKS_DIR` als Zeile `DOCKGE_STACKS_DIR=` in die `.env` des **Dockge-Projektordners** eintragen. Das Projekt unter `C:\Projekte\dockge` ergibt beispielsweise `DOCKGE_STACKS_DIR=/run/desktop/mnt/host/c/Projekte/dockge/stacks`. [Docker Desktop und WSL](https://docs.docker.com/desktop/features/wsl/) -- I have been using Portainer for some time, but for the stack management, I am sometimes not satisfied with it. For example, sometimes when I try to deploy a stack, the loading icon keeps spinning for a few minutes without progress. And sometimes error messages are not clear. -- Try to develop with ES Module + TypeScript +### Erster Start -If you love this project, please consider giving it a ⭐. +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. + ~~~yaml + services: + web: + image: nginx:alpine + restart: unless-stopped + ports: + - "127.0.0.1:8081:80" + ~~~ -## 🗣️ Community and Contribution +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). -### Bug Report -https://github.com/louislam/dockge/issues +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/) -### Ask for Help / Discussions -https://github.com/louislam/dockge/discussions +## Stacks verwalten -### Translation -If you want to translate Dockge into your language, please read [Translation Guide](https://github.com/louislam/dockge/blob/master/frontend/src/lang/README.md) +- **Ü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. +- **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. -### Create a Pull Request +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. -Be sure to read the [guide](https://github.com/louislam/dockge/blob/master/CONTRIBUTING.md), as we don't accept all types of pull requests and don't want to waste your time. +Ü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. -## FAQ +### Mehrere Docker-Hosts -#### "Dockge"? +Starte auf jedem zusätzlichen Host eine Dockge-Instanz mit Zugriff auf dessen Docker-Socket. Wähle auf der Startseite deiner Hauptinstanz **Agent hinzufügen** und trage die für sie erreichbare URL sowie die Zugangsdaten der Zielinstanz ein. Bei mehreren verbundenen Hosts kannst du Stacks, Container, Images und Volumes nach Host auswählen. Update- und Bereinigungszeitpläne laufen auf der Instanz, die den jeweiligen Docker-Host verwaltet. -"Dockge" is a coinage word which is created by myself. I originally hoped it sounds like `Dodge`, but apparently many people called it `Dockage`, it is also acceptable. +## Updates und Schwachstellenscans -The naming idea came from Twitch emotes like `sadge`, `bedge` or `wokege`. They all end in `-ge`. +![Stack-Wartung mit Uhrzeit, Wartezeit und Grype-Scanbericht](docs/images/wartung.png) -#### Can I manage a single container without `compose.yaml`? +- **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. +- **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/) -The main objective of Dockge is to try to use the docker `compose.yaml` for everything. If you want to manage a single container, you can just use Portainer or Docker CLI. +## Images und Volumes -#### Can I manage existing stacks? +Unter **Einstellungen → Images** siehst du Tags, Größe, Erstellungsdatum und die Container, die ein Image verwenden. Über **Details** kannst du einen Tag mit dem Registry-Stand vergleichen. Kann Dockge die Registry oder die passende Plattform nicht eindeutig prüfen, zeigt es einen unbekannten Status an. -Yes, you can. However, you need to move your compose file into the stacks directory: +![Image-Verwaltung mit verwendeten und ungenutzten Images sowie Tag-Details](docs/images/images.png) -1. Stop your stack -2. Move your compose file into `/opt/stacks//compose.yaml` -3. In Dockge, click the " Scan Stacks Folder" button in the top-right corner's dropdown menu -4. Now you should see your stack in the list +Unter **Einstellungen → Volumes** siehst du den Treiber, den Nutzungsstatus und die referenzierenden Container. Bei beiden Listen zählen auch **gestoppte** Container als Referenzen. -#### Is Dockge a Portainer replacement? +![Volume-Verwaltung mit verwendetem und ungenutztem Volume](docs/images/volumes.png) -Yes or no. Portainer provides a lot of Docker features. While Dockge is currently only focusing on docker-compose with a better user interface and better user experience. +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. -If you want to manage your container with docker-compose only, the answer may be yes. +> **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/) -If you still need to manage something like docker networks, single containers, the answer may be no. +## Datei-Explorer -#### Can I install both Dockge and Portainer? +Öffne **Docker-Container → Dateien** bei einem laufenden Container. Der gleiche Einstieg steht im Stack beim jeweiligen Dienst zur Verfügung. Der Explorer bietet Ordnernavigation, Suche, Uploads, Downloads und den Download von Ordnern als TAR-Archiv. Du kannst Ordner und Dateien anlegen, kopieren, umbenennen, verschieben und löschen. Textdateien lassen sich direkt bearbeiten. -Yes, you can. +![Datei-Explorer im Ordner /srv/site eines laufenden Demo-Containers](docs/images/datei-explorer.png) -## Others +Der Explorer benötigt die mitgelieferten Shell-Werkzeuge des Zielcontainers, insbesondere `sh` und für Ordnerarchive `tar`. Pro Datei oder Archiv gilt ein Transferlimit von **32 MiB**, für den Texteditor **512 KiB**. Änderungen in der beschreibbaren Container-Schicht können beim Ersetzen des Containers verloren gehen. Lege dauerhaft benötigte Dateien in einem Volume oder Bind-Mount ab. [Docker-Volumes](https://docs.docker.com/engine/storage/volumes/) -Dockge is built on top of [Compose V2](https://docs.docker.com/compose/migrate/). `compose.yaml` also known as `docker-compose.yml`. +## Betrieb und Fehlerbehebung + +| Speicherort | Inhalt | +| --- | --- | +| `./data` → `/app/data` | Dockge-Datenbank mit Konto, Einstellungen und Agent-Konfiguration sowie der Cache für aktualisierte Grype-Versionen | +| `DOCKGE_STACKS_DIR` | Stack-Ordner mit Compose-Dateien, Umgebungsvariablen und Update-Regeln | +| Docker-Volume `grype-db` | Lokale Schwachstellendatenbank. Docker Compose versieht den Volume-Namen mit dem Projektnamen. | +| Stack-eigene Docker-Volumes und Bind-Mounts | Anwendungsdaten der bereitgestellten Dienste | + +Sichere für einen Umzug die Dockge-Daten, das Stack-Verzeichnis und die jeweiligen Anwendungsdaten. Halte Dockge für eine konsistente Kopie seiner SQLite-Datenbank an. Setze beim Umzug `DOCKGE_STACKS_DIR` auf den passenden Pfad. Quell- und Zielpfad des Stack-Bind-Mounts müssen identisch sein, damit der Docker-Daemon Stack-Pfade und relative Mounts auflösen kann. [Compose-Konfiguration](compose.yaml) + +### Dockge aktualisieren und anhalten + +Aktualisiere den lokalen Quellcode des Forks. Baue und starte Dockge anschließend im selben Projektordner neu. + +~~~sh +docker compose up -d --build +docker compose ps +~~~ + +Mit `docker compose stop` hältst du Dockge an. `docker compose down` entfernt seinen Container und sein Compose-Netzwerk. `docker compose down --volumes` entfernt zusätzlich das Grype-Datenbank-Volume. Die über Dockge bereitgestellten Stacks sind eigenständige Compose-Projekte. [Docker Compose down](https://docs.docker.com/reference/cli/docker/compose/down/) + +### Weitere Einstellungen + +Unter **Allgemein** legst du den primären Hostnamen für Links zu veröffentlichten Container-Ports fest. **Erscheinungsbild** steuert Sprache und Farbschema. Unter **Sicherheit** kannst du dein Passwort ändern. Die separate **Konsole** für Docker-Befehle ist standardmäßig deaktiviert. Die Umgebungsvariable `DOCKGE_ENABLE_CONSOLE=true` im Dockge-Dienst schaltet sie frei. + +### Häufige Probleme + +| Problem | Prüfung | +| --- | --- | +| Docker oder Compose antwortet nicht | Prüfe `docker version` und `docker compose version`. Unter Windows muss Docker Desktop laufen und Linux-Container verwenden. | +| Port 5001 ist belegt | Prüfe mit `docker ps`, welche Instanz den Port nutzt. Passe bei einer zweiten Instanz den Host-Port in `compose.yaml` an. | +| Stack erscheint nicht | Kontrolliere `DOCKGE_STACKS_DIR` und die Unterordner mit Compose-Dateien. Scanne den Stack-Ordner danach erneut. | +| Grype-Scan meldet einen Datenbankfehler | Prüfe freien Docker-Speicher, Netzwerkzugriff auf `grype.anchore.io` und den Datenbankstatus mit `docker compose exec dockge grype db status`. | +| Dockge startet nicht | Lies die Ausgabe von `docker compose logs --tail=100 dockge`. | +| Passwort vergessen | Führe im laufenden Dockge-Container `docker compose exec dockge npm run reset-password` aus. | + +## Entwicklung + +Für lokale Änderungen benötigt das Projekt Node.js ab **22.14**. Docker muss für Stack-Funktionen verfügbar sein. `npm run dev` startet Frontend und Backend im Entwicklungsmodus. `npm run build:frontend` erstellt das Frontend für die Auslieferung. [Projekt-Skripte](package.json) + +~~~sh +npm ci +npm run check-ts +npm run dev +~~~ + +## Lizenz + +[MIT](LICENSE) · Ursprünglich entwickelt von Louis Lam, als Fork weitergepflegt von **Weapie**. diff --git a/backend/agent-socket-handlers/container-management-socket-handler.ts b/backend/agent-socket-handlers/container-management-socket-handler.ts new file mode 100644 index 0000000..61803d8 --- /dev/null +++ b/backend/agent-socket-handlers/container-management-socket-handler.ts @@ -0,0 +1,28 @@ +import { AgentSocketHandler } from "../agent-socket-handler"; +import type { DockgeServer } from "../dockge-server"; +import { callbackError, callbackResult, checkLogin, DockgeSocket, ValidationError } from "../util-server"; +import type { AgentSocket } from "../../common/agent-socket"; + +export class ContainerManagementSocketHandler extends AgentSocketHandler { + create(socket: DockgeSocket, server: DockgeServer, agentSocket: AgentSocket) { + const on = (event: string, fallback: string, action: (...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 action(...args) }, callback); + } catch (error) { + callbackError(error instanceof ValidationError ? error : new Error(fallback), callback); + } + }); + }; + + on("listHostContainers", "containerInventoryFailed", async () => ({ items: await server.containerManagement.list() })); + 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 c464dad..32c0601 100644 --- a/backend/agent-socket-handlers/docker-socket-handler.ts +++ b/backend/agent-socket-handlers/docker-socket-handler.ts @@ -262,13 +262,26 @@ export class DockerSocketHandler extends AgentSocketHandler { } }); - // down stack - onStackMutation("setStackAutoUpdate", async (name, enabled, callback) => { - if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name) || typeof enabled !== "boolean") { + agentSocket.on("getStackAutoUpdate", async (name: unknown, callback) => { + try { + checkLogin(socket); + if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) { + throw new ValidationError("autoUpdateUnavailable"); + } + const stack = await Stack.getStack(server, name); + callbackResult({ ok: true, + autoUpdate: await server.stackAutoUpdate.getPolicy(stack) }, callback); + } catch (error) { + callbackError(error, callback); + } + }); + + onStackMutation("setStackAutoUpdate", async (name, schedule, callback) => { + if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) { throw new ValidationError("Invalid automatic update settings."); } const stack = await Stack.getStack(server, name); - const autoUpdate = await server.stackAutoUpdate.setEnabled(stack, enabled); + const autoUpdate = await server.stackAutoUpdate.setPolicy(stack, schedule); callbackResult({ ok: true, autoUpdate, diff --git a/backend/agent-socket-handlers/resource-socket-handler.ts b/backend/agent-socket-handlers/resource-socket-handler.ts new file mode 100644 index 0000000..1ca7fb7 --- /dev/null +++ b/backend/agent-socket-handlers/resource-socket-handler.ts @@ -0,0 +1,45 @@ +import { AgentSocketHandler } from "../agent-socket-handler"; +import type { DockgeServer } from "../dockge-server"; +import { callbackError, callbackResult, checkLogin, DockgeSocket, ValidationError } from "../util-server"; +import type { AgentSocket } from "../../common/agent-socket"; + +export class ResourceSocketHandler extends AgentSocketHandler { + create(socket: DockgeSocket, server: DockgeServer, agentSocket: AgentSocket) { + const resources = server.dockerResources; + const on = (event: string, errorKey: string, operation: (...args: unknown[]) => Promise) => { + agentSocket.on(event, async (...args: unknown[]) => { + const callback = args.pop(); + try { + checkLogin(socket); + callbackResult({ ok: true, + ...await operation(...args) }, callback); + } catch (error) { + callbackError(error instanceof ValidationError ? error : new Error(errorKey), callback); + } + }); + }; + + on("listDockerImages", "resourceLoadFailed", async () => ({ items: await resources.listImages() })); + on("listDockerVolumes", "resourceLoadFailed", async () => ({ items: await resources.listVolumes() })); + on("getResourceCleanup", "resourceLoadFailed", async kind => ({ schedule: await server.resourceCleanup.status(kind) })); + 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("checkDockerImageTag", "resourceCheckFailed", async (id, tag) => ({ status: await resources.checkImage(id, tag) })); + on("removeDockerImage", "resourceDeleteFailed", async (id, tag) => { + await resources.removeImage(id, tag); + return { msg: "resourceDeleted", + msgi18n: true }; + }); + on("removeDockerVolume", "resourceDeleteFailed", async (name, created) => { + await resources.removeVolume(name, created); + return { msg: "resourceDeleted", + msgi18n: true }; + }); + } +} diff --git a/backend/check-version.ts b/backend/check-version.ts deleted file mode 100644 index cd6508a..0000000 --- a/backend/check-version.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { log } from "./log"; -import compareVersions from "compare-versions"; -import packageJSON from "../package.json"; -import { Settings } from "./settings"; - -// How much time in ms to wait between update checks -const UPDATE_CHECKER_INTERVAL_MS = 1000 * 60 * 60 * 48; -const CHECK_URL = "https://dockge.kuma.pet/version"; - -class CheckVersion { - version = packageJSON.version; - latestVersion? : string; - interval? : NodeJS.Timeout; - - async startInterval() { - const check = async () => { - if (await Settings.get("checkUpdate") === false) { - return; - } - - log.debug("update-checker", "Retrieving latest versions"); - - try { - const res = await fetch(CHECK_URL); - const data = await res.json(); - - // For debug - if (process.env.TEST_CHECK_VERSION === "1") { - data.slow = "1000.0.0"; - } - - const checkBeta = await Settings.get("checkBeta"); - - if (checkBeta && data.beta) { - if (compareVersions.compare(data.beta, data.slow, ">")) { - this.latestVersion = data.beta; - return; - } - } - - if (data.slow) { - this.latestVersion = data.slow; - } - - } catch (_) { - log.info("update-checker", "Failed to check for new versions"); - } - - }; - - await check(); - this.interval = setInterval(check, UPDATE_CHECKER_INTERVAL_MS); - } -} - -const checkVersion = new CheckVersion(); -export default checkVersion; diff --git a/backend/container-file-explorer.ts b/backend/container-file-explorer.ts new file mode 100644 index 0000000..1c213dc --- /dev/null +++ b/backend/container-file-explorer.ts @@ -0,0 +1,313 @@ +import { execFile } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { posix } from "node:path"; +import { promisify } from "node:util"; +import { fileChunkBytes, maxContainerFileBytes } from "../common/container-files"; +import { containerId, docker } from "./container-management"; +import { ValidationError } from "./util-server"; + +const exec = promisify(execFile); +const transferLimit = 4; +const ttl = 2 * 60 * 1000; + +interface Transfer { + owner: string; + id: string; + path: string; + type: "download" | "upload"; + data: Buffer; + offset: number; + expected?: string; + busy: boolean; + timer: NodeJS.Timeout; +} + +function checkedPath(value: unknown): string { + if (typeof value !== "string" || !value.startsWith("/") || value.includes("\0") + || Buffer.byteLength(value) > 4096 || posix.normalize(value) !== value || (value !== "/" && value.endsWith("/"))) { + throw new ValidationError("containerFileInvalidPath"); + } + return value; +} + +// Positional arguments are always data. Reject symbolic-link parents before working on a path. +const shell = ` +directory() { + cd -P -- "$1" && [ "$(pwd -P)" = "$1" ] +} +in_parent() { + p=\${1%/*} + directory "\${p:-/}" || exit 24 +} +exists() { + [ -e "$1" ] || [ -L "$1" ] +} +`; +const list = ` +directory "$1" || exit 24 +count=0 +for entry in ./* ./.[!.]* ./..?*; do + exists "$entry" || continue + count=$((count + 1)) + [ "$count" -le 3000 ] || exit 25 + kind=other + if [ -L "$entry" ]; then kind=link + elif [ -d "$entry" ]; then kind=directory + elif [ -f "$entry" ]; then kind=file + fi + metadata=$(stat -c '%s %Y' -- "$entry") || exit 24 + printf '%s\\0%s\\0%s\\0' "\${entry#./}" "$kind" "$metadata" +done +`; +const read = ` +in_parent "$1" +name=./\${1##*/} +[ ! -L "$name" ] || exit 24 +if [ -d "$name" ]; then + tar -cf - -- "$name" +else + [ -f "$name" ] || exit 24 + head -c "$2" -- "$name" +fi +`; +const write = ` +in_parent "$1" +name=./\${1##*/} +if [ -n "$2" ]; then + [ -f "$name" ] && [ ! -L "$name" ] || exit 23 + sum=$(sha256sum < "$name") || exit 24 + [ "\${sum%% *}" = "$2" ] || exit 23 + mode=$(stat -c '%a' -- "$name") || exit 24 + owner=$(stat -c '%u:%g' -- "$name") || exit 24 +else + if exists "$name"; then exit 23; fi +fi +temp=$(mktemp ./.dockge.XXXXXX) || exit 24 +trap 'rm -f -- "$temp"' EXIT +cat > "$temp" || exit 24 +[ "$(stat -c '%s' -- "$temp")" = "$3" ] || exit 24 +if [ -n "$2" ]; then + if [ "$(stat -c '%u:%g' -- "$temp")" != "$owner" ]; then + chown -- "$owner" "$temp" || exit 24 + fi + chmod -- "$mode" "$temp" || exit 24 + [ -f "$name" ] && [ ! -L "$name" ] || exit 23 + sum=$(sha256sum < "$name") || exit 24 + [ "\${sum%% *}" = "$2" ] || exit 23 + mv -fT -- "$temp" "$name" || exit 24 +else + mv -nT -- "$temp" "$name" || exit 24 + [ ! -e "$temp" ] || exit 23 +fi +`; +const change = ` +case "$1" in + mkdir) + in_parent "$2" + mkdir -- "./\${2##*/}" || exit 24 + ;; + delete) + in_parent "$2" + rm -r -- "./\${2##*/}" || exit 24 + ;; + move|copy) + in_parent "$2" + in_parent "$3" + if exists "./\${3##*/}"; then exit 23; fi + if [ "$1" = move ]; then + mv -nT -- "$2" "./\${3##*/}" && ! exists "$2" || exit 23 + else + staging=$(mktemp -d ./.dockge.XXXXXX) || exit 24 + trap 'rm -rf -- "$staging"' EXIT + cp -a -- "$2" "$staging/item" || exit 24 + mv -nT -- "$staging/item" "./\${3##*/}" || exit 24 + ! exists "$staging/item" || exit 23 + fi + ;; +esac +`; + +export class ContainerFileExplorer { + private readonly transfers = new Map(); + + disconnect(owner: string) { + for (const [ token, transfer ] of this.transfers) { + if (transfer.owner === owner) { + this.release(token); + } + } + } + + async request(owner: string, request: unknown): Promise { + if (!request || typeof request !== "object") { + throw new ValidationError("containerFileInvalidRequest"); + } + const args = request as Record; + const action = args.action; + if (action === "chunk" || action === "finish" || action === "cancel") { + return this.transferRequest(owner, action, args); + } + const id = containerId(args.id); + const path = checkedPath(args.path); + await this.requireRunning(id); + + if (action === "list") { + const { stdout } = await docker([ "container", "inspect", "--format", "{{.Name}}", "--", id ]); + const fields = (await this.run(id, list, [ path ])).toString("utf8").split("\0"); + const entries = []; + for (let i = 0; i + 2 < fields.length; i += 3) { + const [ size, modified ] = fields[i + 2].split(" ").map(Number); + entries.push({ name: fields[i], + type: fields[i + 1], + size, + modified }); + } + return { entries, + name: stdout.trim().replace(/^\//, "") }; + } + if (path === "/") { + throw new ValidationError("containerFileInvalidPath"); + } + if (action === "download" || action === "upload") { + return this.openTransfer(owner, id, path, action, args); + } + if (action === "mkdir" || action === "delete" || action === "move" || action === "copy") { + const target = action === "move" || action === "copy" ? checkedPath(args.target) : ""; + if (target && (target === "/" || target === path || target.startsWith(path + "/") || path.startsWith(target + "/"))) { + throw new ValidationError("containerFileInvalidPath"); + } + await this.run(id, change, [ action, path, target ]); + return {}; + } + throw new ValidationError("containerFileInvalidRequest"); + } + + private async requireRunning(id: string) { + const { stdout } = await docker([ "container", "inspect", "--format", "{{.State.Running}} {{.State.Paused}}", "--", id ]); + if (stdout.trim() !== "true false") { + throw new ValidationError("containerFileNotRunning"); + } + } + + private async run(id: string, script: string, args: string[], input?: Buffer) { + const pending = exec("docker", [ + "container", "exec", ...(input ? [ "-i" ] : []), id, "sh", "-c", shell + script, "dockge-files", ...args, + ], { + encoding: "buffer", + timeout: 30000, + maxBuffer: maxContainerFileBytes + 1024, + windowsHide: true, + }); + if (input) { + pending.child.stdin?.on("error", () => {}); + pending.child.stdin?.end(input); + } + try { + return (await pending).stdout; + } catch (error) { + const code = (error as { code?: string | number }).code; + const messages: Record = { + "23": "containerFileConflict", + "25": "containerFileTooManyEntries", + "126": "containerFileToolsUnavailable", + "127": "containerFileToolsUnavailable", + ERR_CHILD_PROCESS_STDIO_MAXBUFFER: "containerFileTooLarge", + }; + throw new ValidationError(messages[String(code)] || "containerFileFailed"); + } + } + + private release(token: string) { + const transfer = this.transfers.get(token); + if (transfer) { + clearTimeout(transfer.timer); + this.transfers.delete(token); + } + } + + private async openTransfer(owner: string, id: string, path: string, type: Transfer["type"], args: Record) { + if (this.transfers.size >= transferLimit || Array.from(this.transfers.values()).some(value => value.owner === owner)) { + throw new ValidationError("containerFileTransferBusy"); + } + const size = args.size; + const expected = args.expected; + if (type === "upload" && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0 || size > maxContainerFileBytes + || (expected !== undefined && (typeof expected !== "string" || !/^[0-9a-f]{64}$/.test(expected))))) { + throw new ValidationError("containerFileInvalidRequest"); + } + const token = randomUUID(); + const transfer: Transfer = { + owner, + id, + path, + type, + expected: typeof expected === "string" ? expected : undefined, + data: Buffer.alloc(type === "upload" ? Number(size) : 0), + offset: 0, + busy: true, + timer: setTimeout(() => this.release(token), ttl).unref(), + }; + this.transfers.set(token, transfer); + try { + if (type === "download") { + transfer.data = await this.run(id, read, [ path, String(maxContainerFileBytes + 1) ]); + if (transfer.data.length > maxContainerFileBytes) { + throw new ValidationError("containerFileTooLarge"); + } + } + transfer.busy = false; + return { + token, + size: transfer.data.length, + revision: type === "download" ? createHash("sha256").update(transfer.data).digest("hex") : undefined, + }; + } catch (error) { + this.release(token); + throw error; + } + } + + private async transferRequest(owner: string, action: string, args: Record) { + const token = args.token; + const transfer = typeof token === "string" && this.transfers.get(token); + if (!transfer || transfer.owner !== owner || transfer.busy || typeof token !== "string") { + throw new ValidationError("containerFileTransferExpired"); + } + transfer.timer.refresh(); + if (action === "cancel") { + this.release(token); + return {}; + } + if (action === "finish") { + if (transfer.type !== "upload" || transfer.offset !== transfer.data.length) { + throw new ValidationError("containerFileInvalidRequest"); + } + transfer.busy = true; + try { + await this.requireRunning(transfer.id); + await this.run(transfer.id, write, [ transfer.path, transfer.expected || "", String(transfer.data.length) ], transfer.data); + return {}; + } finally { + this.release(token); + } + } + if (args.offset !== transfer.offset || transfer.offset >= transfer.data.length) { + throw new ValidationError("containerFileInvalidRequest"); + } + const end = Math.min(transfer.offset + fileChunkBytes, transfer.data.length); + if (transfer.type === "download") { + const data = transfer.data.subarray(transfer.offset, end); + transfer.offset = end; + if (end === transfer.data.length) { + this.release(token); + } + return { data }; + } + if (!Buffer.isBuffer(args.data) || args.data.length !== end - transfer.offset) { + throw new ValidationError("containerFileInvalidRequest"); + } + args.data.copy(transfer.data, transfer.offset); + transfer.offset = end; + return {}; + } +} diff --git a/backend/container-management.ts b/backend/container-management.ts new file mode 100644 index 0000000..8788cca --- /dev/null +++ b/backend/container-management.ts @@ -0,0 +1,37 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { ValidationError } from "./util-server"; + +const exec = promisify(execFile); +const idPattern = /^[0-9a-f]{64}$/; + +export function containerId(id: unknown): string { + if (typeof id !== "string" || !idPattern.test(id)) { + throw new ValidationError("containerInvalidId"); + } + return id; +} + +export function docker(args: string[], timeout = 15000, maxBuffer = 4 * 1024 * 1024) { + return exec("docker", args, { timeout, + maxBuffer, + encoding: "utf8", + windowsHide: true }); +} + +interface ContainerRow { + id: string; + name: string; + image: string; + state: string; + project: string; +} + +const format = "{\"id\":{{json .ID}},\"name\":{{json .Names}},\"image\":{{json .Image}},\"state\":{{json .State}},\"project\":{{json (.Label \"com.docker.compose.project\")}}}"; + +export class ContainerManagement { + async list(): Promise { + const { stdout } = await docker([ "container", "ls", "--all", "--no-trunc", "--format", format ]); + return stdout.trim().split(/\r?\n/).filter(Boolean).map(row => JSON.parse(row) as ContainerRow); + } +} diff --git a/backend/docker-resources.ts b/backend/docker-resources.ts new file mode 100644 index 0000000..fb7456d --- /dev/null +++ b/backend/docker-resources.ts @@ -0,0 +1,303 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { ValidationError } from "./util-server"; + +const exec = promisify(execFile); +const imageId = /^sha256:[0-9a-f]{64}$/; +const volumeName = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/; +const tagName = /^[a-zA-Z0-9][a-zA-Z0-9./:_-]*:[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/; + +interface ContainerUsage { + id: string; + name: string; + image: string; + reference: string; + state: string; + mounts: Array<{ Type: string; Name?: string; Source: string }> | null; +} + +interface Platform { + os: string; + architecture: string; + variant?: string; +} + +interface Image { + id: string; + tags: string[] | null; + created: string | null; + size: number | null; + os: string; + arch: string; + variant?: string; + descriptor?: { digest: string; mediaType: string; platform?: Platform }; +} + +interface Volume { + name: string; + driver: string; + created: string | null; +} + +type TagStatus = "current" | "updateAvailable" | "unknown"; + +interface Manifest { + Descriptor?: { digest: string; platform?: Platform }; + SchemaV2Manifest?: { config?: { digest: string } }; + OCIManifest?: { config?: { digest: string } }; +} + +const containerFields = "{\"id\":{{json .Id}},\"name\":{{json .Name}},\"image\":{{json .Image}},\"reference\":{{json .Config.Image}},\"state\":{{json .State.Status}},\"mounts\":{{json .Mounts}}}"; +const imageFields = "{\"id\":{{json .Id}},\"tags\":{{json (index . \"RepoTags\")}},\"created\":{{json (index . \"Created\")}},\"size\":{{json (index . \"Size\")}},\"os\":{{json (index . \"Os\")}},\"arch\":{{json (index . \"Architecture\")}},\"variant\":{{json (index . \"Variant\")}},\"descriptor\":{{json (index . \"Descriptor\")}}}"; +const volumeFields = "{\"name\":{{json .Name}},\"driver\":{{json .Driver}},\"created\":{{json (index . \"CreatedAt\")}}}"; + +async function docker(args: string[], timeout = 15000, allowMissing = false): Promise { + try { + const { stdout } = await exec("docker", args, { + encoding: "utf8", + timeout, + maxBuffer: 8 * 1024 * 1024, + windowsHide: true, + }); + return stdout.trim(); + } catch (error) { + const result = error as { stderr?: string; stdout?: string }; + const messages = lines(result.stderr?.trim() ?? ""); + if (allowMissing && messages.length && messages.every(line => /^Error response from daemon: No such (image|volume):/.test(line))) { + return result.stdout?.trim() ?? ""; + } + throw error; + } +} + +function lines(value: string) { + return value ? value.split(/\r?\n/) : []; +} + +async function inspect(kind: string, format: string, ids: string[], allowMissing = false): Promise { + const result: T[] = []; + // Bound command-line length on hosts with many Docker resources. + for (let offset = 0; offset < ids.length; offset += 50) { + const output = await docker([ kind, "inspect", "--format", format, "--", ...ids.slice(offset, offset + 50) ], 15000, allowMissing); + result.push(...lines(output).map(line => JSON.parse(line) as T)); + } + return result; +} + +async function containers() { + const ids = lines(await docker([ "container", "ls", "--all", "--quiet", "--no-trunc" ])); + return inspect("container", containerFields, ids); +} + +function displayUsage(container: ContainerUsage) { + return { + id: container.id, + name: container.name.replace(/^\//, ""), + state: container.state, + reference: container.reference, + }; +} + +function canonicalTag(reference: string) { + if (reference.includes("@")) { + return reference; + } + const slash = reference.indexOf("/"); + const first = reference.slice(0, slash); + const tag = reference.lastIndexOf(":") > reference.lastIndexOf("/") ? reference : reference + ":latest"; + if (slash < 0) { + return "docker.io/library/" + tag; + } + if (/^(docker\.io|index\.docker\.io|registry-1\.docker\.io)$/.test(first)) { + const name = tag.slice(slash + 1); + return "docker.io/" + (name.includes("/") ? name : "library/" + name); + } + if (first === "localhost" || first.includes(".") || first.includes(":")) { + return tag; + } + return "docker.io/" + tag; +} + +function usesVolume(container: ContainerUsage, name: string) { + return container.mounts?.some(mount => mount.Type === "volume" && mount.Name === name); +} + +function usesImage(container: ContainerUsage, id: string) { + return container.image === id || container.mounts?.some(mount => mount.Type === "image" && mount.Source === id); +} + +export class DockerResources { + private imagesRequest?: ReturnType; + private volumesRequest?: ReturnType; + private checkingRegistry = false; + private readonly checks = new Map(); + + listImages() { + this.imagesRequest ??= this.loadImages().finally(() => { + this.imagesRequest = undefined; + }); + return this.imagesRequest; + } + + listVolumes() { + this.volumesRequest ??= this.loadVolumes().finally(() => { + this.volumesRequest = undefined; + }); + return this.volumesRequest; + } + + private async loadImages() { + const [ usage, tagged, dangling ] = await Promise.all([ + containers(), + docker([ "image", "ls", "--quiet", "--no-trunc" ]), + docker([ "image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true" ]), + ]); + const ids = Array.from(new Set([ ...lines(tagged), ...lines(dangling), ...usage.map(container => container.image) ])); + const images = await inspect("image", imageFields, ids, true); + const inspected = new Set(images.map(image => image.id)); + // Containerd may keep the content of an untagged image only through its container. + for (const id of new Set(usage.map(container => container.image))) { + if (imageId.test(id) && !inspected.has(id)) { + images.push({ id, + tags: [], + created: null, + size: null, + os: "", + arch: "" }); + } + } + const imagesByTag = new Map(images.flatMap(image => (image.tags ?? []).map(tag => [ canonicalTag(tag), image.id ] as const))); + return images.map(image => ({ + id: image.id, + tags: image.tags ?? [], + created: image.created, + size: image.size, + referenceOnly: !inspected.has(image.id), + platform: [ image.os, image.arch, image.variant ].filter(Boolean).join("/"), + checks: Object.fromEntries((image.tags ?? []).flatMap(tag => { + const check = this.checks.get(image.id + " " + tag); + return check && check.expires > Date.now() ? [[ tag, check.status ]] : []; + })), + containers: usage.filter(container => usesImage(container, image.id)).map(container => { + const current = imagesByTag.get(canonicalTag(container.reference)); + return { + ...displayUsage(container), + differentTagImage: Boolean(current && current !== container.image), + }; + }), + })); + } + + private async loadVolumes() { + const [ usage, listed ] = await Promise.all([ containers(), docker([ "volume", "ls", "--quiet" ]) ]); + const volumes = await inspect("volume", volumeFields, lines(listed), true); + return volumes.map(volume => ({ + ...volume, + containers: usage.filter(container => usesVolume(container, volume.name)).map(displayUsage), + })); + } + + /** Compare the selected tag for this platform without pulling layers. */ + async checkImage(id: unknown, tag: unknown) { + const image = await this.getTaggedImage(id, tag); + if (this.checkingRegistry) { + throw new ValidationError("resourceRegistryBusy"); + } + this.checkingRegistry = true; + try { + const status = await this.compareTag(image, String(tag)); + const key = image.id + " " + tag; + this.checks.delete(key); + this.checks.set(key, { status, + expires: Date.now() + 15 * 60 * 1000 }); + if (this.checks.size > 512) { + const oldest = this.checks.keys().next().value; + if (oldest) { + this.checks.delete(oldest); + } + } + return status; + } finally { + this.checkingRegistry = false; + } + } + + private async compareTag(image: Image, tag: string): Promise { + try { + const platform = image.descriptor?.platform ?? { + os: image.os, + architecture: image.arch, + variant: image.variant, + }; + let local = image.id; + if (/index|manifest\.list/.test(image.descriptor?.mediaType ?? "")) { + const format = [ platform.os, platform.architecture, platform.variant ].filter(Boolean).join("/"); + local = await docker([ "image", "inspect", "--platform", format, "--format", "{{.Id}}", "--", image.id ]); + } + + const raw = await docker([ "manifest", "inspect", "--verbose", "--", tag ], 45000); + const parsed = JSON.parse(raw) as Manifest | Manifest[]; + const matches = (Array.isArray(parsed) ? parsed : [ parsed ]).filter(entry => { + const remote = entry.Descriptor?.platform; + return remote?.os === platform.os && remote.architecture === platform.architecture + && (!platform.variant || !remote.variant || platform.variant === remote.variant); + }); + if (matches.length !== 1) { + return "unknown"; + } + const match = matches[0]; + const digest = match.Descriptor?.digest; + const config = (match.OCIManifest ?? match.SchemaV2Manifest)?.config?.digest; + if (!digest || !imageId.test(digest) || !imageId.test(local)) { + return "unknown"; + } + return local === digest || local === config ? "current" : "updateAvailable"; + } catch { + return "unknown"; + } + } + + async removeImage(id: unknown, tag: unknown) { + if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string") { + throw new ValidationError("resourceInvalidSelection"); + } + if ((await containers()).some(container => usesImage(container, id))) { + throw new ValidationError("resourceInUse"); + } + if (tag) { + await this.getTaggedImage(id, tag); + } else { + const [ image ] = await inspect("image", imageFields, [ id ]); + if (image.tags?.length) { + throw new ValidationError("resourceChanged"); + } + } + // Docker performs its own usage check as part of the removal. + await docker([ "image", "rm", "--no-prune", "--", tag || id ]); + } + + async removeVolume(name: unknown, created: unknown) { + if (typeof name !== "string" || !volumeName.test(name) || (typeof created !== "string" && created !== null)) { + throw new ValidationError("resourceInvalidSelection"); + } + const [ volume ] = await inspect("volume", volumeFields, [ name ]); + if (volume.created !== created) { + throw new ValidationError("resourceChanged"); + } + if ((await containers()).some(container => usesVolume(container, name))) { + throw new ValidationError("resourceInUse"); + } + await docker([ "volume", "rm", "--", name ]); + } + + private async getTaggedImage(id: unknown, tag: unknown) { + if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string" || !tagName.test(tag) || tag.length > 512) { + throw new ValidationError("resourceInvalidSelection"); + } + const [ image ] = await inspect("image", imageFields, [ tag ]); + if (image.id !== id || !image.tags?.includes(tag)) { + throw new ValidationError("resourceChanged"); + } + return image; + } +} diff --git a/backend/dockge-server.ts b/backend/dockge-server.ts index 160a690..920c46f 100644 --- a/backend/dockge-server.ts +++ b/backend/dockge-server.ts @@ -15,7 +15,6 @@ import { Socket } from "socket.io"; import { MainSocketHandler } from "./socket-handlers/main-socket-handler"; import { SocketHandler } from "./socket-handler"; import { Settings } from "./settings"; -import checkVersion from "./check-version"; import dayjs from "dayjs"; import { R } from "redbean-node"; import { genSecret, isDev, LooseObject } from "../common/util-common"; @@ -23,6 +22,12 @@ import { generatePasswordHash } from "./password-hash"; import { Bean } from "redbean-node/dist/bean"; import { Arguments, Config, DockgeSocket } from "./util-server"; import { DockerSocketHandler } from "./agent-socket-handlers/docker-socket-handler"; +import { ResourceSocketHandler } from "./agent-socket-handlers/resource-socket-handler"; +import { DockerResources } from "./docker-resources"; +import { ContainerManagement } from "./container-management"; +import { ContainerFileExplorer } from "./container-file-explorer"; +import { ContainerManagementSocketHandler } from "./agent-socket-handlers/container-management-socket-handler"; +import { ResourceCleanup } from "./resource-cleanup"; import expressStaticGzip from "express-static-gzip"; import path from "path"; import { TerminalSocketHandler } from "./agent-socket-handlers/terminal-socket-handler"; @@ -70,6 +75,8 @@ export class DockgeServer { */ agentSocketHandlerList : AgentSocketHandler[] = [ new DockerSocketHandler(), + new ContainerManagementSocketHandler(), + new ResourceSocketHandler(), new TerminalSocketHandler(), ]; @@ -84,6 +91,10 @@ export class DockgeServer { stacksDir : string = ""; stackAutoUpdate = new StackAutoUpdate(this); + dockerResources = new DockerResources(); + containerManagement = new ContainerManagement(); + containerFileExplorer = new ContainerFileExplorer(); + resourceCleanup = new ResourceCleanup(); imageVulnerabilityScan = new ImageVulnerabilityScan(this); /** @@ -93,7 +104,7 @@ export class DockgeServer { // Catch unexpected errors here let unexpectedErrorHandler = (error : unknown) => { console.trace(error); - console.error("If you keep encountering errors, please report to https://github.com/louislam/dockge"); + console.error("If you keep encountering errors, contact Weapie, the maintainer of this Dockge fork."); }; process.addListener("unhandledRejection", unexpectedErrorHandler); process.addListener("uncaughtException", unexpectedErrorHandler); @@ -414,8 +425,9 @@ export class DockgeServer { this.sendStackList(true); }); - checkVersion.startInterval(); this.stackAutoUpdate.start(); + this.resourceCleanup.start(); + this.imageVulnerabilityScan.startScannerUpdates(); }); gracefulShutdown(this.httpServer, { @@ -437,18 +449,15 @@ export class DockgeServer { */ async sendInfo(socket : Socket, hideVersion = false) { let versionProperty; - let latestVersionProperty; let isContainer; if (!hideVersion) { versionProperty = packageJSON.version; - latestVersionProperty = checkVersion.latestVersion; isContainer = (process.env.DOCKGE_IS_CONTAINER === "1"); } socket.emit("info", { version: versionProperty, - latestVersion: latestVersionProperty, isContainer, primaryHostname: await Settings.get("primaryHostname"), //serverTimezone: await this.getTimezone(), @@ -694,6 +703,7 @@ export class DockgeServer { // TODO: Close all terminals? this.stackAutoUpdate.stop(); + this.resourceCleanup.stop(); await this.imageVulnerabilityScan.stop(); await Database.close(); Settings.stopCacheCleaner(); diff --git a/backend/grype-updater.ts b/backend/grype-updater.ts new file mode 100644 index 0000000..7e6a1d7 --- /dev/null +++ b/backend/grype-updater.ts @@ -0,0 +1,165 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { createWriteStream, promises as fs } from "node:fs"; +import path from "node:path"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { promisify } from "node:util"; +import { gt, valid } from "semver"; +import { log } from "./log"; + +const exec = promisify(execFile); +// Node 22 provides AbortSignal.any. The project's ambient Node types predate it. +const signalClass = AbortSignal as typeof AbortSignal & { any(signals: AbortSignal[]): AbortSignal }; +const releaseAPI = "https://api.github.com/repos/anchore/grype/releases/latest"; +const releaseBase = "https://github.com/anchore/grype/releases/download"; +const interval = 6 * 60 * 60 * 1000; +const maxArchiveBytes = 100 * 1024 * 1024; + +interface Release { + tag_name: string; + assets: Array<{ name: string; digest: string; size: number }>; +} + +export class GrypeUpdater { + private readonly override = process.env.DOCKGE_GRYPE_PATH; + private readonly shutdown = new AbortController(); + private readonly architecture = process.platform === "linux" ? { x64: "amd64", + arm64: "arm64" }[process.arch as "x64" | "arm64"] : undefined; + + private current = "grype"; + private pending?: Promise; + private timer?: NodeJS.Timeout; + private nextCheck = 0; + + constructor(private readonly directory: string) {} + + start() { + void this.executable(); + this.timer ??= setInterval(() => void this.executable(), 15 * 60 * 1000).unref(); + } + + async stop() { + clearInterval(this.timer); + this.shutdown.abort(); + await this.pending; + } + + async executable() { + if (this.override || !this.architecture || this.shutdown.signal.aborted) { + return this.override || this.current; + } + if (!this.pending && Date.now() >= this.nextCheck) { + this.pending = this.refresh(this.architecture).then(() => { + this.nextCheck = Date.now() + interval; + }).catch(() => { + this.nextCheck = Date.now() + 15 * 60 * 1000; + if (!this.shutdown.signal.aborted) { + log.warn("grype-update", "Could not refresh Grype from Anchore releases"); + } + }).finally(() => { + this.pending = undefined; + }); + } + await this.pending; + return this.current; + } + + private async version(binary: string): Promise { + try { + const { stdout } = await exec(binary, [ "version", "-o", "json" ], { + env: { ...process.env, + GRYPE_CHECK_FOR_APP_UPDATE: "false" }, + signal: this.shutdown.signal, + timeout: 5000, + maxBuffer: 64 * 1024, + }); + return valid(JSON.parse(stdout).version); + } catch { + return null; + } + } + + private async refresh(arch: string) { + const installed = path.join(this.directory, "grype"); + const [ bundled, cached ] = await Promise.all([ this.version("grype"), this.version(installed) ]); + const useCached = cached && (!bundled || gt(cached, bundled)); + this.current = useCached ? installed : "grype"; + const currentVersion = useCached ? cached : bundled; + + const response = await fetch(releaseAPI, { + signal: signalClass.any([ this.shutdown.signal, AbortSignal.timeout(10000) ]), + headers: { Accept: "application/vnd.github+json", + "User-Agent": "Dockge-Grype-Updater" }, + }); + if (!response.ok) { + throw new Error("Could not retrieve Grype release"); + } + const release = await response.json() as Release; + const tag = release.tag_name; + const version = /^v\d+\.\d+\.\d+$/.test(tag) ? valid(tag) : null; + if (!version) { + throw new Error("Invalid Grype release tag"); + } + if (currentVersion && !gt(version, currentVersion)) { + return; + } + const filename = `grype_${version}_linux_${arch}.tar.gz`; + const asset = release.assets?.find(asset => asset.name === filename); + if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest) + || !Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > maxArchiveBytes) { + throw new Error("Missing Grype release checksum"); + } + + await fs.mkdir(this.directory, { recursive: true }); + const temp = await fs.mkdtemp(path.join(this.directory, ".install-")); + try { + const archive = path.join(temp, "archive.tar.gz"); + await this.download(`${releaseBase}/${tag}/${filename}`, archive, asset); + const binary = path.join(temp, "grype"); + const options = { signal: this.shutdown.signal, + timeout: 15000, + maxBuffer: 150 * 1024 * 1024, + encoding: "buffer" as const }; + const { stdout } = await exec("tar", [ "-xOzf", archive, "grype" ], options); + await fs.writeFile(binary, stdout, { mode: 0o755 }); + if (await this.version(binary) !== version) { + throw new Error("Downloaded Grype could not be verified"); + } + const license = await exec("tar", [ "-xOzf", archive, "LICENSE" ], options); + await fs.writeFile(path.join(temp, "LICENSE"), license.stdout); + await fs.rename(path.join(temp, "LICENSE"), path.join(this.directory, "LICENSE")); + await fs.rename(binary, installed); + this.current = installed; + log.info("grype-update", `Installed Grype ${version}`); + } finally { + await fs.rm(temp, { recursive: true, + force: true }); + } + } + + private async download(url: string, archive: string, asset: { size: number; digest: string }) { + const signal = signalClass.any([ this.shutdown.signal, AbortSignal.timeout(90000) ]); + const response = await fetch(url, { signal }); + if (!response.ok || !response.body) { + throw new Error("Grype download failed"); + } + const hash = createHash("sha256"); + let size = 0; + const verify = new Transform({ + transform(chunk: Buffer, encoding, callback) { + size += chunk.length; + if (size > asset.size) { + callback(new Error("Grype archive exceeds release asset size")); + return; + } + hash.update(chunk); + callback(null, chunk); + }, + }); + await pipeline(Readable.fromWeb(response.body as unknown as import("node:stream/web").ReadableStream), verify, createWriteStream(archive, { flags: "wx" }), { signal }); + if (size !== asset.size || `sha256:${hash.digest("hex")}` !== asset.digest) { + throw new Error("Grype archive checksum mismatch"); + } + } +} diff --git a/backend/image-vulnerability-scan.ts b/backend/image-vulnerability-scan.ts index afc3bc1..9d19bf9 100644 --- a/backend/image-vulnerability-scan.ts +++ b/backend/image-vulnerability-scan.ts @@ -1,3 +1,4 @@ +import { GrypeUpdater } from "./grype-updater"; import { execFile, spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { createWriteStream, promises as fs } from "node:fs"; @@ -20,6 +21,7 @@ const maxImages = 20; const maxReports = 8; const maxFindings = 500; const pageSize = 25; +const databaseTimeout = 15 * 60 * 1000; const imageIdPattern = /^sha256:[a-f0-9]{64}$/; const inspectFields = [ "\"id\":{{json .Image}}", @@ -60,6 +62,7 @@ interface ScanReport { startedAt: string; finishedAt?: string; error?: string; + preparingDatabase?: boolean; images: ImageScan[]; } @@ -158,7 +161,7 @@ function normalizeFindings(output: string) { } export class ImageVulnerabilityScan { - private readonly scanner = process.env.DOCKGE_GRYPE_PATH || "grype"; + private updater?: GrypeUpdater; private readonly reports = new Map(); private readonly shutdown = new AbortController(); private active?: ScanReport; @@ -231,9 +234,19 @@ export class ImageVulnerabilityScan { this.reports.delete(stackName); } + private get scanner() { + this.updater ??= new GrypeUpdater(path.resolve(this.server.config.dataDir, "grype-bin")); + return this.updater; + } + + startScannerUpdates() { + this.scanner.start(); + } + /** Abort outstanding commands as Dockge shuts down. */ async stop() { this.shutdown.abort(); + await this.updater?.stop(); await this.activeRun; } @@ -242,7 +255,12 @@ export class ImageVulnerabilityScan { try { report.images = await this.discoverImages(stack); if (report.images.length) { - await this.runGrype([ "version" ], path.resolve(this.server.config.dataDir), 5000); + report.preparingDatabase = true; + try { + await this.prepareDatabase(); + } finally { + report.preparingDatabase = false; + } } for (const image of report.images) { @@ -394,10 +412,28 @@ export class ImageVulnerabilityScan { return stdout.trim(); } - /** Invoke a local Grype binary against an archive, with a persistent DB cache. */ + /** Update once per report and use a valid cached database if the update fails. */ + private async prepareDatabase() { + const cwd = os.tmpdir(); + try { + await this.runGrype([ "db", "update" ], cwd, databaseTimeout); + } catch (error) { + if (this.shutdown.signal.aborted || error instanceof ValidationError) { + throw error; + } + this.reportError(error, "imageScanDatabaseUnavailable"); + try { + await this.runGrype([ "db", "status" ], cwd, 60 * 1000); + } catch { + throw new ValidationError("imageScanDatabaseUnavailable"); + } + } + } + + /** Invoke Grype with the same cache for the database update and the image scans. */ private async runGrype(args: string[], cwd: string, timeout: number): Promise { try { - const { stdout } = await exec(this.scanner, args, { + const { stdout } = await exec(await this.scanner.executable(), args, { cwd, timeout, maxBuffer: 32 * 1024 * 1024, @@ -405,8 +441,10 @@ export class ImageVulnerabilityScan { windowsHide: true, env: { ...process.env, - GRYPE_DB_CACHE_DIR: path.resolve(this.server.config.dataDir, "grype-db"), + GRYPE_DB_CACHE_DIR: path.resolve(process.env.GRYPE_DB_CACHE_DIR || path.join(this.server.config.dataDir, "grype-db")), GRYPE_CHECK_FOR_APP_UPDATE: "false", + GRYPE_DB_AUTO_UPDATE: "false", + GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT: process.env.GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT || "10m", TMPDIR: cwd, TMP: cwd, TEMP: cwd, @@ -429,7 +467,8 @@ export class ImageVulnerabilityScan { if (error instanceof ValidationError) { return error.message; } - const code = (error as NodeJS.ErrnoException)?.code ?? "unknown"; + const failure = error as (NodeJS.ErrnoException & { killed?: boolean }) | undefined; + const code = failure?.killed ? "timeout" : failure?.code ?? "unknown"; log.warn("image-scan", `${fallback} (${code})`); return fallback; } diff --git a/backend/resource-cleanup.ts b/backend/resource-cleanup.ts new file mode 100644 index 0000000..22ef82e --- /dev/null +++ b/backend/resource-cleanup.ts @@ -0,0 +1,165 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { Cron } from "croner"; +import { log } from "./log"; +import { Settings } from "./settings"; +import { ValidationError } from "./util-server"; + +const exec = promisify(execFile); +const kinds = [ "images", "volumes" ] as const; +type Kind = typeof kinds[number]; +const defaults = { enabled: false, + time: "04:00", + timezone: "UTC" }; +type Schedule = typeof defaults; + +function resourceKind(value: unknown): Kind { + if (value !== "images" && value !== "volumes") { + throw new ValidationError("resourceInvalidSelection"); + } + return value; +} + +function validSchedule(value: unknown): value is Schedule { + const schedule = value as Partial | null; + if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string" + || !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.time) + || typeof schedule.timezone !== "string" || !/^[A-Za-z][A-Za-z0-9_+/-]{0,99}$/.test(schedule.timezone)) { + return false; + } + try { + new Intl.DateTimeFormat("en-CA", { timeZone: schedule.timezone }); + return true; + } catch { + return false; + } +} + +export class ResourceCleanup { + private readonly jobs = new Map(); + private readonly running = new Set(); + private readonly saving = new Set(); + private readonly shutdown = new AbortController(); + private initialization?: Promise; + + start() { + this.initialization ??= this.initialize(); + } + + stop() { + this.shutdown.abort(); + this.jobs.forEach(job => job.stop()); + } + + private async initialize() { + for (const kind of kinds) { + try { + this.schedule(kind, await this.read(kind)); + } catch { + log.warn("resource-cleanup", `Could not load ${kind} schedule`); + } + } + } + + private async read(kind: Kind): Promise { + const value = await Settings.get(`resourceCleanup:${kind}`, false); + return validSchedule(value) ? value : { ...defaults }; + } + + async status(value: unknown) { + const kind = resourceKind(value); + await this.initialization; + const schedule = await this.read(kind); + return { + ...schedule, + nextRun: this.jobs.get(kind)?.nextRun()?.toISOString(), + lastRun: await Settings.get(`resourceCleanupRun:${kind}`, false) || null, + }; + } + + async set(value: unknown, schedule: unknown) { + const kind = resourceKind(value); + await this.initialization; + if (!validSchedule(schedule)) { + throw new ValidationError("resourceCleanupInvalidSchedule"); + } + if (this.saving.has(kind)) { + throw new ValidationError("resourceCleanupBusy"); + } + this.saving.add(kind); + try { + const { enabled, time, timezone } = schedule; + await Settings.set(`resourceCleanup:${kind}`, { enabled, + time, + timezone }); + this.schedule(kind, schedule); + return await this.status(kind); + } finally { + this.saving.delete(kind); + } + } + + private schedule(kind: Kind, schedule: Schedule) { + this.jobs.get(kind)?.stop(); + this.jobs.delete(kind); + if (!schedule.enabled || this.shutdown.signal.aborted) { + return; + } + const [ hours, minutes ] = schedule.time.split(":").map(Number); + const job = new Cron(`${minutes} ${hours} * * *`, { + timezone: schedule.timezone, + protect: true, + }, () => this.runScheduled(kind, schedule, job)); + this.jobs.set(kind, job); + } + + private async runScheduled(kind: Kind, schedule: Schedule, job: Cron) { + const date = new Date(); + const day = date.toLocaleDateString("en-CA", { timeZone: schedule.timezone }); + const key = `resourceCleanupRun:${kind}`; + try { + const previous = await Settings.get(key, false); + const current = await this.read(kind); + if (this.jobs.get(kind) !== job || previous?.day === day || !current.enabled || current.time !== schedule.time + || current.timezone !== schedule.timezone || this.shutdown.signal.aborted) { + return; + } + await Settings.set(key, { at: date.toISOString(), + day, + result: "started" }); + let result = "success"; + try { + await this.prune(kind); + } catch { + result = "failed"; + } + if (!this.shutdown.signal.aborted) { + await Settings.set(key, { at: date.toISOString(), + day, + result }); + log.info("resource-cleanup", `${kind}: ${result}`); + } + } catch { + log.warn("resource-cleanup", `Could not run ${kind} schedule`); + } + } + + async prune(value: unknown) { + const kind = resourceKind(value); + if (this.running.has(kind) || this.shutdown.signal.aborted) { + throw new ValidationError("resourceCleanupBusy"); + } + 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, + }); + } 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 c39a06a..426ec0f 100644 --- a/backend/socket-handlers/agent-proxy-socket-handler.ts +++ b/backend/socket-handlers/agent-proxy-socket-handler.ts @@ -22,6 +22,9 @@ export class AgentProxySocketHandler extends SocketHandler { } if (endpoint === ALL_ENDPOINTS) { // Send to all endpoints + if ([ "containerFiles", "listHostContainers" ].includes(eventName)) { + throw new Error("containerActionUnavailable"); + } log.debug("agent", "Sending to all endpoints: " + eventName); socket.instanceManager.emitToAllEndpoints(eventName, ...args); diff --git a/backend/stack-auto-update.ts b/backend/stack-auto-update.ts index 01a7b86..7dbd8f9 100644 --- a/backend/stack-auto-update.ts +++ b/backend/stack-auto-update.ts @@ -12,18 +12,82 @@ import { ValidationError } from "./util-server"; const exec = promisify(execFile); const policyFile = ".dockge-auto-update.json"; -const dockgeImage = /(?:^|\/)louislam\/dockge(?:[:@]|$)/i; +const dockgeImage = /(?:^|\/)(?:louislam\/dockge|dockge:local)(?:[:@]|$)/i; const stackName = /^[a-z0-9_-]+$/; -type Outcome = "updated" | "unchanged" | "skipped" | "failed"; -const outcomes: Outcome[] = [ "updated", "unchanged", "skipped", "failed" ]; +type Outcome = "updated" | "unchanged" | "waiting" | "skipped" | "failed"; +const outcomes: Outcome[] = [ "updated", "unchanged", "waiting", "skipped", "failed" ]; -interface Policy { +interface Schedule { enabled: boolean; + time: string; + timezone: string; + delayHours: number; +} + +interface PendingImage { + service: string; + image: string; + id: string; + since: string; +} + +interface Policy extends Schedule { + lastScheduledDay?: string; lastRun?: { at: string; result: Outcome; }; + pending: PendingImage[]; +} + +const defaults: Schedule = { + enabled: false, + time: "04:00", + timezone: "UTC", + delayHours: 0, +}; +const clockTime = /^([01][0-9]|2[0-3]):[0-5][0-9]$/; +const hourMs = 60 * 60 * 1000; + +function validTimezone(timezone: unknown): timezone is string { + if (typeof timezone !== "string" || timezone.length > 100 || !/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(timezone)) { + return false; + } + try { + new Intl.DateTimeFormat("en-CA", { timeZone: timezone }); + return true; + } catch { + return false; + } +} + +function validDelay(value: unknown): value is number { + return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2160; +} + +function validDate(value: unknown): value is string { + return typeof value === "string" && Number.isFinite(Date.parse(value)); +} + +function localDay(timezone: string, date: Date): string { + return new Intl.DateTimeFormat("en-CA", { + timeZone: timezone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(date); +} + +function nextRun(policy: Schedule, after: Date) { + const [ hours, minutes ] = policy.time.split(":").map(Number); + const cron = new Cron(`${minutes} ${hours} * * *`, { timezone: policy.timezone, + paused: true }); + try { + return cron.nextRun(after); + } finally { + cron.stop(); + } } interface ContainerSummary { @@ -62,26 +126,28 @@ const inspectFormat = `{${inspectFields.join(",")}}`; export class StackAutoUpdate { private schedule?: Cron; private runInProgress = false; + private readonly due = new Map(); private readonly shutdown = new AbortController(); constructor(private readonly server: DockgeServer) {} /** Run daily on this host, including when no browser is connected. */ start() { - this.schedule = new Cron("0 4 * * *", { + this.schedule = new Cron("0 * * * * *", { timezone: "UTC", protect: true, - }, () => this.run()); + }, () => this.collectDue()); } /** Stop scheduling and terminate commands during application shutdown. */ stop() { this.schedule?.stop(); + this.due.clear(); this.shutdown.abort(); } /** Return an absent policy for stacks that cannot be scheduled. */ - async getPolicy(stack: Stack): Promise { + private async readPolicy(stack: Stack): Promise { if (!stackName.test(stack.name) || stack.name === "dockge") { return; } @@ -98,7 +164,18 @@ export class StackAutoUpdate { } const policy = JSON.parse(await fs.readFile(file, "utf8")); const lastRun = policy?.lastRun; - const validPolicy: Policy = { enabled: policy?.enabled === true }; + const validPolicy: Policy = { + enabled: policy?.enabled === true, + time: typeof policy?.time === "string" && clockTime.test(policy.time) ? policy.time : defaults.time, + timezone: validTimezone(policy?.timezone) ? policy.timezone : defaults.timezone, + delayHours: validDelay(policy?.delayHours) ? policy.delayHours : defaults.delayHours, + pending: Array.isArray(policy?.pending) ? policy.pending.filter((entry: PendingImage) => + typeof entry?.service === "string" && typeof entry.image === "string" + && typeof entry.id === "string" && /^sha256:[a-f0-9]{64}$/.test(entry.id) && validDate(entry.since)) : [], + }; + if (typeof policy?.lastScheduledDay === "string" && /^\d{4}-\d{2}-\d{2}$/.test(policy.lastScheduledDay)) { + validPolicy.lastScheduledDay = policy.lastScheduledDay; + } if (typeof lastRun?.at === "string" && Number.isFinite(Date.parse(lastRun.at)) && outcomes.includes(lastRun.result)) { validPolicy.lastRun = { at: lastRun.at, @@ -110,76 +187,121 @@ export class StackAutoUpdate { if ((error as NodeJS.ErrnoException).code !== "ENOENT") { log.warn("auto-update", `Could not read policy for ${stack.name}`); } - return { enabled: false }; + return { ...defaults, + pending: [] }; } } - /** Persist the administrator's explicit choice for this stack. */ - async setEnabled(stack: Stack, enabled: boolean): Promise { - const current = await this.getPolicy(stack); - if (!current) { - throw new ValidationError("Automatic updates are unavailable for this stack."); + async getPolicy(stack: Stack) { + const policy = await this.readPolicy(stack); + return policy && this.publicPolicy(policy); + } + + private publicPolicy(policy: Policy) { + let next = policy.enabled ? nextRun(policy, new Date()) : null; + if (next && localDay(policy.timezone, next) === policy.lastScheduledDay) { + next = nextRun(policy, next); } - const policy = { - ...current, - enabled, + return { + enabled: policy.enabled, + time: policy.time, + timezone: policy.timezone, + delayHours: policy.delayHours, + lastRun: policy.lastRun, + nextRun: next?.toISOString(), + pending: policy.pending.map(entry => ({ + service: entry.service, + eligibleAt: new Date(Date.parse(entry.since) + policy.delayHours * hourMs).toISOString(), + })), }; - await this.writePolicy(stack, policy); - return policy; } - /** Check each opted-in stack once per scheduled run. */ - async run(): Promise { + /** Save the schedule on the host running the stack. Boolean requests are used by older clients. */ + async setPolicy(stack: Stack, settings: unknown) { + const current = await this.readPolicy(stack); + if (!current) { + throw new ValidationError("autoUpdateUnavailable"); + } + if (typeof settings === "boolean") { + current.enabled = settings; + } else { + const schedule = settings as Partial | null; + if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string" || !clockTime.test(schedule.time) + || !validTimezone(schedule.timezone) || !validDelay(schedule.delayHours)) { + throw new ValidationError("autoUpdateInvalidSchedule"); + } + current.enabled = schedule.enabled; + current.time = schedule.time; + current.timezone = schedule.timezone; + current.delayHours = schedule.delayHours; + } + await this.writePolicy(stack, current); + return this.publicPolicy(current); + } + + private isDue(policy: Policy, minute: Date) { + return policy.enabled && policy.lastScheduledDay !== localDay(policy.timezone, minute) + && nextRun(policy, new Date(minute.getTime() - 1000))?.getTime() === minute.getTime(); + } + + /** Collect each minute separately so long pulls do not block other scheduled starts. */ + private async collectDue() { + const minute = new Date(Math.floor(Date.now() / 60000) * 60000); + try { + const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true }); + for (const dir of dirs) { + if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") { + continue; + } + const policy = await this.readPolicy(new Stack(this.server, dir.name)); + if (policy && this.isDue(policy, minute)) { + this.due.set(dir.name, minute); + } + } + void this.runDue(); + } catch (error) { + log.warn("auto-update", String(error)); + } + } + + private async runDue() { if (this.runInProgress || this.shutdown.signal.aborted) { return; } this.runInProgress = true; try { - const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true }); - for (const dir of dirs) { + for (const [ name, minute ] of this.due) { if (this.shutdown.signal.aborted) { break; } - if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") { - continue; - } - - const stack = new Stack(this.server, dir.name); - if (!(await this.getPolicy(stack))?.enabled) { - continue; - } + this.due.delete(name); + const stack = new Stack(this.server, name); try { - await Stack.withOperation(this.server, dir.name, async () => { - const policy = await this.getPolicy(stack); - if (!policy?.enabled) { + await Stack.withOperation(this.server, name, async () => { + const policy = await this.readPolicy(stack); + if (!policy || !this.isDue(policy, minute)) { return; } + policy.lastScheduledDay = localDay(policy.timezone, minute); + await this.writePolicy(stack, policy); let result: Outcome; try { - result = await this.update(stack); + result = await this.update(stack, policy); } catch (error) { result = "failed"; log.warn("auto-update", `${stack.name}: ${String(error)}`); } - const current = await this.getPolicy(stack); - if (!current?.enabled) { - return; - } - await this.writePolicy(stack, { - ...current, - lastRun: { - at: new Date().toISOString(), - result, - }, - }); + policy.lastRun = { + at: new Date().toISOString(), + result, + }; + await this.writePolicy(stack, policy); log.info("auto-update", `${stack.name}: ${result}`); }); } catch (error) { log.warn("auto-update", `${stack.name}: ${String(error)}`); } } - } catch (error) { - log.warn("auto-update", String(error)); } finally { this.runInProgress = false; } @@ -201,7 +323,7 @@ export class StackAutoUpdate { } /** Pull and recreate only running services whose image actually changed. */ - private async update(stack: Stack): Promise { + private async update(stack: Stack, policy: Policy): Promise { const before = await this.getCandidates(stack); if (before.size === 0) { return "skipped"; @@ -211,6 +333,9 @@ export class StackAutoUpdate { 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); @@ -223,21 +348,32 @@ export class StackAutoUpdate { if (!/^sha256:[a-f0-9]{64}$/.test(imageId)) { throw new Error("Docker image inspect returned an invalid image ID"); } - if (current.imageIds.some(id => id !== imageId)) { + 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 skipped ? "skipped" : "unchanged"; + return waiting.length ? "waiting" : (skipped ? "skipped" : "unchanged"); } - if (!(await this.getPolicy(stack))?.enabled) { - return "skipped"; - } - + // 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"; } diff --git a/backend/stack.ts b/backend/stack.ts index e2fa626..7b41a7e 100644 --- a/backend/stack.ts +++ b/backend/stack.ts @@ -580,7 +580,7 @@ export class Stack { let statusList = new Map>(); try { - let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--format", "json"), { + let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--no-trunc", "--orphans=false", "--format", "json"), { cwd: this.path, encoding: "utf-8", }); @@ -591,11 +591,13 @@ export class Stack { let lines = res.stdout?.toString().split("\n"); - const addLine = (obj: { Service: string, State: string, Name: string, Health: string }) => { + const addLine = (obj: { ID: string, Service: string, State: string, Name: string, Health: string }) => { if (!statusList.has(obj.Service)) { statusList.set(obj.Service, []); } statusList.get(obj.Service)?.push({ + id: obj.ID, + state: obj.State, status: obj.Health || obj.State, name: obj.Name }); diff --git a/common/container-files.ts b/common/container-files.ts new file mode 100644 index 0000000..0a0d726 --- /dev/null +++ b/common/container-files.ts @@ -0,0 +1,3 @@ +export const fileChunkBytes = 256 * 1024; +export const maxContainerFileBytes = 32 * 1024 * 1024; +export const maxContainerTextBytes = 512 * 1024; diff --git a/components.json b/components.json new file mode 100644 index 0000000..67bb0c7 --- /dev/null +++ b/components.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://shadcn-vue.com/schema.json", + "style": "reka-nova", + "typescript": true, + "tailwind": { + "config": "", + "css": "frontend/src/styles/theme.css", + "baseColor": "mist", + "cssVariables": true + }, + "iconLibrary": "phosphor", + "rtl": false, + "menuColor": "default", + "menuAccent": "bold", + "aliases": { + "components": "@/components", + "ui": "@/components/ui", + "utils": "@/lib/utils", + "lib": "@/lib", + "composables": "@/composables" + } +} diff --git a/compose.yaml b/compose.yaml index b2b7bdb..63a34dd 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,22 +1,21 @@ services: dockge: - image: louislam/dockge:1 + image: dockge:local + build: + context: . + dockerfile: docker/Dockerfile + target: release restart: unless-stopped ports: - # Host Port : Container Port - - 5001:5001 + - "127.0.0.1:5001:5001" volumes: - /var/run/docker.sock:/var/run/docker.sock - ./data:/app/data - - # If you want to use private registries, you need to share the auth file with Dockge: - # - /root/.docker/:/root/.docker - - # Stacks Directory - # ⚠️ READ IT CAREFULLY. If you did it wrong, your data could end up writing into a WRONG PATH. - # ⚠️ 1. FULL path only. No relative path (MUST) - # ⚠️ 2. Left Stacks Path === Right Stacks Path (MUST) - - /opt/stacks:/opt/stacks + - grype-db:/app/grype-db + # Stack paths must match inside Dockge and on the Docker host. + - "${DOCKGE_STACKS_DIR:-/opt/stacks}:${DOCKGE_STACKS_DIR:-/opt/stacks}" environment: - # Tell Dockge where is your stacks directory - - DOCKGE_STACKS_DIR=/opt/stacks + DOCKGE_STACKS_DIR: "${DOCKGE_STACKS_DIR:-/opt/stacks}" + +volumes: + grype-db: diff --git a/docker/Dockerfile b/docker/Dockerfile index 0a5be9b..e306dc6 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,3 +1,15 @@ +############################################ +# Build the Vue frontend +############################################ +FROM louislam/dockge:base AS frontend +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --ignore-scripts +COPY common ./common +COPY frontend ./frontend +COPY tsconfig.json ./ +RUN npm run build:frontend + ############################################ # Healthcheck Binary ############################################ @@ -20,7 +32,11 @@ ARG TARGETARCH WORKDIR /app COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck COPY --from=build /app/node_modules /app/node_modules -COPY --chown=node:node . . +COPY --chown=node:node backend ./backend +COPY --chown=node:node common ./common +COPY --chown=node:node extra ./extra +COPY --chown=node:node package.json package-lock.json tsconfig.json LICENSE ./ +COPY --chown=node:node --from=frontend /app/frontend-dist ./frontend-dist RUN mkdir ./data # Grype is available upstream for the amd64 and arm64 images. @@ -46,8 +62,9 @@ RUN set -eu; \ # - https://github.com/sagemathinc/cocalc/issues/6963 # - https://github.com/microsoft/node-pty/issues/630#issuecomment-1987212447 ENV UV_USE_IO_URING=0 +ENV GRYPE_DB_CACHE_DIR=/app/grype-db -VOLUME /app/data +VOLUME ["/app/data", "/app/grype-db"] EXPOSE 5001 HEALTHCHECK --interval=60s --timeout=30s --start-period=60s --retries=5 CMD extra/healthcheck ENTRYPOINT ["/usr/bin/dumb-init", "--"] diff --git a/docs/images/datei-explorer.png b/docs/images/datei-explorer.png new file mode 100644 index 0000000..27a7b99 Binary files /dev/null and b/docs/images/datei-explorer.png differ diff --git a/docs/images/images.png b/docs/images/images.png new file mode 100644 index 0000000..e15dc10 Binary files /dev/null and b/docs/images/images.png differ diff --git a/docs/images/stack-uebersicht.png b/docs/images/stack-uebersicht.png new file mode 100644 index 0000000..b4dea51 Binary files /dev/null and b/docs/images/stack-uebersicht.png differ diff --git a/docs/images/volumes.png b/docs/images/volumes.png new file mode 100644 index 0000000..27d0e11 Binary files /dev/null and b/docs/images/volumes.png differ diff --git a/docs/images/wartung.png b/docs/images/wartung.png new file mode 100644 index 0000000..fac1d88 Binary files /dev/null and b/docs/images/wartung.png differ diff --git a/frontend/components.d.ts b/frontend/components.d.ts deleted file mode 100644 index c3ca03d..0000000 --- a/frontend/components.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* eslint-disable */ -/* prettier-ignore */ -// @ts-nocheck -// Generated by unplugin-vue-components -// Read more: https://github.com/vuejs/core/pull/3399 -export {} - -declare module 'vue' { - export interface GlobalComponents { - About: typeof import('./src/components/settings/About.vue')['default'] - Appearance: typeof import('./src/components/settings/Appearance.vue')['default'] - ArrayInput: typeof import('./src/components/ArrayInput.vue')['default'] - ArraySelect: typeof import('./src/components/ArraySelect.vue')['default'] - BButton: typeof import('bootstrap-vue-next')['BButton'] - BDropdown: typeof import('bootstrap-vue-next')['BDropdown'] - BDropdownItem: typeof import('bootstrap-vue-next')['BDropdownItem'] - BFormGroup: typeof import('bootstrap-vue-next')['BFormGroup'] - BFormInput: typeof import('bootstrap-vue-next')['BFormInput'] - BModal: typeof import('bootstrap-vue-next')['BModal'] - Confirm: typeof import('./src/components/Confirm.vue')['default'] - Container: typeof import('./src/components/Container.vue')['default'] - DockerStat: typeof import('./src/components/DockerStat.vue')['default'] - General: typeof import('./src/components/settings/General.vue')['default'] - GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default'] - HiddenInput: typeof import('./src/components/HiddenInput.vue')['default'] - ImageVulnerabilities: typeof import('./src/components/ImageVulnerabilities.vue')['default'] - Login: typeof import('./src/components/Login.vue')['default'] - NetworkInput: typeof import('./src/components/NetworkInput.vue')['default'] - RouterLink: typeof import('vue-router')['RouterLink'] - RouterView: typeof import('vue-router')['RouterView'] - Security: typeof import('./src/components/settings/Security.vue')['default'] - StackConfigEditor: typeof import('./src/components/StackConfigEditor.vue')['default'] - StackList: typeof import('./src/components/StackList.vue')['default'] - StackListItem: typeof import('./src/components/StackListItem.vue')['default'] - Terminal: typeof import('./src/components/Terminal.vue')['default'] - TwoFADialog: typeof import('./src/components/TwoFADialog.vue')['default'] - Uptime: typeof import('./src/components/Uptime.vue')['default'] - } - export interface ComponentCustomProperties { - vBModal: typeof import('bootstrap-vue-next')['vBModal'] - } -} diff --git a/frontend/index.html b/frontend/index.html index bd46fe2..ff671c2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -7,7 +7,7 @@ - + Dockge diff --git a/frontend/src/components/ArraySelect.vue b/frontend/src/components/ArraySelect.vue index 228c83a..7ce7223 100644 --- a/frontend/src/components/ArraySelect.vue +++ b/frontend/src/components/ArraySelect.vue @@ -1,27 +1,27 @@ - - diff --git a/frontend/src/components/AuthCard.vue b/frontend/src/components/AuthCard.vue new file mode 100644 index 0000000..4d83926 --- /dev/null +++ b/frontend/src/components/AuthCard.vue @@ -0,0 +1,27 @@ + + + diff --git a/frontend/src/components/Confirm.vue b/frontend/src/components/Confirm.vue index e855b67..7467435 100644 --- a/frontend/src/components/Confirm.vue +++ b/frontend/src/components/Confirm.vue @@ -1,84 +1,39 @@ diff --git a/frontend/src/components/Container.vue b/frontend/src/components/Container.vue index a4a6e26..c8a8e9e 100644 --- a/frontend/src/components/Container.vue +++ b/frontend/src/components/Container.vue @@ -1,204 +1,107 @@