From 8aa49e76c08c59390150c1b4a38d21f583b7d27d Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 18 Oct 2026 13:41:21 +0800 Subject: [PATCH] feat(deploy): add shumai-transcode docker image and k8s autoscaling example with garage s3 --- .github/workflows/release.yaml | 28 ++++ .gitignore | 2 + CHANGELOG.md | 2 + Dockerfile.transcode | 80 ++++++++++++ apps/transcode/src/index.ts | 16 +++ build.ts | 56 ++++---- docs/configuration/distributed.mdx | 73 ++++++++++- k8s/README.md | 115 +++++++++++++++++ k8s/config.yaml | 29 +++++ k8s/garage.yaml | 199 +++++++++++++++++++++++++++++ k8s/kustomization.yaml | 11 ++ k8s/namespace.yaml | 4 + k8s/postgres.yaml | 62 +++++++++ k8s/shumai-server.yaml | 66 ++++++++++ k8s/shumai-transcode-hpa.yaml | 39 ++++++ k8s/shumai-transcode.yaml | 41 ++++++ 16 files changed, 793 insertions(+), 30 deletions(-) create mode 100644 Dockerfile.transcode create mode 100644 k8s/README.md create mode 100644 k8s/config.yaml create mode 100644 k8s/garage.yaml create mode 100644 k8s/kustomization.yaml create mode 100644 k8s/namespace.yaml create mode 100644 k8s/postgres.yaml create mode 100644 k8s/shumai-server.yaml create mode 100644 k8s/shumai-transcode-hpa.yaml create mode 100644 k8s/shumai-transcode.yaml diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 2074a4ce..91cc717a 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -74,3 +74,31 @@ jobs: provenance: false tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} + + # Extract metadata for Docker (Transcode Worker) + - name: Extract metadata for Docker (Transcode Worker) + id: meta-transcode + uses: docker/metadata-action@v5 + with: + images: | + shumaione/shumai-transcode + crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai-transcode + tags: | + type=semver,pattern={{version}} + type=ref,event=branch,enable=${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !inputs.pr && !inputs.tag) }} + type=raw,value=pr-${{ inputs.pr }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.pr != '' && inputs.tag == '' }} + type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.tag != '' }} + labels: | + org.opencontainers.image.revision=${{ steps.checkout.outputs.commit }} + + # Build and push Docker image (Transcode Worker) + - name: Build and push Docker image (Transcode Worker) + uses: docker/build-push-action@v7 + with: + platforms: linux/amd64,linux/arm64 + context: . + file: ./Dockerfile.transcode + push: true + provenance: false + tags: ${{ steps.meta-transcode.outputs.tags }} + labels: ${{ steps.meta-transcode.outputs.labels }} diff --git a/.gitignore b/.gitignore index 4884fc07..6f3f2d32 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,5 @@ code_quality.md # Paraglide JS packages/webui/paraglide +runner-package.json + diff --git a/CHANGELOG.md b/CHANGELOG.md index 25539060..04a4e329 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +* **deploy**: Add dedicated `shumaione/shumai-transcode` Docker image and a complete Kubernetes example featuring horizontal pod autoscaling (1 to 5 replicas) for media processing with in-cluster Garage S3 storage + ### Fixed * **workflow**: Fix an issue where creating background tasks from within an active workflow step caused an invalid transition error during video processing diff --git a/Dockerfile.transcode b/Dockerfile.transcode new file mode 100644 index 00000000..ebab5b5e --- /dev/null +++ b/Dockerfile.transcode @@ -0,0 +1,80 @@ +#syntax=docker/dockerfile:1.7-labs +# Stage 1: Builder +FROM oven/bun:1.4.2 AS builder + +WORKDIR /app + +# Copy package files +COPY package.json bun.lock ./ +COPY --parents packages/*/package.json ./ +COPY --parents apps/*/package.json ./ +COPY patches/ ./patches/ + +# Install dependencies (including devDependencies for build tools) +RUN bun install --frozen-lockfile + +# Copy source code +COPY . . + +# Build transcode worker bundle +RUN bun run build.ts transcode + +# Generate runner-package.json for the runner stage +RUN bun run scripts/extract-runtime-deps.ts + +# Stage 2: Runner +FROM oven/bun:1.4.2 AS runner + +# Install transcoding system dependencies and Jellyfin-FFmpeg (with VA-API/hardware acceleration support) +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + ca-certificates \ + gosu \ + poppler-utils \ + imagemagick \ + fonts-noto-cjk \ + libraw-bin \ + libimage-exiftool-perl \ + && . /etc/os-release \ + && TARGETARCH=$(dpkg --print-architecture) \ + && FFMPEG_VERSION="8.1.2-5" \ + && curl -fsSL -o /tmp/jellyfin-ffmpeg.deb "https://github.com/jellyfin/jellyfin-ffmpeg/releases/download/v${FFMPEG_VERSION}/jellyfin-ffmpeg8_${FFMPEG_VERSION}-${VERSION_CODENAME}_${TARGETARCH}.deb" \ + && apt-get install -y --no-install-recommends /tmp/jellyfin-ffmpeg.deb \ + && rm -f /tmp/jellyfin-ffmpeg.deb \ + && ldconfig /usr/lib/jellyfin-ffmpeg/lib \ + && ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/local/bin/ffmpeg \ + && ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/local/bin/ffprobe \ + && ln -sf /usr/lib/jellyfin-ffmpeg/ffmpeg /usr/bin/ffmpeg \ + && ln -sf /usr/lib/jellyfin-ffmpeg/ffprobe /usr/bin/ffprobe \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* + +# Set up working directory and make it owned by the bun user, ensure video/render group access +RUN usermod -a -G video,render bun 2>/dev/null || true \ + && mkdir -p /app/data \ + && chown -R bun:bun /app + +# Switch to the non-root bun user +USER bun +WORKDIR /app + +# Install runtime dependencies with exact matching versions extracted from the builder stage +COPY --chown=bun:bun --from=builder /app/runner-package.json ./package.json +RUN bun install + +# Copy build artifacts +COPY --chown=bun:bun --from=builder /app/dist ./ + +# Switch back to root at the end so the container runs the entrypoint as root +USER root +COPY scripts/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh + +# Expose "bun transcode-worker.js" as "shumai-transcode" CLI command +RUN printf '#!/bin/sh\nexec bun /app/transcode-worker.js "$@"\n' > /usr/local/bin/shumai-transcode \ + && chmod +x /usr/local/bin/shumai-transcode + +ENTRYPOINT ["docker-entrypoint.sh"] + +# Default command: start transcode worker +CMD ["shumai-transcode"] diff --git a/apps/transcode/src/index.ts b/apps/transcode/src/index.ts index b80634c3..9145bb1b 100644 --- a/apps/transcode/src/index.ts +++ b/apps/transcode/src/index.ts @@ -17,6 +17,22 @@ async function run() { console.log('šŸš€ Starting Transcode Worker...') await workflowService.startWorkers(TaskQueueTranscode) + + let isShuttingDown = false + const shutdown = async () => { + if (isShuttingDown) return + isShuttingDown = true + console.log('Shutting down Transcode Worker gracefully...') + try { + await workflowService.shutdownWorkers() + } catch (err) { + console.error('Error during Transcode Worker shutdown:', err) + } + process.exit(0) + } + + process.on('SIGINT', shutdown) + process.on('SIGTERM', shutdown) } handleDaemonCommands('shumai-transcode', run).catch((err) => { diff --git a/build.ts b/build.ts index d4a117fe..78494c10 100644 --- a/build.ts +++ b/build.ts @@ -7,38 +7,42 @@ import { rm } from 'fs/promises' console.log('\nšŸš€ Starting build process...\n') const outdir = 'dist' +const target = process.argv[2] || 'all' -if (existsSync(outdir)) { +if (existsSync(outdir) && target === 'all') { console.log(`šŸ—‘ļø Cleaning previous build at ${outdir}`) await rm(outdir, { recursive: true, force: true }) } -await Bun.build({ - entrypoints: ['./apps/web/src/index.ts'], - root: '.', - target: 'bun', - outdir: outdir, - minify: true, - splitting: true, - naming: '[name].[ext]', - plugins: [tailwindPlugin, bunPluginPino({ transports: ['pino-pretty'] })], - external: ['@dbos-inc/dbos-sdk', 'pg', 'pdfkit'], - // compile: { - // outfile: 'Shumai', - // autoloadBunfig: true, - // autoloadDotenv: true, - // autoloadTsconfig: true, - // autoloadPackageJson: true, - // }, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, -}) +if (target === 'all' || target === 'web') { + await Bun.build({ + entrypoints: ['./apps/web/src/index.ts'], + root: '.', + target: 'bun', + outdir: outdir, + minify: true, + splitting: true, + naming: '[name].[ext]', + plugins: [tailwindPlugin, bunPluginPino({ transports: ['pino-pretty'] })], + external: ['@dbos-inc/dbos-sdk', 'pg', 'pdfkit'], + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + }) +} -for (const worker of [ - { entrypoint: './apps/transcode/src/index.ts', naming: 'transcode-worker.[ext]' }, - { entrypoint: './apps/agent/src/index.ts', naming: 'agent-worker.[ext]' }, -]) { +const allWorkers = [ + { + name: 'transcode', + entrypoint: './apps/transcode/src/index.ts', + naming: 'transcode-worker.[ext]', + }, + { name: 'agent', entrypoint: './apps/agent/src/index.ts', naming: 'agent-worker.[ext]' }, +] + +const workersToBuild = target === 'all' ? allWorkers : allWorkers.filter((w) => w.name === target) + +for (const worker of workersToBuild) { await Bun.build({ entrypoints: [worker.entrypoint], root: '.', diff --git a/docs/configuration/distributed.mdx b/docs/configuration/distributed.mdx index 4f94a784..6250f766 100644 --- a/docs/configuration/distributed.mdx +++ b/docs/configuration/distributed.mdx @@ -76,15 +76,17 @@ npm install -g @shumai-one/shumai-transcode shumai-transcode ``` -Alternatively, you can run the transcode worker using the official Docker image: +Alternatively, you can run the transcode worker using the dedicated lightweight Docker image: ```bash docker run -d \ --name shumai-transcode-worker \ --env-file .env \ - shumaione/shumai:latest shumai-transcode + shumaione/shumai-transcode:latest ``` +(You can also use the all-in-one image: `docker run -d --name shumai-transcode-worker --env-file .env shumaione/shumai:latest shumai-transcode`.) + ### AI Agent Worker Run this on your sandboxed agent execution nodes (requires sandbox dependencies like `bubblewrap` or `sandbox-exec`): @@ -123,5 +125,68 @@ Workers pull tasks from PostgreSQL queues based on configurable concurrency limi When running multiple replicas of the transcode or agent worker across multiple machines or pods: - `DbosExecutor` automatically derives a unique per-instance ID from the machine hostname and process ID to ensure startup recovery only re-enqueues tasks belonging to that specific instance. -- **Custom Worker ID**: Set `SHUMAI_WORKER_ID` if you wish to assign an explicit identifier. -- **Kubernetes**: In Kubernetes StatefulSets, set `POD_NAME` (via Downward API `fieldRef: { fieldPath: metadata.name }`) to provide stable identity across pod restarts. +- **Custom Worker ID**: Set `SHUMAI_WORKERS_ID` (or `SHUMAI_WORKER_ID`) if you wish to assign an explicit identifier. +- **Kubernetes**: In Kubernetes Pods, set `POD_NAME` (via Downward API `fieldRef: { fieldPath: metadata.name }`) to provide stable, unique per-pod identity across pod restarts. + +--- + +## Kubernetes Deployment & Autoscaling (HPA) + +Shumai provides an out-of-the-box Kubernetes configuration under `k8s/` showcasing horizontal scalability for media processing. Because DBOS manages task queues directly within PostgreSQL, transcode workers are completely stateless and can scale dynamically with workload demand. + +### Architecture + +```mermaid +graph TD + User([User / Web Browser]) -->|Port 3000| Server[Pod: shumai-server
SHUMAI_WORKERS=agent] + Server -->|Enqueue to transcode_queue| DB[(PostgreSQL: pgvector18
Service: shumai-postgres)] + Server -->|Direct Uploads / Stream Proxies| Storage[(Garage S3
Service: garage:3900)] + + DB -->|Poll transcode_queue| Worker1[Pod: shumai-transcode-1] + DB -->|Poll transcode_queue| WorkerN[Pod: shumai-transcode-N
Autoscaled Replicas: 1..5] + Worker1 -->|Fetch Source / Store Proxies| Storage + WorkerN -->|Fetch Source / Store Proxies| Storage + + HPA[HorizontalPodAutoscaler
Target: 70% CPU
min: 1, max: 5] -.->|Autoscale| WorkerN +``` + +### Components + +The `k8s/` directory includes a self-contained Kustomize stack: + +1. **`shumai-server`**: Main dashboard and REST API handling web traffic and AI agent tasks (`SHUMAI_WORKERS=agent`). +2. **`shumai-transcode`**: Dedicated transcoding worker pool running `shumaione/shumai-transcode:latest` with `CONCURRENCY_TRANSCODE=1`. Each pod receives its unique identity via the Kubernetes Downward API (`POD_NAME`). +3. **`garage`**: Lightweight in-cluster S3-compatible storage powered by `dxflrs/garage`, automatically initialized with bucket `shumai` and pre-configured credentials. +4. **`shumai-postgres`**: PostgreSQL database with `pgvector:pg18` hosting application data and DBOS workflow queues. +5. **`shumai-transcode-hpa`**: `HorizontalPodAutoscaler` (`autoscaling/v2`) targeting 70% CPU utilization, scaling between **1 and 5 replicas**. + +### Deploying the Stack + +Deploy the entire stack with a single command: + +```bash +kubectl apply -k k8s/ +``` + +Check the status of all pods: + +```bash +kubectl get pods -n shumai +``` + +Inspect the HorizontalPodAutoscaler: + +```bash +kubectl get hpa -n shumai +``` + +```text +NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS +shumai-transcode-hpa Deployment/shumai-transcode cpu: 10%/70% 1 5 1 +``` + +### How Autoscaling Operates + +1. **Scale-Up**: When users upload video assets, the `shumai-server` creates transcode workflow tasks and submits them to `transcode_queue` in PostgreSQL. As the active transcode worker utilizes CPU for FFmpeg encoding, CPU usage crosses the 70% threshold, triggering the HPA to scale up additional `shumai-transcode` pods (up to 5 pods). +2. **Per-Pod Executor Identity**: Each newly spawned pod uses `POD_NAME` as its DBOS executor identity. Pods poll `transcode_queue` in parallel, safely picking up and executing transcode jobs concurrently. +3. **Graceful Scale-Down & Drainage**: Worker pods configure `terminationGracePeriodSeconds: 300` and handle `SIGTERM` gracefully by draining active DBOS steps before termination, ensuring zero video proxy corruption during scale-down. diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 00000000..77c82ef4 --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,115 @@ +# Shumai Kubernetes Deployment & Autoscaling Example + +This directory contains a complete, production-ready Kubernetes example demonstrating how to run Shumai in a decoupled, horizontally scalable architecture powered by **DBOS Transact** and **Garage S3** (`dxflrs/garage`). + +--- + +## Architecture Overview + +```text + [ User / Ingress ] + │ + ā–¼ (Port 3000) + ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” + │ shumai-server (Deployment) │ + │ SHUMAI_WORKERS=agent │ + ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ + │ │ + DBOS Task Submissions │ │ Direct S3 Uploads/Reads + (Queue: transcode_queue)│ │ + ā–¼ ā–¼ + ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” + │ shumai-postgres │ │ garage-s3 │ + │ (pgvector:pg18) │ │ (dxflrs/garage)│ + ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā–²ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ + │ │ + DBOS Queue │ │ Fetch source video + Polling │ │ Store transcoded proxies + ā–¼ │ + ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ + │ shumai-transcode ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ + │ (1..5 Autoscaled Pods) + ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ + ā–² + │ CPU Utilization Target (70%) + ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” + │ shumai-transcode-hpa │ + │ (min: 1, max: 5) │ + ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ +``` + +1. **`shumai-server`**: Serves the Web dashboard and REST API, while processing agent workflows. It sets `SHUMAI_WORKERS=agent` so that all video and media transcoding tasks are delegated directly to the `transcode_queue` in PostgreSQL. +2. **`shumai-transcode`**: Dedicated stateless worker pool consuming tasks from `transcode_queue`. Each replica uses the Kubernetes Downward API to set `POD_NAME` for unique, collision-free DBOS executor identity. +3. **`garage`**: Lightweight distributed S3-compatible object storage (`dxflrs/garage`) providing high-performance shared storage for original and transcoded media files without requiring external cloud storage. +4. **`shumai-postgres`**: PostgreSQL database with `pgvector:pg18` running both application persistence and DBOS workflow queues. +5. **`shumai-transcode-hpa`**: `HorizontalPodAutoscaler` (`autoscaling/v2`) that monitors transcode worker CPU utilization and scales the pool between **1 and 5 replicas**. + +--- + +## Quickstart: Deploy to Kubernetes + +### Prerequisites +- A Kubernetes cluster (e.g. Docker Desktop, Minikube, Kind, or managed cloud Kubernetes). +- `kubectl` configured with cluster access. +- `metrics-server` installed in your cluster (required by HPA to read CPU metrics). + +### 1. Deploy the Entire Stack +Run a single command using Kustomize: + +```bash +kubectl apply -k k8s/ +``` + +### 2. Monitor Pod Status +Watch until all components are running and initialized: + +```bash +kubectl get pods -n shumai -w +``` + +Expected output: +```text +NAME READY STATUS RESTARTS AGE +garage-0 1/1 Running 0 1m +garage-init-xxxxx 0/1 Completed 0 45s +shumai-postgres-0 1/1 Running 0 1m +shumai-server-xxxxxxxxxx-xxxxx 1/1 Running 0 1m +shumai-transcode-yyyyyyyyyy-yyyyy 1/1 Running 0 1m +``` + +### 3. Check Autoscaling Status +Inspect the HorizontalPodAutoscaler: + +```bash +kubectl get hpa -n shumai +``` + +You should see: +```text +NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE +shumai-transcode-hpa Deployment/shumai-transcode 0%/70% 1 5 1 1m +``` + +### 4. Access the Shumai Dashboard +Forward port 3000 from the `shumai-server` service to your local machine: + +```bash +kubectl port-forward -n shumai svc/shumai-server 3000:3000 +``` + +Open your browser to `http://localhost:3000`. + +--- + +## Testing Transcoding & Horizontal Autoscaling + +1. Upload one or more video files in the Shumai Web UI. +2. Observe the `shumai-transcode` worker pod picking up the transcode tasks in its logs: + ```bash + kubectl logs -n shumai -l app=shumai-transcode -f + ``` +3. When multiple heavy video transcoding jobs run concurrently, CPU utilization increases past 70%, triggering the HPA to scale up additional worker pods: + ```bash + kubectl get hpa -n shumai -w + ``` +4. Once transcoding completes, the HPA will hold replicas for a 300-second stabilization window before cleanly scaling back down to 1 pod. diff --git a/k8s/config.yaml b/k8s/config.yaml new file mode 100644 index 00000000..7023155f --- /dev/null +++ b/k8s/config.yaml @@ -0,0 +1,29 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: shumai-config + namespace: shumai +data: + # S3 Storage Configuration (Garage S3) + STORAGE_BACKEND: 's3' + AWS_ENDPOINT_URL_S3: 'http://garage.shumai.svc.cluster.local:3900' + S3_BUCKET: 'shumai' + S3_REGION: 'garage' + S3_FORCE_PATH_STYLE: 'true' + + # Server & Worker Configuration + SHUMAI_SERVER_PORT: '3000' + CONCURRENCY_TRANSCODE: '1' +--- +apiVersion: v1 +kind: Secret +metadata: + name: shumai-secret + namespace: shumai +type: Opaque +stringData: + DATABASE_URL: 'postgresql://shumai:shumai_password@shumai-postgres.shumai.svc.cluster.local:5432/shumai_db?schema=public' + BETTER_AUTH_SECRET: 'qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=' + S3_ACCESS_KEY_ID: 'GKshumaiaccesskeyid001' + S3_SECRET_ACCESS_KEY: 'shumaisecretaccesskey00000000000000001' + GARAGE_ADMIN_TOKEN: 'admin-secret-token' diff --git a/k8s/garage.yaml b/k8s/garage.yaml new file mode 100644 index 00000000..0494b674 --- /dev/null +++ b/k8s/garage.yaml @@ -0,0 +1,199 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: garage-config + namespace: shumai +data: + garage.toml: | + metadata_dir = "/var/lib/garage/meta" + data_dir = "/var/lib/garage/data" + db_engine = "sqlite" + replication_factor = 1 + + rpc_bind_addr = "0.0.0.0:3901" + rpc_secret = "c7d7e35b7501a91e5cfb3874026315579930f367fa3b7e4a1e94cf67484a86cf" + + [s3_api] + s3_region = "garage" + api_bind_addr = "0.0.0.0:3900" + root_domain = ".s3.garage" + + [admin] + api_bind_addr = "0.0.0.0:3903" + admin_token = "admin-secret-token" +--- +apiVersion: v1 +kind: Service +metadata: + name: garage + namespace: shumai + labels: + app: garage +spec: + ports: + - port: 3900 + name: s3-api + - port: 3901 + name: rpc + - port: 3903 + name: admin + selector: + app: garage +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: garage + namespace: shumai +spec: + serviceName: garage + replicas: 1 + selector: + matchLabels: + app: garage + template: + metadata: + labels: + app: garage + spec: + containers: + - name: garage + image: dxflrs/garage:v2.4.1 + imagePullPolicy: IfNotPresent + command: ['/garage', 'server'] + ports: + - containerPort: 3900 + name: s3-api + - containerPort: 3901 + name: rpc + - containerPort: 3903 + name: admin + volumeMounts: + - name: config + mountPath: /etc/garage.toml + subPath: garage.toml + - name: garage-meta + mountPath: /var/lib/garage/meta + - name: garage-data + mountPath: /var/lib/garage/data + volumes: + - name: config + configMap: + name: garage-config + volumeClaimTemplates: + - metadata: + name: garage-meta + spec: + accessModes: ['ReadWriteOnce'] + resources: + requests: + storage: 1Gi + - metadata: + name: garage-data + spec: + accessModes: ['ReadWriteOnce'] + resources: + requests: + storage: 10Gi +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: garage-init + namespace: shumai +spec: + backoffLimit: 10 + template: + metadata: + labels: + app: garage-init + spec: + restartPolicy: OnFailure + containers: + - name: init + image: alpine:3.20 + env: + - name: S3_BUCKET + valueFrom: + configMapKeyRef: + name: shumai-config + key: S3_BUCKET + - name: S3_ACCESS_KEY_ID + valueFrom: + secretKeyRef: + name: shumai-secret + key: S3_ACCESS_KEY_ID + - name: S3_SECRET_ACCESS_KEY + valueFrom: + secretKeyRef: + name: shumai-secret + key: S3_SECRET_ACCESS_KEY + - name: GARAGE_ADMIN_TOKEN + valueFrom: + secretKeyRef: + name: shumai-secret + key: GARAGE_ADMIN_TOKEN + command: + - /bin/sh + - -c + - | + set -e + apk add --no-cache curl jq >/dev/null 2>&1 + + echo "Waiting for Garage Admin API to respond..." + until curl -s -f -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" http://garage:3903/v2/GetClusterStatus >/dev/null 2>&1; do + sleep 2 + done + + echo "Garage Admin API is online. Retrieving cluster status..." + STATUS=$(curl -s -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" http://garage:3903/v2/GetClusterStatus) + NODE_ID=$(echo "$STATUS" | jq -r '.nodes[0].id // empty') + if [ -z "$NODE_ID" ]; then + echo "Error: Node ID not found" + exit 1 + fi + echo "Discovered Node ID: $NODE_ID" + + ROLE=$(echo "$STATUS" | jq -r '.nodes[0].role // empty') + if [ -z "$ROLE" ] || [ "$ROLE" = "null" ]; then + echo "Assigning layout role to node..." + curl -s -f -X POST http://garage:3903/v2/UpdateClusterLayout \ + -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"roles\": [{\"id\": \"$NODE_ID\", \"zone\": \"dc1\", \"capacity\": 10737418240, \"tags\": []}]}" >/dev/null + + echo "Applying cluster layout (version 1)..." + curl -s -f -X POST http://garage:3903/v2/ApplyClusterLayout \ + -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d '{"version": 1}' >/dev/null || true + fi + + echo "Importing S3 Access Key..." + curl -s -f -X POST http://garage:3903/v2/ImportKey \ + -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"name\": \"shumai-key\", \"accessKeyId\": \"${S3_ACCESS_KEY_ID}\", \"secretAccessKey\": \"${S3_SECRET_ACCESS_KEY}\"}" >/dev/null || true + + echo "Creating S3 bucket '${S3_BUCKET}'..." + BUCKET_RESP=$(curl -s -X POST http://garage:3903/v2/CreateBucket \ + -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"globalAlias\": \"${S3_BUCKET}\"}") + echo "$BUCKET_RESP" + + BUCKET_ID=$(echo "$BUCKET_RESP" | jq -r '.id // empty') + if [ -z "$BUCKET_ID" ]; then + # Fetch existing bucket ID if already created + BUCKET_ID=$(curl -s -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" "http://garage:3903/v2/GetBucketInfo?globalAlias=${S3_BUCKET}" | jq -r '.id // empty') + fi + + if [ -n "$BUCKET_ID" ]; then + echo "Granting bucket permissions for key on bucket ID $BUCKET_ID..." + curl -s -f -X POST http://garage:3903/v2/AllowBucketKey \ + -H "Authorization: Bearer ${GARAGE_ADMIN_TOKEN}" \ + -H "Content-Type: application/json" \ + -d "{\"bucketId\": \"${BUCKET_ID}\", \"accessKeyId\": \"${S3_ACCESS_KEY_ID}\", \"permissions\": {\"read\": true, \"write\": true, \"owner\": true}}" >/dev/null || true + fi + + echo "āœ… Garage S3 storage cluster initialized successfully!" diff --git a/k8s/kustomization.yaml b/k8s/kustomization.yaml new file mode 100644 index 00000000..ea1920ed --- /dev/null +++ b/k8s/kustomization.yaml @@ -0,0 +1,11 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +resources: + - namespace.yaml + - config.yaml + - postgres.yaml + - garage.yaml + - shumai-server.yaml + - shumai-transcode.yaml + - shumai-transcode-hpa.yaml diff --git a/k8s/namespace.yaml b/k8s/namespace.yaml new file mode 100644 index 00000000..58d6feda --- /dev/null +++ b/k8s/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: shumai diff --git a/k8s/postgres.yaml b/k8s/postgres.yaml new file mode 100644 index 00000000..d7ebef93 --- /dev/null +++ b/k8s/postgres.yaml @@ -0,0 +1,62 @@ +apiVersion: v1 +kind: Service +metadata: + name: shumai-postgres + namespace: shumai + labels: + app: shumai-postgres +spec: + ports: + - port: 5432 + name: postgres + selector: + app: shumai-postgres +--- +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: shumai-postgres + namespace: shumai +spec: + serviceName: shumai-postgres + replicas: 1 + selector: + matchLabels: + app: shumai-postgres + template: + metadata: + labels: + app: shumai-postgres + spec: + containers: + - name: postgres + image: pgvector/pgvector:pg18 + ports: + - containerPort: 5432 + name: postgres + env: + - name: POSTGRES_USER + value: 'shumai' + - name: POSTGRES_PASSWORD + value: 'shumai_password' + - name: POSTGRES_DB + value: 'shumai_db' + readinessProbe: + exec: + command: + - sh + - -c + - pg_isready -U shumai -d shumai_db + initialDelaySeconds: 5 + periodSeconds: 5 + volumeMounts: + - name: postgres-data + mountPath: /var/lib/postgresql/18/docker + volumeClaimTemplates: + - metadata: + name: postgres-data + spec: + accessModes: ['ReadWriteOnce'] + resources: + requests: + storage: 5Gi diff --git a/k8s/shumai-server.yaml b/k8s/shumai-server.yaml new file mode 100644 index 00000000..8ce90fdd --- /dev/null +++ b/k8s/shumai-server.yaml @@ -0,0 +1,66 @@ +apiVersion: v1 +kind: Service +metadata: + name: shumai-server + namespace: shumai + labels: + app: shumai-server +spec: + type: ClusterIP + ports: + - port: 3000 + targetPort: 3000 + name: http + selector: + app: shumai-server +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shumai-server + namespace: shumai + labels: + app: shumai-server +spec: + replicas: 1 + selector: + matchLabels: + app: shumai-server + template: + metadata: + labels: + app: shumai-server + spec: + containers: + - name: server + image: shumaione/shumai:latest + imagePullPolicy: IfNotPresent + env: + - name: SHUMAI_WORKERS + value: 'agent' + envFrom: + - configMapRef: + name: shumai-config + - secretRef: + name: shumai-secret + ports: + - containerPort: 3000 + name: http + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + cpu: 2000m + memory: 2Gi + readinessProbe: + httpGet: + path: / + port: 3000 + initialDelaySeconds: 10 + periodSeconds: 5 + livenessProbe: + tcpSocket: + port: 3000 + initialDelaySeconds: 15 + periodSeconds: 10 diff --git a/k8s/shumai-transcode-hpa.yaml b/k8s/shumai-transcode-hpa.yaml new file mode 100644 index 00000000..8e7ca868 --- /dev/null +++ b/k8s/shumai-transcode-hpa.yaml @@ -0,0 +1,39 @@ +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: shumai-transcode-hpa + namespace: shumai + labels: + app: shumai-transcode +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: shumai-transcode + minReplicas: 1 + maxReplicas: 5 + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 70 + behavior: + scaleUp: + stabilizationWindowSeconds: 0 + selectPolicy: Max + policies: + - type: Percent + value: 100 + periodSeconds: 15 + - type: Pods + value: 2 + periodSeconds: 15 + scaleDown: + stabilizationWindowSeconds: 300 + selectPolicy: Min + policies: + - type: Pods + value: 1 + periodSeconds: 60 diff --git a/k8s/shumai-transcode.yaml b/k8s/shumai-transcode.yaml new file mode 100644 index 00000000..890a44e9 --- /dev/null +++ b/k8s/shumai-transcode.yaml @@ -0,0 +1,41 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: shumai-transcode + namespace: shumai + labels: + app: shumai-transcode +spec: + replicas: 1 + selector: + matchLabels: + app: shumai-transcode + template: + metadata: + labels: + app: shumai-transcode + spec: + terminationGracePeriodSeconds: 300 + containers: + - name: worker + image: shumaione/shumai-transcode:latest + imagePullPolicy: IfNotPresent + env: + # Downward API: Injects the unique pod name so DbosExecutor assigns a unique, + # deterministic executor ID per worker replica across pod restarts. + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + envFrom: + - configMapRef: + name: shumai-config + - secretRef: + name: shumai-secret + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + cpu: 2000m + memory: 2Gi