From 2c3ce19c781b716ec488270ff15ea58ec8b32f32 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Thu, 5 Nov 2026 15:43:02 +0000 Subject: [PATCH 1/8] fix(k8s): run one worker fleet and package the WebUI for Skaffold The backend container's start-k8s.sh started a full worker fleet alongside the workers sidecar, so both fleets transcribed every session. When the sidecar is enabled, the backend container now runs only the API, and the separate workers Deployment is not rendered. - Mount defaults.yml and config.yml from chronicle-config; drop the mem0 CA - Use the Recreate strategy for the ReadWriteOnce data volume - Add a production WebUI image built from the repository root - Add a Tailnet ingress for the backend and WebUI - Map speaker image COMPUTE_MODE values to the current uv extras - Write generated secrets owner-only and ignore generated manifests Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 +- backend/webui/Dockerfile.k8s | 28 +++++++++++ backend/webui/Dockerfile.k8s.dockerignore | 3 ++ backend/webui/nginx.conf | 47 +++++++++++++++++++ .../charts/backend/templates/deployment.yaml | 34 +++++++++----- .../backend/templates/workers-deployment.yaml | 20 +++++--- extras/speaker-recognition/Dockerfile-k8s | 12 +++-- k8s-manifests/tailscale-ingress.yaml | 25 ++++++++++ scripts/generate-k8s-configs.py | 14 +++++- skaffold.yaml | 4 +- 10 files changed, 164 insertions(+), 27 deletions(-) create mode 100644 backend/webui/Dockerfile.k8s create mode 100644 backend/webui/Dockerfile.k8s.dockerignore create mode 100644 backend/webui/nginx.conf create mode 100644 k8s-manifests/tailscale-ingress.yaml diff --git a/.gitignore b/.gitignore index e33d4882e..edeca4866 100644 --- a/.gitignore +++ b/.gitignore @@ -170,8 +170,10 @@ backend/data/speaker_model_cache/ extras/asr-services/providers/*/finetune/ -# k8s config +# k8s config (generated by scripts/generate-k8s-configs.py; holds secrets) backends/charts/backend/env-configmap.yaml +k8s-manifests/configmap.yaml +k8s-manifests/secrets.yaml extras/openmemory-mcp/data/* .env.backup.* diff --git a/backend/webui/Dockerfile.k8s b/backend/webui/Dockerfile.k8s new file mode 100644 index 000000000..5532c286f --- /dev/null +++ b/backend/webui/Dockerfile.k8s @@ -0,0 +1,28 @@ +# Production WebUI image for the Kubernetes (Skaffold) deployment. +# Build context is the repository root, because package.json depends on +# ../../contracts/audio/v2/typescript. Local development uses Dockerfile.dev. +FROM node:22-alpine AS build + +WORKDIR /workspace/backend/webui + +COPY contracts/audio/v2/typescript /workspace/contracts/audio/v2/typescript + +COPY backend/webui/package.json ./package.json +COPY backend/webui/package-lock.json ./package-lock.json +RUN npm ci + +COPY backend/webui/ . + +ARG VITE_BACKEND_URL +ENV VITE_BACKEND_URL=${VITE_BACKEND_URL} + +RUN npm run build + +FROM nginx:alpine AS production + +COPY backend/webui/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /workspace/backend/webui/dist /usr/share/nginx/html + +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] diff --git a/backend/webui/Dockerfile.k8s.dockerignore b/backend/webui/Dockerfile.k8s.dockerignore new file mode 100644 index 000000000..c5e5168ba --- /dev/null +++ b/backend/webui/Dockerfile.k8s.dockerignore @@ -0,0 +1,3 @@ +**/node_modules +**/dist +**/.git diff --git a/backend/webui/nginx.conf b/backend/webui/nginx.conf new file mode 100644 index 000000000..bc75b9a58 --- /dev/null +++ b/backend/webui/nginx.conf @@ -0,0 +1,47 @@ +server { + listen 80; + server_name localhost; + root /usr/share/nginx/html; + index index.html index.htm; + + # Basic settings + client_max_body_size 100M; + + # Gzip compression + gzip on; + gzip_vary on; + gzip_min_length 10240; + gzip_proxied any; + gzip_types + text/plain + text/css + text/xml + text/javascript + application/javascript + application/json + application/xml+rss; + + # Prevent stale index.html after deployments + location = /index.html { + add_header Cache-Control "no-cache, no-store, must-revalidate"; + try_files $uri =404; + } + + # Handle React Router (SPA) + location / { + try_files $uri $uri/ /index.html; + } + + # Cache static assets + location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { + expires 1y; + add_header Cache-Control "public, immutable"; + try_files $uri =404; + } + + # Security headers + add_header X-Frame-Options DENY; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + add_header Referrer-Policy "strict-origin-when-cross-origin"; +} diff --git a/backends/charts/backend/templates/deployment.yaml b/backends/charts/backend/templates/deployment.yaml index 02d380b4d..2b0301624 100644 --- a/backends/charts/backend/templates/deployment.yaml +++ b/backends/charts/backend/templates/deployment.yaml @@ -6,6 +6,10 @@ metadata: {{- include "backend.labels" . | nindent 4 }} spec: replicas: {{ .Values.replicaCount }} + # The data PVC is ReadWriteOnce and the node has little spare memory, so stop + # the old pod before starting the new one instead of running both at once. + strategy: + type: Recreate selector: matchLabels: {{- include "backend.selectorLabels" . | nindent 6 }} @@ -19,6 +23,11 @@ spec: - name: {{ .Chart.Name }} image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} + {{- if .Values.workers.sidecar.enabled }} + # The sidecar owns the workers. start-k8s.sh would start a second fleet, + # and both fleets would transcribe every session. + command: ["python3", "-u", "src/backend/main.py"] + {{- end }} ports: - name: http containerPort: {{ .Values.service.port }} @@ -51,16 +60,15 @@ spec: resources: {{- toYaml .Values.resources | nindent 12 }} volumeMounts: + - name: config-files + mountPath: /app/config + readOnly: true {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} - name: data-volume mountPath: /app/audio_chunks {{- end }} - - name: mem0-ca-cert - mountPath: /etc/ssl/certs/mem0-ca.crt - subPath: ca.crt - readOnly: true {{- if .Values.workers.sidecar.enabled }} # Workers sidecar container (optional) @@ -81,26 +89,30 @@ spec: resources: {{- toYaml .Values.workers.resources | default .Values.resources | nindent 12 }} volumeMounts: + - name: config-files + mountPath: /app/config + readOnly: true {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} - name: data-volume mountPath: /app/audio_chunks {{- end }} - - name: mem0-ca-cert - mountPath: /etc/ssl/certs/mem0-ca.crt - subPath: ca.crt - readOnly: true {{- end }} volumes: + - name: config-files + configMap: + name: chronicle-config + items: + - key: defaults.yml + path: defaults.yml + - key: config.yml + path: config.yml {{- if .Values.persistence.enabled }} - name: data-volume persistentVolumeClaim: claimName: {{ include "backend.fullname" . }}-data {{- end }} - - name: mem0-ca-cert - configMap: - name: mem0-ca-cert {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/backends/charts/backend/templates/workers-deployment.yaml b/backends/charts/backend/templates/workers-deployment.yaml index 3ee77ee4a..07a06c9a0 100644 --- a/backends/charts/backend/templates/workers-deployment.yaml +++ b/backends/charts/backend/templates/workers-deployment.yaml @@ -1,3 +1,4 @@ +{{- if not .Values.workers.sidecar.enabled }} apiVersion: apps/v1 kind: Deployment metadata: @@ -36,25 +37,29 @@ spec: resources: {{- toYaml .Values.workers.resources | default .Values.resources | nindent 12 }} volumeMounts: + - name: config-files + mountPath: /app/config + readOnly: true {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} - name: data-volume mountPath: /app/audio_chunks {{- end }} - - name: mem0-ca-cert - mountPath: /etc/ssl/certs/mem0-ca.crt - subPath: ca.crt - readOnly: true volumes: + - name: config-files + configMap: + name: chronicle-config + items: + - key: defaults.yml + path: defaults.yml + - key: config.yml + path: config.yml {{- if .Values.persistence.enabled }} - name: data-volume persistentVolumeClaim: claimName: {{ include "backend.fullname" . }}-data {{- end }} - - name: mem0-ca-cert - configMap: - name: mem0-ca-cert {{- with .Values.workers.nodeSelector | default .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} @@ -67,3 +72,4 @@ spec: tolerations: {{- toYaml . | nindent 8 }} {{- end }} +{{- end }} diff --git a/extras/speaker-recognition/Dockerfile-k8s b/extras/speaker-recognition/Dockerfile-k8s index d1bafedd6..422a0bff6 100644 --- a/extras/speaker-recognition/Dockerfile-k8s +++ b/extras/speaker-recognition/Dockerfile-k8s @@ -26,12 +26,14 @@ COPY src/ src/ # Install dependencies and package # Use build arg to control CPU vs GPU mode +# COMPUTE_MODE can be: cpu, gpu (defaults to cu121), cu121, cu126, cu128 ARG COMPUTE_MODE=cpu -RUN if [ "$COMPUTE_MODE" = "gpu" ]; then \ - uv sync --no-default-groups --group gpu; \ - else \ - uv sync --no-default-groups --group cpu; \ - fi +RUN case "$COMPUTE_MODE" in \ + gpu|cu121) uv sync --no-default-groups --extra cu121 ;; \ + cu126) uv sync --no-default-groups --extra cu126 ;; \ + cu128) uv sync --no-default-groups --extra cu128 ;; \ + *) uv sync --no-default-groups --extra cpu ;; \ + esac # Create directories RUN mkdir -p /app/audio_chunks /app/debug /app/data /models diff --git a/k8s-manifests/tailscale-ingress.yaml b/k8s-manifests/tailscale-ingress.yaml new file mode 100644 index 000000000..b169397fd --- /dev/null +++ b/k8s-manifests/tailscale-ingress.yaml @@ -0,0 +1,25 @@ +# Tailnet entry point: https://chronicle-pure..ts.net +# One Ingress for both charts, because a Tailscale hostname can belong to only +# one Ingress. Backend paths match backends/charts/backend/ingress-values.yaml. +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: chronicle-pure-ts + annotations: + tailscale.com/proxy-group: ushadow-proxies +spec: + ingressClassName: tailscale + tls: + - hosts: + - chronicle-pure + rules: + - http: + paths: + - { path: /api, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /auth, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /users, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /ws, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /health, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /readiness, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /audio, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } + - { path: /, pathType: Prefix, backend: { service: { name: webui, port: { number: 80 } } } } diff --git a/scripts/generate-k8s-configs.py b/scripts/generate-k8s-configs.py index ee4633b54..f7cd126bf 100755 --- a/scripts/generate-k8s-configs.py +++ b/scripts/generate-k8s-configs.py @@ -45,9 +45,21 @@ def generate_k8s_manifests(namespace: str = "chronicle"): escaped_value = var_value.replace('"', '\\"') f.write(f' {var_name}: "{escaped_value}"\n') + # Config files, mounted at /app/config by the backend chart + for file_name in ("defaults.yml", "config.yml"): + file_path = Path("config") / file_name + if not file_path.exists(): + continue + f.write(f" {file_name}: |\n") + for line in file_path.read_text().splitlines(): + f.write(f" {line}\n" if line else "\n") + # Generate Secret secret_path = output_dir / "secrets.yaml" - with open(secret_path, "w") as f: + # Owner-only from creation: the file holds credentials (base64 is not encryption) + fd = os.open(secret_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.chmod(secret_path, 0o600) # O_CREAT mode does not change an existing file + with os.fdopen(fd, "w") as f: f.write("apiVersion: v1\n") f.write("kind: Secret\n") f.write("type: Opaque\n") diff --git a/skaffold.yaml b/skaffold.yaml index 1cebdb4e4..62f90845a 100644 --- a/skaffold.yaml +++ b/skaffold.yaml @@ -124,9 +124,9 @@ profiles: docker: dockerfile: Dockerfile.k8s - image: webui - context: backend/webui + context: . docker: - dockerfile: Dockerfile + dockerfile: backend/webui/Dockerfile.k8s deploy: helm: From 0af1b3cc589d12df42f74d73be4f532e2533af53 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Fri, 6 Nov 2026 22:35:19 +0000 Subject: [PATCH 2/8] feat(k8s): ship Pi in the k8s image and allow chart hostAliases The k8s image now carries Node 22.19, Pi 0.85.1 and ripgrep, so Timeline analysis and the memory agents can run. The backend chart accepts hostAliases for Tailnet hosts that cluster DNS cannot resolve. Co-Authored-By: Claude Opus 5.5 --- backend/Dockerfile.k8s | 16 +++++++++++++++- .../charts/backend/templates/deployment.yaml | 4 ++++ .../backend/templates/workers-deployment.yaml | 4 ++++ backends/charts/backend/values.yaml | 2 ++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/Dockerfile.k8s b/backend/Dockerfile.k8s index 2b86f6df5..2a7bb47fa 100644 --- a/backend/Dockerfile.k8s +++ b/backend/Dockerfile.k8s @@ -1,3 +1,12 @@ +# Pi 0.85 requires Node >=22.19. Keep these versions the same as backend/Dockerfile. +ARG NODE_VERSION=22.19.0 + +FROM node:${NODE_VERSION}-bookworm-slim AS pi-fetcher +ARG PI_VERSION=0.85.1 +RUN npm install --global --prefix /opt/pi --omit=dev --ignore-scripts --no-audit --no-fund \ + "@earendil-works/pi-coding-agent@${PI_VERSION}" \ + && npm cache clean --force + FROM python:3.12-slim-bookworm AS builder # Install system dependencies for building @@ -8,12 +17,17 @@ RUN apt-get update && \ git \ curl \ ffmpeg \ + ripgrep \ && rm -rf /var/lib/apt/lists/* # portaudio19-dev \ # Install uv COPY --from=ghcr.io/astral-sh/uv:0.6.10 /uv /uvx /bin/ +# Pi runs Timeline analysis. Node is its runtime; npm is not needed at runtime. +COPY --from=pi-fetcher /usr/local/bin/node /usr/local/bin/node +COPY --from=pi-fetcher /opt/pi /opt/pi + # Set up the working directory WORKDIR /app @@ -41,7 +55,7 @@ COPY start-k8s.sh ./ RUN chmod +x start-k8s.sh # Activate virtual environment in PATH -ENV PATH="/app/.venv/bin:$PATH" +ENV PATH="/app/.venv/bin:/opt/pi/bin:$PATH" # Run the application with workers # K8s startup script starts both FastAPI backend and RQ workers diff --git a/backends/charts/backend/templates/deployment.yaml b/backends/charts/backend/templates/deployment.yaml index 2b0301624..097614e3c 100644 --- a/backends/charts/backend/templates/deployment.yaml +++ b/backends/charts/backend/templates/deployment.yaml @@ -113,6 +113,10 @@ spec: persistentVolumeClaim: claimName: {{ include "backend.fullname" . }}-data {{- end }} + {{- with .Values.hostAliases }} + hostAliases: + {{- toYaml . | nindent 8 }} + {{- end }} {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/backends/charts/backend/templates/workers-deployment.yaml b/backends/charts/backend/templates/workers-deployment.yaml index 07a06c9a0..3e2d41a1d 100644 --- a/backends/charts/backend/templates/workers-deployment.yaml +++ b/backends/charts/backend/templates/workers-deployment.yaml @@ -60,6 +60,10 @@ spec: persistentVolumeClaim: claimName: {{ include "backend.fullname" . }}-data {{- end }} + {{- with .Values.hostAliases }} + hostAliases: + {{- toYaml . | nindent 8 }} + {{- end }} {{- with .Values.workers.nodeSelector | default .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} diff --git a/backends/charts/backend/values.yaml b/backends/charts/backend/values.yaml index 28c3452af..2a63d736f 100644 --- a/backends/charts/backend/values.yaml +++ b/backends/charts/backend/values.yaml @@ -89,6 +89,8 @@ persistence: size: 10Gi mountPath: /app/data +# Extra /etc/hosts entries, e.g. a Tailnet host the cluster DNS cannot resolve. +hostAliases: [] nodeSelector: {} tolerations: [] affinity: {} From ad4eb1e46957e59077daacb75fca6d1af32dcdab Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Sat, 7 Nov 2026 16:16:45 +0000 Subject: [PATCH 3/8] fix(k8s): authenticate to Mongo and run config scripts with python-dotenv The backend crashlooped on the cluster because the Mongo URI had no credentials. The URI now takes the password from chronicle-secrets via Kubernetes $(MONGO_ROOT_PASSWORD) expansion, so it never enters Helm values. The config generator targets now use `uv run --with python-dotenv`, because the repo root has no project environment to install it into. Co-Authored-By: Claude Opus 5.5 --- Makefile | 4 ++-- skaffold.yaml | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 2f19a318a..cfe5e90a6 100644 --- a/Makefile +++ b/Makefile @@ -206,12 +206,12 @@ config: config-all ## Generate all configuration files config-docker: ## Generate Docker Compose configuration files @echo "🐳 Generating Docker Compose configuration files..." - @CONFIG_FILE=config.env.dev python3 scripts/generate-docker-configs.py + @CONFIG_FILE=config.env.dev uv run --with python-dotenv python scripts/generate-docker-configs.py @echo "βœ… Docker Compose configuration files generated" config-k8s: ## Generate Kubernetes configuration files (ConfigMap/Secret only - no .env files) @echo "☸️ Generating Kubernetes configuration files..." - @python3 scripts/generate-k8s-configs.py + @uv run --with python-dotenv python scripts/generate-k8s-configs.py @echo "πŸ“¦ Applying ConfigMap and Secret to Kubernetes..." @kubectl apply -f k8s-manifests/configmap.yaml -n $(APPLICATION_NAMESPACE) 2>/dev/null || echo "⚠️ ConfigMap not applied (cluster not available?)" @kubectl apply -f k8s-manifests/secrets.yaml -n $(APPLICATION_NAMESPACE) 2>/dev/null || echo "⚠️ Secret not applied (cluster not available?)" diff --git a/skaffold.yaml b/skaffold.yaml index 62f90845a..710892b0a 100644 --- a/skaffold.yaml +++ b/skaffold.yaml @@ -142,7 +142,9 @@ profiles: image.repository: "{{.IMAGE_REPO_backend}}" image.tag: "{{.IMAGE_TAG_backend}}" # Override specific Kubernetes-specific values (not in env file) - env.MONGODB_URI: "mongodb://mongodb.{{.INFRASTRUCTURE_NAMESPACE}}.svc.cluster.local:27017/chronicle" + # $(MONGO_ROOT_PASSWORD) is expanded by Kubernetes from the + # chronicle-secrets envFrom, so the password never enters Helm values. + env.MONGODB_URI: "mongodb://root:$(MONGO_ROOT_PASSWORD)@mongodb.{{.INFRASTRUCTURE_NAMESPACE}}.svc.cluster.local:27017/chronicle?authSource=admin" env.REDIS_URL: "redis://redis-master.{{.INFRASTRUCTURE_NAMESPACE}}.svc.cluster.local:6379/0" persistence.storageClass: "openebs-hostpath" persistence.size: "10Gi" From 3e7901de8afb1580655fc0b3eba2954da7eb6e35 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Mon, 9 Nov 2026 17:04:41 +0000 Subject: [PATCH 4/8] feat(k8s): build and deploy speaker recognition with make deploy-speaker The speaker profile builds amd64 images with a Skaffold custom builder (scripts/k8s/buildx-push.sh) on a configurable buildx builder, so it works from an arm64 build machine. COMPUTE_MODE selects the torch build: cu126 keeps Pascal GPUs, which cu128 drops. make config-k8s now regenerates skaffold.env from config.env, so a stale copy cannot override it. The backend reaches the service at its in-cluster address. The WebUI build context now includes chronicle-espresso-preset.js. Co-Authored-By: Claude Opus 5.5 --- Makefile | 9 +++++- config.env.template | 12 ++++++-- extras/speaker-recognition/Dockerfile-k8s | 14 ++++----- .../speaker-recognition/webui/.dockerignore | 1 + scripts/generate-k8s-configs.py | 30 ++++++++++++++++++- scripts/k8s/buildx-push.sh | 25 ++++++++++++++++ skaffold.yaml | 17 +++++------ 7 files changed, 87 insertions(+), 21 deletions(-) create mode 100755 scripts/k8s/buildx-push.sh diff --git a/Makefile b/Makefile index cfe5e90a6..01301b834 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ export $(shell sed 's/=.*//' config.env | grep -v '^\s*$$' | grep -v '^\s*\#') SCRIPTS_DIR := scripts K8S_SCRIPTS_DIR := $(SCRIPTS_DIR)/k8s -.PHONY: help menu setup-k8s setup-infrastructure setup-rbac setup-storage-pvc config config-docker config-k8s config-all clean deploy deploy-docker deploy-k8s deploy-k8s-full deploy-infrastructure deploy-apps check-infrastructure check-apps build-backend up-backend down-backend k8s-status k8s-cleanup k8s-purge audio-manage test-robot test-robot-integration test-robot-unit test-robot-endpoints test-robot-specific test-robot-clean +.PHONY: help menu setup-k8s setup-infrastructure setup-rbac setup-storage-pvc config config-docker config-k8s config-all clean deploy deploy-docker deploy-k8s deploy-k8s-full deploy-speaker deploy-infrastructure deploy-apps check-infrastructure check-apps build-backend up-backend down-backend k8s-status k8s-cleanup k8s-purge audio-manage test-robot test-robot-integration test-robot-unit test-robot-endpoints test-robot-specific test-robot-clean # Default target .DEFAULT_GOAL := menu @@ -50,6 +50,7 @@ menu: ## Show interactive menu (default) @echo " deploy-docker 🐳 Deploy with Docker Compose" @echo " deploy-k8s ☸️ Deploy to Kubernetes with Skaffold" @echo " deploy-k8s-full πŸ—οΈ Deploy infrastructure + applications" + @echo " deploy-speaker πŸ—£οΈ Build + deploy speaker recognition (GPU, speech ns)" @echo @echo "πŸ”§ Utilities:" @echo " k8s-purge πŸ—‘οΈ Purge unused images (registry + container)" @@ -92,6 +93,7 @@ help: ## Show detailed help for all targets @echo " deploy-docker Deploy with Docker Compose" @echo " deploy-k8s Deploy to Kubernetes with Skaffold" @echo " deploy-k8s-full Deploy infrastructure + applications" + @echo " deploy-speaker Build + deploy speaker recognition to the speech namespace" @echo @echo "πŸ”§ KUBERNETES UTILITIES:" @echo " k8s-status Check Kubernetes cluster status and health" @@ -265,6 +267,11 @@ deploy-k8s: config-k8s ## Deploy to Kubernetes using Skaffold @set -a; source skaffold.env; set +a; skaffold run --profile=backend --default-repo=$(CONTAINER_REGISTRY) @echo "βœ… Kubernetes deployment completed" +deploy-speaker: config-k8s ## Build (amd64, via BUILDX_BUILDER) and deploy speaker recognition + @echo "πŸ—£οΈ Deploying speaker recognition to the speech namespace..." + @set -a; source skaffold.env; set +a; skaffold run --profile=speaker-recognition --default-repo=$(CONTAINER_REGISTRY) + @echo "βœ… Speaker recognition deployed (backend URL: $(SPEAKER_SERVICE_URL))" + deploy-k8s-full: deploy-infrastructure deploy-apps ## Deploy infrastructure + applications to Kubernetes @echo "βœ… Full Kubernetes deployment completed" diff --git a/config.env.template b/config.env.template index 3f85beba1..f24d2ed29 100644 --- a/config.env.template +++ b/config.env.template @@ -97,11 +97,16 @@ HF_TOKEN = hf_xxxxx # Speaker recognition settings SIMILARITY_THRESHOLD = 0.15 -COMPUTE_MODE = gpu +# cpu, cu126 or cu128. cu126 keeps Pascal GPUs (sm_61); cu128 drops them. +COMPUTE_MODE = cu126 -# Node deployment configuration +# Node deployment configuration (the node with the NVIDIA GPU) SPEAKER_NODE = xxxxx +# amd64 buildx builder for k8s images, used by the Skaffold custom builder +# (scripts/k8s/buildx-push.sh). List yours with: docker buildx ls +BUILDX_BUILDER = xxxxx + # React UI settings for speaker recognition REACT_UI_HOST = 0.0.0.0 REACT_UI_PORT = 5173 @@ -119,7 +124,8 @@ SPEAKER_HOST = speaker.$(DOMAIN) # Service URLs BACKEND_URL = http://$(DOMAIN_PREFIX).$(DOMAIN):$(BACKEND_PORT) WEBUI_URL = http://$(DOMAIN_PREFIX).$(DOMAIN):$(WEBUI_PORT) -SPEAKER_SERVICE_URL = http://$(SPEAKER_HOST):$(SPEAKER_PORT) +# In-cluster address: the Tailscale ingress (speaker.$(DOMAIN)) only serves 80/443. +SPEAKER_SERVICE_URL = http://speaker-recognition-speaker.speech.svc.cluster.local:$(SPEAKER_PORT) # CORS and Vite configuration CORS_ORIGINS = http://$(DOMAIN):$(WEBUI_PORT),http://localhost:$(WEBUI_PORT) diff --git a/extras/speaker-recognition/Dockerfile-k8s b/extras/speaker-recognition/Dockerfile-k8s index 422a0bff6..724f70cd6 100644 --- a/extras/speaker-recognition/Dockerfile-k8s +++ b/extras/speaker-recognition/Dockerfile-k8s @@ -26,13 +26,12 @@ COPY src/ src/ # Install dependencies and package # Use build arg to control CPU vs GPU mode -# COMPUTE_MODE can be: cpu, gpu (defaults to cu121), cu121, cu126, cu128 +# COMPUTE_MODE can be: cpu, cu126, cu128 (the extras in pyproject.toml). +# cu126 keeps Pascal (sm_61, e.g. GTX 1070); cu128 torch builds drop it. ARG COMPUTE_MODE=cpu RUN case "$COMPUTE_MODE" in \ - gpu|cu121) uv sync --no-default-groups --extra cu121 ;; \ - cu126) uv sync --no-default-groups --extra cu126 ;; \ - cu128) uv sync --no-default-groups --extra cu128 ;; \ - *) uv sync --no-default-groups --extra cpu ;; \ + cpu|cu126|cu128) uv sync --no-default-groups --extra "$COMPUTE_MODE" ;; \ + *) echo "Unsupported COMPUTE_MODE=$COMPUTE_MODE (use cpu, cu126 or cu128)" >&2; exit 1 ;; \ esac # Create directories @@ -57,5 +56,6 @@ RUN --mount=type=cache,target=/models \ # Expose port EXPOSE 8085 -# Run the service -CMD ["uv", "run", "--no-dev", "simple-speaker-service"] +# Run the service. --no-sync keeps the torch build selected by COMPUTE_MODE; +# without it, uv re-resolves at startup and swaps in the default torch wheel. +CMD ["uv", "run", "--no-dev", "--no-sync", "simple-speaker-service"] diff --git a/extras/speaker-recognition/webui/.dockerignore b/extras/speaker-recognition/webui/.dockerignore index 7ee28f851..d4be6f81d 100644 --- a/extras/speaker-recognition/webui/.dockerignore +++ b/extras/speaker-recognition/webui/.dockerignore @@ -4,6 +4,7 @@ !index.html !vite.config.ts !tailwind.config.js +!chronicle-espresso-preset.js !postcss.config.js !tsconfig.json !tsconfig.node.json diff --git a/scripts/generate-k8s-configs.py b/scripts/generate-k8s-configs.py index f7cd126bf..a61fb62df 100755 --- a/scripts/generate-k8s-configs.py +++ b/scripts/generate-k8s-configs.py @@ -11,7 +11,34 @@ # Add lib directory to path sys.path.append(str(Path(__file__).parent / "lib")) -from env_utils import classify_secrets, get_resolved_env_vars +from env_utils import ( + classify_secrets, + format_variable, + get_resolved_env_vars, + get_skaffold_variables, +) + + +def generate_skaffold_env(all_vars: dict) -> None: + """Write skaffold.env: the config.env values that skaffold.yaml templates use. + + The Makefile sources this file before `skaffold run`, so a stale copy would + override config.env. Regenerating it here keeps both in step. + """ + needed = get_skaffold_variables() + missing = sorted(needed - all_vars.keys()) + if missing: + raise SystemExit( + f"config.env is missing Skaffold variables: {', '.join(missing)}" + ) + with open("skaffold.env", "w") as f: + f.write("# Auto-generated by 'make config-k8s' - DO NOT EDIT DIRECTLY\n") + f.write( + "# Edit config.env instead. Contains only variables used by skaffold.yaml.\n\n" + ) + for name in sorted(needed): + f.write(format_variable(name, all_vars[name], "skaffold") + "\n") + print(" - skaffold.env") def generate_k8s_manifests(namespace: str = "chronicle"): @@ -90,6 +117,7 @@ def main(): """Main entry point""" namespace = sys.argv[1] if len(sys.argv) > 1 else "chronicle" generate_k8s_manifests(namespace) + generate_skaffold_env(get_resolved_env_vars()) if __name__ == "__main__": diff --git a/scripts/k8s/buildx-push.sh b/scripts/k8s/buildx-push.sh new file mode 100755 index 000000000..092f8e282 --- /dev/null +++ b/scripts/k8s/buildx-push.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Skaffold custom builder: build one artifact on a remote buildx builder and push it. +# +# Skaffold's docker builder loads images into the local daemon before pushing, which +# fails with a docker-container buildx builder, and the cluster nodes are amd64 while a +# Mac builds arm64. This builds natively on the builder named by BUILDX_BUILDER +# (config.env) and pushes straight to the registry. +# +# Usage (as a Skaffold custom.buildCommand, run from the artifact context): +# buildx-push.sh [docker buildx build args...] +# Pass a bare `--build-arg NAME` to take NAME's value from the environment. +# Skaffold provides IMAGE, BUILD_CONTEXT and (with --platform) PLATFORMS. +set -euo pipefail + +dockerfile="$1" +shift + +exec docker buildx build \ + --builder "${BUILDX_BUILDER:?set BUILDX_BUILDER in config.env}" \ + --platform "${PLATFORMS:-linux/amd64}" \ + --file "$dockerfile" \ + --tag "${IMAGE:?IMAGE is set by Skaffold}" \ + --push \ + "$@" \ + "${BUILD_CONTEXT:-.}" diff --git a/skaffold.yaml b/skaffold.yaml index 710892b0a..174af7dd0 100644 --- a/skaffold.yaml +++ b/skaffold.yaml @@ -44,24 +44,23 @@ profiles: image.repository: "{{.IMAGE_REPO_parakeet_asr}}" image.tag: "{{.IMAGE_TAG_parakeet_asr}}" + # Built on the amd64 buildx builder named by BUILDX_BUILDER (config.env) and + # pushed directly; bare --build-arg values come from the environment + # (COMPUTE_MODE, VITE_ALLOWED_HOSTS from skaffold.env). Run: make deploy-speaker - name: speaker-recognition build: + platforms: ["linux/amd64"] local: push: true - useDockerCLI: true artifacts: - image: speaker-recognition context: extras/speaker-recognition - docker: - dockerfile: Dockerfile-k8s - buildArgs: - COMPUTE_MODE: "{{.COMPUTE_MODE}}" + custom: + buildCommand: ../../scripts/k8s/buildx-push.sh Dockerfile-k8s --build-arg COMPUTE_MODE - image: speaker-recognition-ui context: extras/speaker-recognition/webui - docker: - dockerfile: Dockerfile - buildArgs: - VITE_ALLOWED_HOSTS: "{{.VITE_ALLOWED_HOSTS}}" + custom: + buildCommand: ../../../scripts/k8s/buildx-push.sh Dockerfile --build-arg VITE_ALLOWED_HOSTS deploy: helm: releases: From 7fd1a624f1305ead92e4d929deb2221dd5b545ba Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Mon, 9 Nov 2026 17:04:42 +0000 Subject: [PATCH 5/8] feat(k8s): keep settings saved in the app across redeploys A ConfigMap is read-only, so the Settings page could not save on Kubernetes. The backend and workers now use CONFIG_DIR on the data volume, as the shared bind mount does under Docker Compose. A config-seed init container fills it from the ConfigMap on every pod start: defaults.yml is replaced, and config.yml and plugins.yml keep every live value, gaining only keys that are new in the repository. plugins.yml is added to the ConfigMap for this. Co-Authored-By: Claude Opus 5.5 --- backend/src/backend/config_seed.py | 100 +++++++++++++++++ backend/tests/test_config_seed.py | 102 ++++++++++++++++++ .../charts/backend/templates/deployment.yaml | 39 +++++++ .../backend/templates/workers-deployment.yaml | 31 ++++++ scripts/generate-k8s-configs.py | 5 +- 5 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 backend/src/backend/config_seed.py create mode 100644 backend/tests/test_config_seed.py diff --git a/backend/src/backend/config_seed.py b/backend/src/backend/config_seed.py new file mode 100644 index 000000000..d84435e35 --- /dev/null +++ b/backend/src/backend/config_seed.py @@ -0,0 +1,100 @@ +"""Seed a writable config directory from a read-only copy, keeping live settings. + +In Kubernetes the repository's config files arrive in a ConfigMap, which is +read-only. Runtime settings changes (the Settings page, ``save_config_section``) +must be written somewhere, so the backend's ``CONFIG_DIR`` points at a +directory on the data volume instead, as the shared bind mount does under +Docker Compose. An init container runs this module before the backend and +workers start, on every pod start: + +* ``defaults.yml`` is shipped code defaults, not settings: always replaced. +* ``config.yml`` and ``plugins.yml`` hold settings. When absent they are + copied. When present, keys that exist only in the seed are added and every + key already in the live file keeps its live value, so a redeploy never + undoes a change made in the app. A list is a single value: a live list is + kept whole, never merged element by element. + +Usage: python -m backend.config_seed SEED_DIR CONFIG_DIR +""" + +import os +import shutil +import sys +from pathlib import Path + +from ruamel.yaml import YAML +from ruamel.yaml.comments import CommentedMap + +ALWAYS_REPLACED = ("defaults.yml",) +MERGED = ("config.yml", "plugins.yml") + + +def merge_missing(live: dict, seed: dict, prefix: str = "") -> list[str]: + """Add the keys of ``seed`` that ``live`` lacks, in place; live values win. + + Returns the dotted paths of the keys that were added. + """ + added = [] + for key, seed_value in seed.items(): + path = f"{prefix}{key}" + if key not in live: + live[key] = seed_value + added.append(path) + elif isinstance(live[key], dict) and isinstance(seed_value, dict): + added.extend(merge_missing(live[key], seed_value, f"{path}.")) + return added + + +def _atomic_write(target: Path, write) -> None: + temporary = target.with_name(f".{target.name}.tmp") + with open(temporary, "w", encoding="utf-8") as stream: + write(stream) + os.replace(temporary, target) + + +def seed_config_dir(seed_dir: Path, config_dir: Path) -> None: + config_dir.mkdir(parents=True, exist_ok=True) + yaml = YAML() + yaml.preserve_quotes = True + + for name in ALWAYS_REPLACED: + source = seed_dir / name + if not source.exists(): + raise FileNotFoundError( + f"{source} is missing from the seed; run 'make config-k8s'" + ) + _atomic_write( + config_dir / name, lambda f: f.write(source.read_text(encoding="utf-8")) + ) + print(f"{name}: replaced from seed") + + for name in MERGED: + source = seed_dir / name + target = config_dir / name + if not source.exists(): + print(f"{name}: not in seed, left as is") + continue + if not target.exists(): + shutil.copyfile(source, target) + print(f"{name}: created from seed") + continue + live = yaml.load(target.read_text(encoding="utf-8")) or CommentedMap() + seed = yaml.load(source.read_text(encoding="utf-8")) or {} + added = merge_missing(live, seed) + if not added: + print(f"{name}: live settings kept, nothing new in seed") + continue + _atomic_write(target, lambda f: yaml.dump(live, f)) + print(f"{name}: live settings kept, added from seed: {', '.join(added)}") + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + print(__doc__.strip().splitlines()[-1], file=sys.stderr) + return 2 + seed_config_dir(Path(argv[0]), Path(argv[1])) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/backend/tests/test_config_seed.py b/backend/tests/test_config_seed.py new file mode 100644 index 000000000..024d3a37f --- /dev/null +++ b/backend/tests/test_config_seed.py @@ -0,0 +1,102 @@ +"""The k8s config seed keeps settings made in the app across redeploys.""" + +from pathlib import Path + +import pytest +from ruamel.yaml import YAML + +from backend.config_seed import main, merge_missing, seed_config_dir + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def _load(path: Path): + return YAML(typ="safe").load(path.read_text(encoding="utf-8")) + + +@pytest.fixture +def dirs(tmp_path): + seed, config = tmp_path / "seed", tmp_path / "config" + _write(seed / "defaults.yml", "llm:\n timeout: 30\n") + return seed, config + + +def test_merge_adds_only_missing_keys_and_keeps_live_values(): + live = {"backend": {"cleanup": {"days": 7}}, "models": [{"name": "live"}]} + seed = { + "backend": {"cleanup": {"days": 30, "enabled": True}, "new": {"x": 1}}, + "models": [{"name": "repo"}], + } + + added = merge_missing(live, seed) + + assert live == { + "backend": {"cleanup": {"days": 7, "enabled": True}, "new": {"x": 1}}, + "models": [{"name": "live"}], + } + assert sorted(added) == ["backend.cleanup.enabled", "backend.new"] + + +def test_first_start_copies_seed(dirs): + seed, config = dirs + _write(seed / "config.yml", "defaults:\n llm: repo-llm\n") + _write(seed / "plugins.yml", "plugins: {}\n") + + seed_config_dir(seed, config) + + assert _load(config / "config.yml") == {"defaults": {"llm": "repo-llm"}} + assert _load(config / "plugins.yml") == {"plugins": {}} + assert _load(config / "defaults.yml") == {"llm": {"timeout": 30}} + + +def test_redeploy_keeps_app_settings_and_comments(dirs): + seed, config = dirs + _write(seed / "config.yml", "defaults:\n llm: repo-llm\n stt: repo-stt\n") + _write( + config / "config.yml", + "# saved from the Settings page\ndefaults:\n llm: app-llm\n", + ) + + seed_config_dir(seed, config) + + text = (config / "config.yml").read_text(encoding="utf-8") + assert "# saved from the Settings page" in text + assert _load(config / "config.yml") == { + "defaults": {"llm": "app-llm", "stt": "repo-stt"} + } + + +def test_defaults_are_always_replaced(dirs): + seed, config = dirs + _write(config / "defaults.yml", "llm:\n timeout: 5\n") + + seed_config_dir(seed, config) + + assert _load(config / "defaults.yml") == {"llm": {"timeout": 30}} + + +def test_unchanged_live_file_is_not_rewritten(dirs): + seed, config = dirs + _write(seed / "config.yml", "a: 1\n") + _write(config / "config.yml", "a: 2 # spacing kept\n") + + seed_config_dir(seed, config) + + assert (config / "config.yml").read_text( + encoding="utf-8" + ) == "a: 2 # spacing kept\n" + + +def test_missing_defaults_in_seed_fails(tmp_path): + with pytest.raises(FileNotFoundError, match="make config-k8s"): + seed_config_dir(tmp_path / "empty", tmp_path / "config") + + +def test_entry_point_seeds_directory(dirs): + seed, config = dirs + + assert main([str(seed), str(config)]) == 0 + assert (config / "defaults.yml").exists() diff --git a/backends/charts/backend/templates/deployment.yaml b/backends/charts/backend/templates/deployment.yaml index 097614e3c..e922138d4 100644 --- a/backends/charts/backend/templates/deployment.yaml +++ b/backends/charts/backend/templates/deployment.yaml @@ -18,6 +18,27 @@ spec: labels: {{- include "backend.selectorLabels" . | nindent 8 }} spec: + {{- if .Values.persistence.enabled }} + # Copy the repo config into the writable config dir. Settings already + # there (saved from the app) win; only keys new in the repo are added. + # See backend/src/backend/config_seed.py. + initContainers: + - name: config-seed + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: + - python + - -m + - backend.config_seed + - /seed + - {{ printf "%s/config" .Values.persistence.mountPath | quote }} + volumeMounts: + - name: config-files + mountPath: /seed + readOnly: true + - name: data-volume + mountPath: {{ .Values.persistence.mountPath }} + {{- end }} containers: # Main FastAPI backend - name: {{ .Chart.Name }} @@ -43,6 +64,12 @@ spec: - name: {{ $key }} value: {{ $value | quote }} {{- end }} + {{- if .Values.persistence.enabled }} + # Writable config on the data volume, like the Docker bind mount. + # The config-seed init container fills it from the ConfigMap. + - name: CONFIG_DIR + value: {{ printf "%s/config" .Values.persistence.mountPath | quote }} + {{- end }} livenessProbe: httpGet: path: /health @@ -60,9 +87,11 @@ spec: resources: {{- toYaml .Values.resources | nindent 12 }} volumeMounts: + {{- if not .Values.persistence.enabled }} - name: config-files mountPath: /app/config readOnly: true + {{- end }} {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} @@ -86,12 +115,20 @@ spec: - name: {{ $key }} value: {{ $value | quote }} {{- end }} + {{- if .Values.persistence.enabled }} + # Writable config on the data volume, like the Docker bind mount. + # The config-seed init container fills it from the ConfigMap. + - name: CONFIG_DIR + value: {{ printf "%s/config" .Values.persistence.mountPath | quote }} + {{- end }} resources: {{- toYaml .Values.workers.resources | default .Values.resources | nindent 12 }} volumeMounts: + {{- if not .Values.persistence.enabled }} - name: config-files mountPath: /app/config readOnly: true + {{- end }} {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} @@ -103,11 +140,13 @@ spec: - name: config-files configMap: name: chronicle-config + {{- if not .Values.persistence.enabled }} items: - key: defaults.yml path: defaults.yml - key: config.yml path: config.yml + {{- end }} {{- if .Values.persistence.enabled }} - name: data-volume persistentVolumeClaim: diff --git a/backends/charts/backend/templates/workers-deployment.yaml b/backends/charts/backend/templates/workers-deployment.yaml index 3e2d41a1d..94350b661 100644 --- a/backends/charts/backend/templates/workers-deployment.yaml +++ b/backends/charts/backend/templates/workers-deployment.yaml @@ -18,6 +18,27 @@ spec: {{- include "backend.selectorLabels" . | nindent 8 }} app.kubernetes.io/component: workers spec: + {{- if .Values.persistence.enabled }} + # Copy the repo config into the writable config dir. Settings already + # there (saved from the app) win; only keys new in the repo are added. + # See backend/src/backend/config_seed.py. + initContainers: + - name: config-seed + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + command: + - python + - -m + - backend.config_seed + - /seed + - {{ printf "%s/config" .Values.persistence.mountPath | quote }} + volumeMounts: + - name: config-files + mountPath: /seed + readOnly: true + - name: data-volume + mountPath: {{ .Values.persistence.mountPath }} + {{- end }} containers: - name: {{ .Chart.Name }}-workers image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" @@ -34,12 +55,20 @@ spec: - name: {{ $key }} value: {{ $value | quote }} {{- end }} + {{- if .Values.persistence.enabled }} + # Writable config on the data volume, like the Docker bind mount. + # The config-seed init container fills it from the ConfigMap. + - name: CONFIG_DIR + value: {{ printf "%s/config" .Values.persistence.mountPath | quote }} + {{- end }} resources: {{- toYaml .Values.workers.resources | default .Values.resources | nindent 12 }} volumeMounts: + {{- if not .Values.persistence.enabled }} - name: config-files mountPath: /app/config readOnly: true + {{- end }} {{- if .Values.persistence.enabled }} - name: data-volume mountPath: {{ .Values.persistence.mountPath }} @@ -50,11 +79,13 @@ spec: - name: config-files configMap: name: chronicle-config + {{- if not .Values.persistence.enabled }} items: - key: defaults.yml path: defaults.yml - key: config.yml path: config.yml + {{- end }} {{- if .Values.persistence.enabled }} - name: data-volume persistentVolumeClaim: diff --git a/scripts/generate-k8s-configs.py b/scripts/generate-k8s-configs.py index a61fb62df..f9125d79e 100755 --- a/scripts/generate-k8s-configs.py +++ b/scripts/generate-k8s-configs.py @@ -72,8 +72,9 @@ def generate_k8s_manifests(namespace: str = "chronicle"): escaped_value = var_value.replace('"', '\\"') f.write(f' {var_name}: "{escaped_value}"\n') - # Config files, mounted at /app/config by the backend chart - for file_name in ("defaults.yml", "config.yml"): + # Config files: the seed that the chart's config-seed init container merges + # into the writable config dir (backend/src/backend/config_seed.py) + for file_name in ("defaults.yml", "config.yml", "plugins.yml"): file_path = Path("config") / file_name if not file_path.exists(): continue From 5fb381b44594fae6bf5fdeccb890b2c098422dc9 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Mon, 9 Nov 2026 17:04:43 +0000 Subject: [PATCH 6/8] chore(make): remove duplicate deploy targets and fix setup-k8s deploy-apps and up-backend now call deploy-k8s and deploy-docker instead of repeating them. deploy-k8s-full deploys MongoDB and Redis through setup-infrastructure; deploy-infrastructure, which applied every file in k8s-manifests/, is removed. setup-k8s now finds the registry script in scripts/k8s/. The config scripts take their packages from setup-requirements.txt. Co-Authored-By: Claude Opus 5.5 --- Makefile | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/Makefile b/Makefile index 01301b834..b1e93da9c 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ export $(shell sed 's/=.*//' config.env | grep -v '^\s*$$' | grep -v '^\s*\#') SCRIPTS_DIR := scripts K8S_SCRIPTS_DIR := $(SCRIPTS_DIR)/k8s -.PHONY: help menu setup-k8s setup-infrastructure setup-rbac setup-storage-pvc config config-docker config-k8s config-all clean deploy deploy-docker deploy-k8s deploy-k8s-full deploy-speaker deploy-infrastructure deploy-apps check-infrastructure check-apps build-backend up-backend down-backend k8s-status k8s-cleanup k8s-purge audio-manage test-robot test-robot-integration test-robot-unit test-robot-endpoints test-robot-specific test-robot-clean +.PHONY: help menu setup-k8s setup-infrastructure setup-rbac setup-storage-pvc config config-docker config-k8s config-all clean deploy deploy-docker deploy-k8s deploy-k8s-full deploy-speaker deploy-apps check-infrastructure check-apps build-backend up-backend down-backend k8s-status k8s-cleanup k8s-purge audio-manage test-robot test-robot-integration test-robot-unit test-robot-endpoints test-robot-specific test-robot-clean # Default target .DEFAULT_GOAL := menu @@ -162,7 +162,7 @@ setup-k8s: ## Initial Kubernetes setup (registry + infrastructure) exit 1; \ fi; \ echo "πŸ”§ Step 1: Configuring insecure registry access on $$node_ip..."; \ - $(SCRIPTS_DIR)/configure-insecure-registry-remote.sh $$node_ip; \ + $(K8S_SCRIPTS_DIR)/configure-insecure-registry-remote.sh $$node_ip; \ echo "πŸ“¦ Step 2: Setting up storage for speaker recognition..."; \ $(K8S_SCRIPTS_DIR)/setup-storage.sh; \ echo "πŸ“ Step 3: Generating configuration files..."; \ @@ -208,12 +208,12 @@ config: config-all ## Generate all configuration files config-docker: ## Generate Docker Compose configuration files @echo "🐳 Generating Docker Compose configuration files..." - @CONFIG_FILE=config.env.dev uv run --with python-dotenv python scripts/generate-docker-configs.py + @CONFIG_FILE=config.env.dev uv run --with-requirements setup-requirements.txt python scripts/generate-docker-configs.py @echo "βœ… Docker Compose configuration files generated" config-k8s: ## Generate Kubernetes configuration files (ConfigMap/Secret only - no .env files) @echo "☸️ Generating Kubernetes configuration files..." - @uv run --with python-dotenv python scripts/generate-k8s-configs.py + @uv run --with-requirements setup-requirements.txt python scripts/generate-k8s-configs.py @echo "πŸ“¦ Applying ConfigMap and Secret to Kubernetes..." @kubectl apply -f k8s-manifests/configmap.yaml -n $(APPLICATION_NAMESPACE) 2>/dev/null || echo "⚠️ ConfigMap not applied (cluster not available?)" @kubectl apply -f k8s-manifests/secrets.yaml -n $(APPLICATION_NAMESPACE) 2>/dev/null || echo "⚠️ Secret not applied (cluster not available?)" @@ -272,18 +272,10 @@ deploy-speaker: config-k8s ## Build (amd64, via BUILDX_BUILDER) and deploy speak @set -a; source skaffold.env; set +a; skaffold run --profile=speaker-recognition --default-repo=$(CONTAINER_REGISTRY) @echo "βœ… Speaker recognition deployed (backend URL: $(SPEAKER_SERVICE_URL))" -deploy-k8s-full: deploy-infrastructure deploy-apps ## Deploy infrastructure + applications to Kubernetes +deploy-k8s-full: setup-infrastructure deploy-k8s ## Deploy infrastructure + applications to Kubernetes @echo "βœ… Full Kubernetes deployment completed" -deploy-infrastructure: ## Deploy infrastructure services to Kubernetes - @echo "πŸ—οΈ Deploying infrastructure services..." - @kubectl apply -f k8s-manifests/ - @echo "βœ… Infrastructure deployment completed" - -deploy-apps: config-k8s ## Deploy application services to Kubernetes - @echo "πŸ“± Deploying application services..." - @set -a; source skaffold.env; set +a; skaffold run --profile=backend --default-repo=$(CONTAINER_REGISTRY) - @echo "βœ… Application deployment completed" +deploy-apps: deploy-k8s ## Alias for deploy-k8s # ======================================== # UTILITY TARGETS @@ -307,9 +299,7 @@ build-backend: ## Build backend Docker image @echo "πŸ”¨ Building backend Docker image..." @cd backend && docker build -t backend:latest . -up-backend: config-docker ## Start backend services - @echo "πŸš€ Starting backend services..." - @cd backend && docker-compose up -d +up-backend: deploy-docker ## Alias for deploy-docker down-backend: ## Stop backend services @echo "πŸ›‘ Stopping backend services..." From f922208329fbd08964aa997688bfbdaf20fb346d Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Mon, 9 Nov 2026 17:04:43 +0000 Subject: [PATCH 7/8] docs(k8s): rewrite README-K8S for the make-based deploy The guide named scripts and files that no longer exist and an old skaffold.env workflow. It now follows make setup-k8s, make deploy and make deploy-speaker, lists the config.env settings and generated files, explains how app settings survive a redeploy, and records known limitations. config.env.template gains MONGO_ROOT_PASSWORD, which the backend needs. Co-Authored-By: Claude Opus 5.5 --- README-K8S.md | 968 +++++++++----------------------------------- config.env.template | 2 + 2 files changed, 195 insertions(+), 775 deletions(-) diff --git a/README-K8S.md b/README-K8S.md index ea19c5049..d7cefe5e1 100644 --- a/README-K8S.md +++ b/README-K8S.md @@ -1,824 +1,242 @@ -# Chronicle Kubernetes Setup Guide +# Chronicle on Kubernetes -This guide walks you through setting up Chronicle from scratch on a fresh Ubuntu system, including MicroK8s installation, Docker registry configuration, and deployment via Skaffold. +This guide deploys Chronicle to a MicroK8s cluster with Skaffold and Helm. All +deploy steps run from the repository root through `make`. -## System Architecture +- **Build machine**: where you run `make`. It builds the images and pushes them + to the cluster registry. It can be another architecture (for example an arm64 + Mac): the speaker images build for amd64 on a buildx builder you choose. +- **Cluster**: one or more MicroK8s nodes. One node hosts the image registry. -- **Build Machine**: Your development machine with Docker (for building images) -- **Kubernetes Node (k8s_control_plane)**: Ubuntu server running MicroK8s cluster -- **Docker Registry**: Runs on the Kubernetes node for image storage +## Contents -## Table of Contents +1. [Prepare the cluster](#1-prepare-the-cluster) +2. [Prepare the build machine](#2-prepare-the-build-machine) +3. [Configure](#3-configure) +4. [First-time setup](#4-first-time-setup) +5. [Deploy](#5-deploy) +6. [Settings changed in the app](#6-settings-changed-in-the-app) +7. [Check and maintain](#7-check-and-maintain) +8. [Troubleshooting](#8-troubleshooting) +9. [Known limitations](#9-known-limitations) -1. [System Requirements](#system-requirements) -2. [Ubuntu Installation](#ubuntu-installation) -3. [MicroK8s Installation](#microk8s-installation) -4. [MicroK8s Registry Setup](#microk8s-registry-setup) -5. [Repository Setup](#repository-setup) -6. [Environment Configuration](#environment-configuration) -7. [Deployment](#deployment) -8. [Verification](#verification) -9. [Troubleshooting](#troubleshooting) +## 1. Prepare the cluster -## System Requirements +**Run on each cluster node.** -### Build Machine (Your Development Machine) -- **OS**: macOS, Linux, or Windows with WSL2 -- **Docker**: Docker Desktop or Docker Engine -- **Tools**: Git, curl/wget - -### Kubernetes Node (k8s_control_plane) -- **Hardware**: Minimum 8GB RAM, 4 CPU cores, 50GB storage -- **Network**: Static IP configuration (recommended: 192.168.1.42) -- **OS**: Ubuntu 22.04 LTS or later -- **Architecture**: x86_64 (AMD64) - -## Ubuntu Installation - -**Run on: Kubernetes Node (k8s_control_plane)** - -1. **Download Ubuntu Server 22.04 LTS** +1. Install MicroK8s: ```bash - # Download from https://ubuntu.com/download/server - # Or use wget: - wget https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso - ``` - -2. **Install Ubuntu Server** - - Boot from USB/DVD - - Choose "Install Ubuntu Server" - - Configure network with static IP (recommended: 192.168.1.42) - - Set hostname (e.g., `k8s_control_plane`) - - Create user account - - Install OpenSSH server - -3. **Post-Installation Setup** - ```bash - # Update system - sudo apt update && sudo apt upgrade -y - - # Install essential packages - sudo apt install -y curl wget git vim htop tree - - # Configure firewall - sudo ufw allow ssh - sudo ufw allow 6443 # Kubernetes API - sudo ufw allow 32000 # Docker registry - sudo ufw enable - ``` - -## MicroK8s Installation - -**Run on: Kubernetes Node (k8s_control_plane)** - -1. **Install MicroK8s** - ```bash - # Install MicroK8s sudo snap install microk8s --classic - - # Add user to microk8s group sudo usermod -a -G microk8s $USER - sudo chown -f -R $USER ~/.kube - - # Log out and back in, or run: newgrp microk8s + microk8s status --wait-ready ``` - -2. **Configure as Control Plane** - ```bash - # Start MicroK8s - sudo microk8s start - - # Wait for all services to be ready - sudo microk8s status --wait-ready - - # Generate join token for worker nodes - sudo microk8s add-node - # This will output a command like: - # sudo microk8s join 192.168.1.42:25000/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - # Save this command for worker node setup - ``` - -3. **Start MicroK8s** - ```bash - # Start MicroK8s - sudo microk8s start - - # Wait for all services to be ready - sudo microk8s status --wait-ready - ``` - -4. **Enable Required Add-ons** - ```bash - # Enable essential add-ons - sudo microk8s enable dns - sudo microk8s enable ingress - sudo microk8s enable storage - sudo microk8s enable metrics-server - - # Wait for add-ons to be ready - sudo microk8s status --wait-ready - ``` - -5. **Configure kubectl** - ```bash - # Create kubectl alias - echo 'alias kubectl="microk8s kubectl"' >> ~/.bashrc - source ~/.bashrc - - # Verify installation - kubectl get nodes - kubectl get pods -A - ``` - -## Worker Node Installation - -**Run on: Each Worker Node** - -1. **Install Ubuntu Server (Same as Control Plane)** - ```bash - # Follow the same Ubuntu installation steps as the control plane - # Use different hostname (e.g., k8s_worker_01, k8s_worker_02) - # Configure static IP (e.g., 192.168.1.43, 192.168.1.44) - # Ensure network connectivity to control plane (192.168.1.42) - ``` - -2. **Install MicroK8s** - ```bash - # Install MicroK8s - sudo snap install microk8s --classic - - # Add user to microk8s group - sudo usermod -a -G microk8s $USER - sudo chown -f -R $USER ~/.kube - - # Log out and back in, or run: - newgrp microk8s - ``` - -3. **Join the Cluster** - ```bash - # Use the join command from the control plane - # Replace with your actual join token - sudo microk8s join 192.168.1.42:25000/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - - # Wait for node to join - sudo microk8s status --wait-ready - ``` - -4. **Verify Node Status** - ```bash - # On the control plane, verify the worker node joined - kubectl get nodes - - # The worker node should show as Ready - # Example output: - # NAME STATUS ROLES AGE VERSION - # k8s_control_plane Ready 1h v1.28.0 - # k8s_worker_01 Ready 5m v1.28.0 - ``` - -5. **Configure Worker Node for Registry Access** - ```bash - # From your build machine, configure the worker node - ./configure-insecure-registry-remote.sh 192.168.1.43 - - # Repeat for each worker node with their respective IPs - ``` - -## MicroK8s Registry Setup - -**Run on: Kubernetes Node (k8s_control_plane)** - -1. **Enable Built-in Registry** - ```bash - # Enable the built-in MicroK8s registry (not enabled by default) - sudo microk8s enable registry - - # Wait for registry to be ready - sudo microk8s status --wait-ready - - # Verify registry is running - kubectl get pods -n container-registry - ``` - -2. **Configure Registry Access** - ```bash - # The registry runs on port 32000 by default - # Verify it's accessible - curl http://localhost:32000/v2/ - ``` - -3. **Configure Remote Access (from Build Machine)** - ```bash - # From your build machine, configure MicroK8s to trust the insecure registry - chmod +x scripts/configure-insecure-registry-remote.sh - - # Run the configuration script with your node IP address - # Usage: ./scripts/configure-insecure-registry-remote.sh [ssh_user] - ./scripts/configure-insecure-registry-remote.sh 192.168.1.42 - - # Or with custom SSH user: - # ./scripts/configure-insecure-registry-remote.sh 192.168.1.42 myuser - ``` - -## Storage Configuration - -**Run on: Kubernetes Node (k8s_control_plane)** - -1. **Install OpenEBS Hostpath Provisioner** - - the default hostpath provisioner seems to have a bug in it that makes it not work. If you want to use the default - one, then you will need to update the charts to use that for the PVC. - - ```bash - # Apply the hostpath provisioner - kubectl apply -f k8s-manifests/hostpath-provisioner-official.yaml - - # Verify storage class - kubectl get storageclass - ``` - -## Repository Setup - -**Run on: Build Machine (Your Development Machine)** - -### **Directory Structure** -``` -chronicle/ -β”œβ”€β”€ scripts/ # Kubernetes deployment and management scripts -β”‚ β”œβ”€β”€ deploy-all-services.sh # Deploy all services -β”‚ β”œβ”€β”€ cluster-status.sh # Check cluster health -β”‚ β”œβ”€β”€ setup-nvidia-operator.sh # Setup GPU support -β”‚ β”œβ”€β”€ test-gpu-pod.sh # Test GPU access -β”‚ β”œβ”€β”€ cleanup-all.sh # Remove all deployments -β”‚ β”œβ”€β”€ configure-insecure-registry-remote.sh # Configure registry access -β”‚ └── generate-configmap.sh # Generate ConfigMap templates -β”œβ”€β”€ k8s-manifests/ # Standalone Kubernetes manifests -β”‚ └── hostpath-provisioner-official.yaml # Storage provisioner -β”œβ”€β”€ skaffold.env.template # Configuration template -β”œβ”€β”€ skaffold.yaml # Skaffold deployment configuration -β”œβ”€β”€ init.sh # Docker Compose setup -└── deploy-speaker-recognition.sh # Standalone speaker recognition -``` - -### **Repository Setup** - -1. **Clone Repository** - ```bash - # Clone Chronicle repository with submodules - git clone --recursive https://github.com/SimpleOpenSoftware/chronicle.git - cd chronicle - - # If you already cloned without --recursive, initialize submodules: - # git submodule update --init --recursive - - # Verify template files are present - ls -la skaffold.env.template - ls -la backend/.env.template - ``` - - > **Note:** The `--recursive` flag downloads the optional Mycelia submodule (an alternative memory backend with timeline visualization). Most deployments use the default Chronicle memory system and don't need Mycelia. - -2. **Install Required Tools** - - **kubectl** (required for Skaffold and Helm): - - Visit: https://kubernetes.io/docs/tasks/tools/ - - Follow the official installation guide for your platform - - **Skaffold**: - - Visit: https://skaffold.dev/docs/install/ - - Follow the official installation guide - - **Helm**: - - Visit: https://helm.sh/docs/intro/install/ - - Follow the official installation guide - - **Verify installations:** - ```bash - kubectl version --client - skaffold version - helm version - ``` - -## Environment Configuration - -**Important**: Never commit your actual `.env` or `skaffold.env` files to version control. Only the `.template` files should be committed. - -**Run on: Build Machine (Your Development Machine)** - -1. **Create Environment File** - ```bash - # Copy template (if it exists) - # cp backend/.env.template backend/.env - - # Note: Most environment variables are automatically set by Skaffold during deployment - # including MONGODB_URI and other Kubernetes-specific values - ``` - -2. **Configure Skaffold Environment** - ```bash - # Copy the template file - cp skaffold.env.template skaffold.env - - # Edit skaffold.env with your specific values - vim skaffold.env - - # Essential variables to configure: - REGISTRY=192.168.1.42:32000 # Use IP address for immediate access - # Alternative: REGISTRY=k8s_control_plane:32000 (requires adding 'k8s_control_plane 192.168.1.42' to /etc/hosts) - BACKEND_IP=192.168.1.42 - BACKEND_NODEPORT=30270 - WEBUI_NODEPORT=31011 - - # Optional: Configure speaker recognition service - HF_TOKEN=hf_your_huggingface_token_here - DEEPGRAM_API_KEY=your_deepgram_api_key_here - - # Note: MONGODB_URI is automatically generated by Skaffold based on - # your infrastructure namespace and service names - ``` - -3. **Configuration Variables Reference** - - **Required Variables:** - - `REGISTRY`: Docker registry for image storage - - `BACKEND_IP`: IP address of your Kubernetes control plane - - `BACKEND_NODEPORT`: Port for backend service (30000-32767) - - `WEBUI_NODEPORT`: Port for WebUI service (30000-32767) - - `INFRASTRUCTURE_NAMESPACE`: Namespace for MongoDB and FalkorDB - - `APPLICATION_NAMESPACE`: Namespace for your application - - **Optional Variables (for Speaker Recognition):** - - `HF_TOKEN`: Hugging Face token for Pyannote models - - `DEEPGRAM_API_KEY`: Deepgram API key for speech-to-text - - `COMPUTE_MODE`: GPU or CPU mode for ML services - - `SIMILARITY_THRESHOLD`: Speaker identification threshold - - **Automatically Generated:** - - `MONGODB_URI`: Generated from infrastructure namespace - - `IMAGE_REPO_*`: Generated from Skaffold build process - - `IMAGE_TAG_*`: Generated from Skaffold build process - -5. **Generate ConfigMap (if needed)** - ```bash - # Note: Most environment variables are handled by Skaffold automatically - # If you need custom environment variables, you can: - - # Option 1: Use the script (if it exists) - # chmod +x scripts/generate-helm-configmap.sh - # ./scripts/generate-helm-configmap.sh - - # Option 2: Add them directly to the Helm chart values - # Edit backends/charts/backend/values.yaml - ``` - -## Available Scripts - -**Run on: Build Machine (Your Development Machine)** - -The following scripts are available in the `scripts/` folder to simplify common operations: - -### **Deployment Scripts** -```bash -# Deploy all services in the correct order -./scripts/deploy-all-services.sh - -# Deploy with custom registry -./scripts/deploy-all-services.sh 192.168.1.43:32000 - -# Check cluster status and health -./scripts/cluster-status.sh - -# Check status of specific namespace -./scripts/cluster-status.sh chronicle -``` - -### **Setup Scripts** -```bash -# Configure insecure registry access for remote nodes -./scripts/configure-insecure-registry-remote.sh 192.168.1.42 - -# Setup NVIDIA GPU operator -./scripts/setup-nvidia-operator.sh -``` - -### **Maintenance Scripts** -```bash -# Clean up all deployments (with confirmation) -./scripts/cleanup-all.sh - -# Force cleanup without confirmation -./scripts/cleanup-all.sh --force -``` - -### **GPU Testing Scripts** -```bash -# Test GPU access in Kubernetes -./scripts/test-gpu-pod.sh - -# Test with specific GPU count -./scripts/test-gpu-pod.sh 2 -``` - -### **Configuration Scripts** -```bash -# Generate ConfigMap data template from .env file -./scripts/generate-configmap.sh - -# This creates a Helm template that can be included in charts -# Output: backends/charts/backend/templates/env-data.yaml -``` - -**Note**: All scripts automatically read configuration from `skaffold.env` and provide helpful error messages if configuration is missing. - -**When to use generate-configmap.sh**: Use this script when you want to: -- Create environment-specific ConfigMaps from `.env` files -- Generate Helm templates that can be included in other charts -- Manage environment variables in a more maintainable way -- Override the default hardcoded values in the Helm charts - -**Removed Scripts**: The following scripts were removed as they are no longer needed: -- `generate-helm-configmap.sh` - Environment variables are now handled automatically by Skaffold - -## Kubernetes Manifests - -**Location**: `k8s-manifests/` directory - -This directory contains standalone Kubernetes manifests that are not managed by Skaffold: - -- **`hostpath-provisioner-official.yaml`** - OpenEBS hostpath storage provisioner - - Applied manually: `kubectl apply -f k8s-manifests/hostpath-provisioner-official.yaml` - - Creates the `openebs-hostpath` storage class used by all services - -## Deployment - -**Run on: Build Machine (Your Development Machine)** - -1. **Deploy All Services (Recommended)** - ```bash - # Deploy everything in the correct order - ./scripts/deploy-all-services.sh - - # This will automatically: - # - Deploy infrastructure (MongoDB, FalkorDB) - # - Deploy main application (Backend, WebUI) - # - Deploy additional services (if configured) - # - Wait for each service to be ready - # - Verify all deployments - ``` - -2. **Manual Deployment (Alternative)** +2. To add a node, run `microk8s add-node` on an existing node, then run the + printed `microk8s join ...` command on the new node. +3. On one node, enable the add-ons: ```bash - # Deploy infrastructure first - skaffold run --profile=infrastructure - - # Wait for infrastructure to be ready - kubectl get pods -n root - - # Deploy main application - skaffold run --profile=backend --default-repo=192.168.1.42:32000 - - # Monitor deployment - skaffold run --profile=backend --default-repo=192.168.1.42:32000 --tail + microk8s enable dns ingress metrics-server registry ``` + The registry listens on port `32000`. Check it with + `curl http://localhost:32000/v2/`. +4. Install the OpenEBS local hostpath provisioner + ([OpenEBS docs](https://openebs.io/docs)). The charts use the storage class + `openebs-hostpath`. Check it with `kubectl get storageclass`. +5. GPU nodes only: install the NVIDIA GPU operator with + `scripts/k8s/gpu/setup-nvidia-operator.sh`, then test it with + `scripts/k8s/gpu/test-gpu-pod.sh`. -3. **Verify Deployment** - ```bash - # Check all resources - kubectl get all -n chronicle - kubectl get all -n root - - # Check Ingress - kubectl get ingress -n chronicle - - # Check services - kubectl get svc -n chronicle - ``` - -## Multi-Node Cluster Management - -**Run on: Build Machine (Your Development Machine)** - -### **Cluster Status and Management** -```bash -# View all nodes in the cluster -kubectl get nodes -o wide - -# Get detailed node information -kubectl describe node k8s_control_plane -kubectl describe node k8s_worker_01 - -# Check node resources -kubectl top nodes - -# View node labels and taints -kubectl get nodes --show-labels -``` - -### **Pod Scheduling and Distribution** -```bash -# Check pod distribution across nodes -kubectl get pods -A -o wide - -# Force pod scheduling to specific node (if needed) -kubectl label node k8s_worker_01 node-role.kubernetes.io/worker=true - -# Check node capacity and allocatable resources -kubectl describe node k8s_worker_01 | grep -A 5 "Allocated resources" -``` - -### **Worker Node Maintenance** -```bash -# Drain a worker node before maintenance -kubectl drain k8s_worker_01 --ignore-daemonsets --delete-emptydir-data - -# After maintenance, uncordon the node -kubectl uncordon k8s_worker_01 - -# Remove a worker node from the cluster -kubectl delete node k8s_worker_01 -``` - -## Additional Services Deployment - -**Run on: Build Machine (Your Development Machine)** +## 2. Prepare the build machine -### 1. **Speaker Recognition Service** +Install these tools: -```bash -# Deploy speaker recognition with GPU support -skaffold run --profile=speaker-recognition --default-repo=k8s_control_plane:32000 - -# Monitor deployment -skaffold run --profile=speaker-recognition --default-repo=k8s_control_plane:32000 --tail - -# Verify deployment -kubectl get pods -n speech -kubectl get svc -n speech -``` - -### 2. **ASR (Automatic Speech Recognition) Services** +| Tool | Used for | +|---|---| +| `kubectl` | talking to the cluster (needs a kubeconfig for it) | +| `skaffold` | building and deploying | +| `helm` | the charts that Skaffold deploys | +| Docker with `buildx` | building images | +| `uv` | running the config scripts (`make config-k8s`) | +Then clone the repository: ```bash -# Deploy ASR services (Moonshine, Parakeet) -skaffold run --profile=asr-services --default-repo=k8s_control_plane:32000 - -# Monitor deployment -skaffold run --profile=asr-services --default-repo=k8s_control_plane:32000 --tail - -# Verify deployment -kubectl get pods -n asr -kubectl get svc -n asr +git clone https://github.com/SimpleOpenSoftware/chronicle.git +cd chronicle ``` -### 3. **NVIDIA GPU Operator Setup** - -**Prerequisites:** -- NVIDIA GPU(s) installed on the Kubernetes node -- NVIDIA drivers installed on the host system +## 3. Configure -**Installation:** -```bash -# Use the automated setup script -./scripts/setup-nvidia-operator.sh - -# Or manually install: -# Add NVIDIA Helm repository -helm repo add nvidia https://helm.ngc.nvidia.com/nvidia -helm repo update - -# Install NVIDIA GPU Operator -helm install gpu-operator nvidia/gpu-operator \ - --namespace gpu-operator \ - --create-namespace \ - --set driver.enabled=false \ - --set toolkit.enabled=false - -# Wait for GPU operator to be ready -kubectl wait --for=condition=ready pod -l app.kubernetes.io/name=gpu-operator -n gpu-operator --timeout=300s - -# Verify GPU detection -kubectl get nodes -o json | jq '.items[] | {name: .metadata.name, gpu: .status.allocatable."nvidia.com/gpu"}' - -# Check GPU operator pods -kubectl get pods -n gpu-operator -``` - -**GPU-Enabled Pod Configuration:** -```yaml -# Example pod spec with GPU access -spec: - containers: - - name: gpu-container - image: nvidia/cuda:11.8-base-ubuntu20.04 - resources: - limits: - nvidia.com/gpu: 1 - command: ["nvidia-smi"] -``` +All deploy settings live in one file, `config.env`. It is gitignored. -**Test GPU Access:** ```bash -# Test GPU functionality -./scripts/test-gpu-pod.sh - -# Test with multiple GPUs -./scripts/test-gpu-pod.sh 2 +cp config.env.template config.env ``` -## Verification - -**Run on: Build Machine (Your Development Machine)** - -1. **Check Application Health** - ```bash - # Check backend health - curl -k https://chronicle.192-168-1-42.nip.io:32623/health +Edit at least these values: - # Check WebUI - curl -k https://chronicle.192-168-1-42.nip.io:32623/ - ``` +| Variable | Meaning | +|---|---| +| `CONTAINER_REGISTRY` | the cluster registry, for example `:32000` | +| `INFRASTRUCTURE_NAMESPACE` | namespace of MongoDB and Redis | +| `APPLICATION_NAMESPACE` | namespace of the backend and WebUI | +| `DOMAIN`, `DOMAIN_PREFIX`, `EXTERNAL_DOMAIN` | host names for the ingress | +| `MONGO_ROOT_PASSWORD` | the backend logs in to MongoDB as `root` with it | +| `AUTH_SECRET_KEY`, `ADMIN_EMAIL`, `ADMIN_PASSWORD` | login | +| `OPENAI_API_KEY`, `DEEPGRAM_API_KEY` | LLM and speech-to-text providers | -2. **Access WebUI** - - Open browser to: `https://chronicle.192-168-1-42.nip.io:32623/` - - Accept self-signed certificate warning - - Create admin user account - - Test audio recording functionality +For speaker recognition, also set: -3. **Test WebSocket Connection** - - Open browser console - - Check for WebSocket connection success - - Verify audio recording works +| Variable | Meaning | +|---|---| +| `HF_TOKEN` | Hugging Face token for the pyannote models | +| `COMPUTE_MODE` | `cpu`, `cu126` or `cu128`. Use `cu126` for Pascal GPUs (GTX 10xx); `cu128` drops them | +| `SPEAKER_NODE` | the node with the NVIDIA GPU | +| `BUILDX_BUILDER` | an amd64 buildx builder (`docker buildx ls` lists them) | +| `SPEAKER_SERVICE_URL` | the backend's in-cluster address of the speaker service | -## Troubleshooting +Application settings (models, memory, plugins) live in `config/config.yml`, +`config/defaults.yml` and `config/plugins.yml`, the same as for Docker Compose. -### Common Issues +`make config-k8s` turns these into the files the deploy uses. It runs before +every deploy, so you do not edit these files: -1. **Registry Access Issues** - ```bash - # Test registry connectivity (run on Kubernetes node) - curl http://k8s_control_plane:32000/v2/ +| Generated file | Contents | +|---|---| +| `k8s-manifests/configmap.yaml` | `config.env` values, plus the three `config/*.yml` files | +| `k8s-manifests/secrets.yaml` | values whose name contains `SECRET`, `KEY`, `TOKEN` or `PASSWORD` (mode 600) | +| `skaffold.env` | the `config.env` values that `skaffold.yaml` uses | - # Check MicroK8s containerd config (run on Kubernetes node) - sudo cat /var/snap/microk8s/current/args/certs.d/k8s_control_plane:32000/hosts.toml - ``` +It applies the ConfigMap and Secret to `APPLICATION_NAMESPACE`, and copies them +to the `speech` namespace. All three files are gitignored. -2. **Storage Issues** - ```bash - # Check storage class (run on build machine) - kubectl get storageclass - - # Check persistent volumes (run on build machine) - kubectl get pv - kubectl get pvc -A - ``` - -3. **Ingress Issues** - ```bash - # Check Ingress controller (run on build machine) - kubectl get pods -n ingress-nginx - - # Check Ingress configuration (run on build machine) - kubectl describe ingress -n chronicle - ``` - -4. **Build Issues** - ```bash - # Clean and rebuild (run on build machine) - skaffold clean - skaffold run --profile=backend --default-repo=k8s_control_plane:32000 - ``` - -5. **GPU Issues** - ```bash - # Check GPU operator status (run on build machine) - kubectl get pods -n gpu-operator - kubectl describe pod -n gpu-operator - - # Check GPU detection on nodes - kubectl get nodes -o json | jq '.items[] | {name: .metadata.name, gpu: .status.allocatable."nvidia.com/gpu"}' - - # Check GPU operator logs - kubectl logs -n gpu-operator deployment/gpu-operator - - # Verify NVIDIA drivers on host (run on Kubernetes node) - nvidia-smi - ``` - -6. **Multi-Node Cluster Issues** - ```bash - # Check node connectivity (run on build machine) - kubectl get nodes - kubectl describe node - - # Check node status and conditions - kubectl get nodes -o json | jq '.items[] | {name: .metadata.name, status: .status.conditions[] | select(.type=="Ready") | .status, message: .message}' - - # Check if pods can be scheduled - kubectl get pods -A -o wide - kubectl describe pod -n - - # Check node resources and capacity - kubectl top nodes - kubectl describe node | grep -A 10 "Allocated resources" - - # Verify network connectivity between nodes - # Run on each node: - ping - curl -s http://:32000/v2/ # Registry access - ``` - -### Useful Commands +## 4. First-time setup ```bash -# View logs (run on build machine) -kubectl logs -n chronicle deployment/backend -kubectl logs -n chronicle deployment/webui - -# Port forward for debugging (run on build machine) -kubectl port-forward -n chronicle svc/backend 8000:8000 -kubectl port-forward -n chronicle svc/webui 8080:80 - -# Check resource usage (run on build machine) -kubectl top pods -n chronicle -kubectl top nodes - -# Restart deployments (run on build machine) -kubectl rollout restart deployment/backend -n chronicle -kubectl rollout restart deployment/webui -n chronicle +make setup-k8s ``` -## Maintenance - -**Run on: Build Machine (Your Development Machine)** - -1. **Regular Updates** - ```bash - # Update Docker images - skaffold run --profile=backend --default-repo=k8s_control_plane:32000 - ``` +It asks for the registry node's IP address, then: -**Run on: Kubernetes Node (k8s_control_plane)** +1. lets that node pull from the insecure registry + (`scripts/k8s/configure-insecure-registry-remote.sh [ssh_user]`; run it + again for each other node); +2. prepares the shared model storage for speaker recognition + (`scripts/k8s/setup-storage.sh`); +3. runs `make config-k8s`; +4. deploys MongoDB and Redis (`make setup-infrastructure`); +5. applies the cross-namespace RBAC (`make setup-rbac`); +6. creates the shared models PVC (`make setup-storage-pvc`). -1. **System Updates** - ```bash - # Update system packages - sudo apt update && sudo apt upgrade -y +Optional, for Tailscale access: `kubectl apply -n -f +k8s-manifests/tailscale-ingress.yaml`. No `make` target applies it. It needs the +Tailscale Kubernetes operator, and its `tailscale.com/proxy-group` annotation +names a ProxyGroup: change it to one in your tailnet. - # Update MicroK8s - sudo snap refresh microk8s - ``` +## 5. Deploy -2. **Backup Configuration** - ```bash - # Backup environment files (run on build machine) - cp backend/.env backend/.env.backup - cp skaffold.env skaffold.env.backup +| Command | What it deploys | +|---|---| +| `make deploy` | backend and WebUI (it runs `deploy-k8s` when `DEPLOYMENT_MODE = kubernetes`) | +| `make deploy-speaker` | speaker recognition, in the `speech` namespace | +| `make deploy-k8s-full` | MongoDB and Redis, then backend and WebUI | - # Backup Kubernetes manifests (run on build machine) - kubectl get all -n chronicle -o yaml > chronicle-backup.yaml - kubectl get all -n root -o yaml > infrastructure-backup.yaml - ``` +`make deploy-apps` and `make deploy-k8s` are the same as `make deploy` in +Kubernetes mode. -## Alternative: Docker Compose Setup +Every deploy runs `make config-k8s` first, then `skaffold run` with a profile. +The backend profile builds two images: -If you prefer to use Docker Compose instead of Kubernetes, use the `init.sh` script: +- `backend` from `backend/Dockerfile.k8s`. It runs the API with the workers as + a sidecar container in the same pod. +- `webui` from `backend/webui/Dockerfile.k8s`. -**Run on: Build Machine (Your Development Machine)** +`make deploy-speaker` builds its two images for amd64 with +`scripts/k8s/buildx-push.sh` on `BUILDX_BUILDER`, and pins the pod to +`SPEAKER_NODE`. +The ASR services have no `make` target. Deploy them with Skaffold directly: ```bash -# Make script executable -chmod +x init.sh - -# Run interactive setup -./init.sh -``` - -This will guide you through setting up Chronicle using Docker Compose instead of Kubernetes. - -## Speaker Recognition Deployment - -For standalone speaker recognition deployment (without full Kubernetes setup): - -**Run on: Build Machine (Your Development Machine)** - +set -a; source skaffold.env; set +a +skaffold run --profile=parakeet-asr --default-repo= # or moonshine-asr +``` + +## 6. Settings changed in the app + +Under Docker Compose, the Settings page writes to `config/` on the host. In +Kubernetes the backend and workers use `/app/data/config` on the data volume +(`CONFIG_DIR`). A ConfigMap is read-only, so it is only the seed. + +Each time the pod starts, the `config-seed` init container +(`backend/src/backend/config_seed.py`) updates that folder from the ConfigMap: + +- `defaults.yml` is always replaced. It holds code defaults, not settings. +- `config.yml` and `plugins.yml` are copied the first time. After that, every + setting already in the live file keeps its live value. Only keys that are new + in the repository are added. + +So a redeploy never undoes a change made in the app. Two results of this: + +- If you change an existing value in `config/config.yml`, a redeploy does not + apply it. Change it in the app instead, or edit the live file (the image has + no editor, so copy it out and back): + ```bash + POD=$(kubectl get pod -n -l app.kubernetes.io/name=backend -o name | head -1) + kubectl cp -n -c backend ${POD#pod/}:/app/data/config/config.yml live-config.yml + # edit live-config.yml, then: + kubectl cp -n -c backend live-config.yml ${POD#pod/}:/app/data/config/config.yml + kubectl rollout restart -n deploy/backend + ``` +- A list is one value. If the live file has a `models:` list, a model added to + the repository's list does not appear. + +## 7. Check and maintain + +| Command | What it does | +|---|---| +| `make k8s-status` | cluster health (`scripts/k8s/cluster-status.sh [namespace]`) | +| `make check-apps` | pods and services in `APPLICATION_NAMESPACE` | +| `make check-infrastructure` | pods and services in `INFRASTRUCTURE_NAMESPACE` | +| `make k8s-cleanup` | frees registry storage | +| `make k8s-purge` | removes unused images from the registry and nodes | + +Useful `kubectl` commands: ```bash -# Make script executable -chmod +x deploy-speaker-recognition.sh - -# Run deployment -./deploy-speaker-recognition.sh -``` - -This script handles speaker recognition service deployment with proper environment configuration. - -## Support - -For additional support: -- Check the main [README.md](README.md) -- Review [AGENTS.md](AGENTS.md) for development notes - ---- - -**Note**: This setup supports both single-node and multi-node MicroK8s clusters. For production use, multi-node clusters provide better reliability, scalability, and resource distribution. The worker node installation section above provides complete instructions for expanding your cluster. +kubectl logs -n deploy/backend -c backend +kubectl logs -n deploy/backend -c backend-workers +kubectl logs -n deploy/backend -c config-seed +kubectl logs -n deploy/webui +kubectl port-forward -n svc/backend 8000:8000 +kubectl rollout restart -n deploy/backend +``` + +Check the backend: `curl http:///health`. + +## 8. Troubleshooting + +- **Image pull fails**: the node does not trust the registry. Run + `scripts/k8s/configure-insecure-registry-remote.sh ` for that node. +- **PVC stays `Pending`**: check `kubectl get storageclass` for + `openebs-hostpath`. +- **Settings page says the config is read-only**: the pod still mounts the + ConfigMap. This happens only with `persistence.enabled=false`. +- **`make config-k8s` says "config.env is missing Skaffold variables"**: add the + named variables to `config.env`. Run the script through `make`, which loads + `config.env`; run alone, it sees no values. +- **GPU pod is `Pending`**: check + `kubectl get nodes -o json | jq '.items[] | {name: .metadata.name, gpu: .status.allocatable."nvidia.com/gpu"}'` + and the GPU operator pods (`kubectl get pods -n gpu-operator`). Run + `nvidia-smi` on the node. If the driver does not load on a Secure Boot + machine, its signing key may not be enrolled. + +## 9. Known limitations + +- `skaffold.yaml` names cluster nodes directly: the backend and WebUI are pinned + to `anubis`, and the shared model storage lists `anubis` and `babel`. Edit + these for your cluster. +- The `infrastructure` profile deploys MongoDB with authentication off, but the + backend logs in as `root` with `MONGO_ROOT_PASSWORD`. On a new cluster, enable + MongoDB authentication with that password, or use a MongoDB that has it. +- The backend data volume is `ReadWriteOnce`. The backend pod uses `Recreate`, + so a deploy stops the old pod before it starts the new one. +- For Docker Compose instead of Kubernetes, use `./wizard.sh` and `./services` + (see [quickstart.md](quickstart.md)). diff --git a/config.env.template b/config.env.template index f24d2ed29..660d20470 100644 --- a/config.env.template +++ b/config.env.template @@ -80,6 +80,8 @@ PARAKEET_ASR_URL = http://host.docker.internal:8767 # MongoDB URIs MONGODB_URI = mongodb://mongo:$(MONGODB_PORT) MONGODB_K8S_URI = mongodb://mongodb.$(INFRASTRUCTURE_NAMESPACE).svc.cluster.local:27017/friend +# Mongo root password. The k8s backend logs in as root with it (skaffold.yaml MONGODB_URI). +MONGO_ROOT_PASSWORD = change-me # ======================================== # MEMORY PROVIDER CONFIGURATION From 703648a4ad7a5a5bbc1b4dafc6feb69c94de6ed9 Mon Sep 17 00:00:00 2001 From: Stu Alexander Date: Mon, 9 Nov 2026 17:24:05 +0000 Subject: [PATCH 8/8] feat(k8s): set node pins and the Tailscale ingress from config.env skaffold.yaml pinned the backend and WebUI to one named node, and the Tailscale ingress was a hand-applied manifest with a fixed hostname and ProxyGroup. Both now come from config.env: - APP_NODE pins the backend, workers and WebUI (a new `node` chart value). - TAILSCALE_HOSTNAME and TAILSCALE_PROXY_GROUP make the backend chart create the Tailscale ingress on make deploy. k8s-manifests/ tailscale-ingress.yaml is removed. - The speaker chart no longer defaults to a named GPU node; SPEAKER_NODE sets it. An empty value turns each one off. The shared-model node list that skaffold.yaml passed to the speaker chart is removed: no template read it. Co-Authored-By: Claude Opus 5.5 --- README-K8S.md | 17 ++++---- .../charts/backend/templates/deployment.yaml | 6 ++- .../backend/templates/tailscale-ingress.yaml | 41 +++++++++++++++++++ .../backend/templates/workers-deployment.yaml | 6 ++- backends/charts/backend/values.yaml | 13 ++++++ .../charts/webui/templates/deployment.yaml | 6 ++- backends/charts/webui/values.yaml | 2 + config.env.template | 10 +++++ .../charts/templates/speaker-deployment.yaml | 4 +- .../charts/templates/webui-deployment.yaml | 4 +- extras/speaker-recognition/charts/values.yaml | 5 +-- k8s-manifests/tailscale-ingress.yaml | 25 ----------- scripts/generate-k8s-configs.py | 5 ++- scripts/lib/env_utils.py | 12 ++++++ skaffold.yaml | 14 +++---- 15 files changed, 117 insertions(+), 53 deletions(-) create mode 100644 backends/charts/backend/templates/tailscale-ingress.yaml delete mode 100644 k8s-manifests/tailscale-ingress.yaml diff --git a/README-K8S.md b/README-K8S.md index d7cefe5e1..c955ba096 100644 --- a/README-K8S.md +++ b/README-K8S.md @@ -94,6 +94,14 @@ For speaker recognition, also set: | `BUILDX_BUILDER` | an amd64 buildx builder (`docker buildx ls` lists them) | | `SPEAKER_SERVICE_URL` | the backend's in-cluster address of the speaker service | +Optional. Leave a value empty to turn it off: + +| Variable | Meaning | +|---|---| +| `APP_NODE` | pin the backend and WebUI pods to this node | +| `TAILSCALE_HOSTNAME` | serve the API and WebUI at `https://..ts.net` (needs the Tailscale Kubernetes operator) | +| `TAILSCALE_PROXY_GROUP` | the Tailscale ProxyGroup for that ingress. Empty: the operator makes a proxy for it | + Application settings (models, memory, plugins) live in `config/config.yml`, `config/defaults.yml` and `config/plugins.yml`, the same as for Docker Compose. @@ -127,10 +135,8 @@ It asks for the registry node's IP address, then: 5. applies the cross-namespace RBAC (`make setup-rbac`); 6. creates the shared models PVC (`make setup-storage-pvc`). -Optional, for Tailscale access: `kubectl apply -n -f -k8s-manifests/tailscale-ingress.yaml`. No `make` target applies it. It needs the -Tailscale Kubernetes operator, and its `tailscale.com/proxy-group` annotation -names a ProxyGroup: change it to one in your tailnet. +For Tailscale access, set `TAILSCALE_HOSTNAME` in `config.env`. `make deploy` +then creates the ingress with the backend chart. ## 5. Deploy @@ -230,9 +236,6 @@ Check the backend: `curl http:///health`. ## 9. Known limitations -- `skaffold.yaml` names cluster nodes directly: the backend and WebUI are pinned - to `anubis`, and the shared model storage lists `anubis` and `babel`. Edit - these for your cluster. - The `infrastructure` profile deploys MongoDB with authentication off, but the backend logs in as `root` with `MONGO_ROOT_PASSWORD`. On a new cluster, enable MongoDB authentication with that password, or use a MongoDB that has it. diff --git a/backends/charts/backend/templates/deployment.yaml b/backends/charts/backend/templates/deployment.yaml index e922138d4..c30af64ce 100644 --- a/backends/charts/backend/templates/deployment.yaml +++ b/backends/charts/backend/templates/deployment.yaml @@ -156,7 +156,11 @@ spec: hostAliases: {{- toYaml . | nindent 8 }} {{- end }} - {{- with .Values.nodeSelector }} + {{- $nodeSelector := deepCopy (.Values.nodeSelector | default dict) }} + {{- with .Values.node }} + {{- $_ := set $nodeSelector "kubernetes.io/hostname" . }} + {{- end }} + {{- with $nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} {{- end }} diff --git a/backends/charts/backend/templates/tailscale-ingress.yaml b/backends/charts/backend/templates/tailscale-ingress.yaml new file mode 100644 index 000000000..9c54f7113 --- /dev/null +++ b/backends/charts/backend/templates/tailscale-ingress.yaml @@ -0,0 +1,41 @@ +{{- with .Values.tailscale.hostname }} +{{- $backend := include "backend.fullname" $ }} +{{- $port := $.Values.service.port }} +# Tailnet entry point: https://{{ . }}..ts.net +# One Ingress for the API and the WebUI, because a Tailscale hostname can belong +# to only one Ingress. Backend paths match ingress-values.yaml. +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: {{ $backend }}-tailscale + labels: + {{- include "backend.labels" $ | nindent 4 }} + {{- with $.Values.tailscale.proxyGroup }} + annotations: + tailscale.com/proxy-group: {{ . | quote }} + {{- end }} +spec: + ingressClassName: tailscale + tls: + - hosts: + - {{ . | quote }} + rules: + - http: + paths: + {{- range list "/api" "/auth" "/users" "/ws" "/health" "/readiness" "/audio" }} + - path: {{ . }} + pathType: Prefix + backend: + service: + name: {{ $backend }} + port: + number: {{ $port }} + {{- end }} + - path: / + pathType: Prefix + backend: + service: + name: {{ $.Values.tailscale.webuiService }} + port: + number: {{ $.Values.tailscale.webuiPort }} +{{- end }} diff --git a/backends/charts/backend/templates/workers-deployment.yaml b/backends/charts/backend/templates/workers-deployment.yaml index 94350b661..051ceae64 100644 --- a/backends/charts/backend/templates/workers-deployment.yaml +++ b/backends/charts/backend/templates/workers-deployment.yaml @@ -95,7 +95,11 @@ spec: hostAliases: {{- toYaml . | nindent 8 }} {{- end }} - {{- with .Values.workers.nodeSelector | default .Values.nodeSelector }} + {{- $nodeSelector := deepCopy ((.Values.workers.nodeSelector | default .Values.nodeSelector) | default dict) }} + {{- with .Values.node }} + {{- $_ := set $nodeSelector "kubernetes.io/hostname" . }} + {{- end }} + {{- with $nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} {{- end }} diff --git a/backends/charts/backend/values.yaml b/backends/charts/backend/values.yaml index 2a63d736f..dbaa22bf4 100644 --- a/backends/charts/backend/values.yaml +++ b/backends/charts/backend/values.yaml @@ -91,6 +91,19 @@ persistence: # Extra /etc/hosts entries, e.g. a Tailnet host the cluster DNS cannot resolve. hostAliases: [] + +# Pin the pods to one node (kubernetes.io/hostname). Empty: any node. +node: "" + +# Tailscale ingress (needs the Tailscale Kubernetes operator). Serves the API +# and the WebUI at https://..ts.net. Empty hostname: none. +tailscale: + hostname: "" + # ProxyGroup to serve it from. Empty: the operator makes a proxy for it. + proxyGroup: "" + webuiService: webui + webuiPort: 80 + nodeSelector: {} tolerations: [] affinity: {} diff --git a/backends/charts/webui/templates/deployment.yaml b/backends/charts/webui/templates/deployment.yaml index 6d57204cc..cd7b35dd5 100644 --- a/backends/charts/webui/templates/deployment.yaml +++ b/backends/charts/webui/templates/deployment.yaml @@ -46,7 +46,11 @@ spec: periodSeconds: 60 resources: {{- toYaml .Values.resources | nindent 12 }} - {{- with .Values.nodeSelector }} + {{- $nodeSelector := deepCopy (.Values.nodeSelector | default dict) }} + {{- with .Values.node }} + {{- $_ := set $nodeSelector "kubernetes.io/hostname" . }} + {{- end }} + {{- with $nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} {{- end }} diff --git a/backends/charts/webui/values.yaml b/backends/charts/webui/values.yaml index 23ea8d74a..a9e0da1f9 100644 --- a/backends/charts/webui/values.yaml +++ b/backends/charts/webui/values.yaml @@ -60,6 +60,8 @@ env: # Other environment variables NODE_ENV: "production" +# Pin the pod to one node (kubernetes.io/hostname). Empty: any node. +node: "" nodeSelector: {} tolerations: [] affinity: {} diff --git a/config.env.template b/config.env.template index 660d20470..15cc8f82c 100644 --- a/config.env.template +++ b/config.env.template @@ -105,6 +105,16 @@ COMPUTE_MODE = cu126 # Node deployment configuration (the node with the NVIDIA GPU) SPEAKER_NODE = xxxxx +# Node for the backend and WebUI pods (kubernetes.io/hostname). Empty: any node. +# The backend data volume is ReadWriteOnce, so the backend stays on one node either way. +APP_NODE = + +# Tailscale ingress for the API and WebUI (needs the Tailscale Kubernetes operator). +# Served at https://..ts.net. Empty hostname: no ingress. +TAILSCALE_HOSTNAME = +# Tailscale ProxyGroup to serve it from. Empty: the operator makes a proxy for it. +TAILSCALE_PROXY_GROUP = + # amd64 buildx builder for k8s images, used by the Skaffold custom builder # (scripts/k8s/buildx-push.sh). List yours with: docker buildx ls BUILDX_BUILDER = xxxxx diff --git a/extras/speaker-recognition/charts/templates/speaker-deployment.yaml b/extras/speaker-recognition/charts/templates/speaker-deployment.yaml index d77f6204d..149725a20 100644 --- a/extras/speaker-recognition/charts/templates/speaker-deployment.yaml +++ b/extras/speaker-recognition/charts/templates/speaker-deployment.yaml @@ -16,9 +16,9 @@ spec: labels: app: {{ .Release.Name }}-speaker spec: - {{- if .Values.nodeSelector.enabled }} + {{- with .Values.nodeSelector.hostname }} nodeSelector: - kubernetes.io/hostname: {{ .Values.nodeSelector.hostname }} + kubernetes.io/hostname: {{ . }} {{- end }} tolerations: - key: "gpu" diff --git a/extras/speaker-recognition/charts/templates/webui-deployment.yaml b/extras/speaker-recognition/charts/templates/webui-deployment.yaml index 3b0337d52..a5e8efb2e 100644 --- a/extras/speaker-recognition/charts/templates/webui-deployment.yaml +++ b/extras/speaker-recognition/charts/templates/webui-deployment.yaml @@ -16,9 +16,9 @@ spec: labels: app: {{ .Release.Name }}-webui spec: - {{- if .Values.nodeSelector.enabled }} + {{- with .Values.nodeSelector.hostname }} nodeSelector: - kubernetes.io/hostname: {{ .Values.nodeSelector.hostname }} + kubernetes.io/hostname: {{ . }} {{- end }} containers: - name: webui diff --git a/extras/speaker-recognition/charts/values.yaml b/extras/speaker-recognition/charts/values.yaml index 0069b4eec..a05ceed33 100644 --- a/extras/speaker-recognition/charts/values.yaml +++ b/extras/speaker-recognition/charts/values.yaml @@ -35,10 +35,9 @@ speaker: SPEAKER_SERVICE_HOST: "0.0.0.0" SPEAKER_SERVICE_PORT: "8085" -# Node selector configuration +# Pin the pods to the GPU node (kubernetes.io/hostname). Empty: any node. nodeSelector: - enabled: true - hostname: "babel" + hostname: "" webui: image: diff --git a/k8s-manifests/tailscale-ingress.yaml b/k8s-manifests/tailscale-ingress.yaml deleted file mode 100644 index b169397fd..000000000 --- a/k8s-manifests/tailscale-ingress.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Tailnet entry point: https://chronicle-pure..ts.net -# One Ingress for both charts, because a Tailscale hostname can belong to only -# one Ingress. Backend paths match backends/charts/backend/ingress-values.yaml. -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: chronicle-pure-ts - annotations: - tailscale.com/proxy-group: ushadow-proxies -spec: - ingressClassName: tailscale - tls: - - hosts: - - chronicle-pure - rules: - - http: - paths: - - { path: /api, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /auth, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /users, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /ws, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /health, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /readiness, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /audio, pathType: Prefix, backend: { service: { name: backend, port: { number: 8000 } } } } - - { path: /, pathType: Prefix, backend: { service: { name: webui, port: { number: 80 } } } } diff --git a/scripts/generate-k8s-configs.py b/scripts/generate-k8s-configs.py index f9125d79e..e43dd4ace 100755 --- a/scripts/generate-k8s-configs.py +++ b/scripts/generate-k8s-configs.py @@ -12,6 +12,7 @@ sys.path.append(str(Path(__file__).parent / "lib")) from env_utils import ( + OPTIONAL_SKAFFOLD_VARIABLES, classify_secrets, format_variable, get_resolved_env_vars, @@ -26,7 +27,7 @@ def generate_skaffold_env(all_vars: dict) -> None: override config.env. Regenerating it here keeps both in step. """ needed = get_skaffold_variables() - missing = sorted(needed - all_vars.keys()) + missing = sorted(needed - all_vars.keys() - OPTIONAL_SKAFFOLD_VARIABLES) if missing: raise SystemExit( f"config.env is missing Skaffold variables: {', '.join(missing)}" @@ -37,7 +38,7 @@ def generate_skaffold_env(all_vars: dict) -> None: "# Edit config.env instead. Contains only variables used by skaffold.yaml.\n\n" ) for name in sorted(needed): - f.write(format_variable(name, all_vars[name], "skaffold") + "\n") + f.write(format_variable(name, all_vars.get(name, ""), "skaffold") + "\n") print(" - skaffold.env") diff --git a/scripts/lib/env_utils.py b/scripts/lib/env_utils.py index ae08e686f..c2ceed02b 100644 --- a/scripts/lib/env_utils.py +++ b/scripts/lib/env_utils.py @@ -65,9 +65,21 @@ def get_skaffold_variables() -> Set[str]: "COMPUTE_MODE", "VITE_ALLOWED_HOSTS", "SPEAKER_NODE", + "APP_NODE", + "TAILSCALE_HOSTNAME", + "TAILSCALE_PROXY_GROUP", } +# Skaffold variables that may be empty: an empty value turns the feature off +# (APP_NODE: no node pin; TAILSCALE_HOSTNAME: no Tailscale ingress). +OPTIONAL_SKAFFOLD_VARIABLES = { + "APP_NODE", + "TAILSCALE_HOSTNAME", + "TAILSCALE_PROXY_GROUP", +} + + def format_variable(var_name: str, var_value: str, service_name: str = None) -> str: """Format a variable based on service-specific rules.""" if service_name == "skaffold" and var_name == "VITE_ALLOWED_HOSTS": diff --git a/skaffold.yaml b/skaffold.yaml index 174af7dd0..b2a6e8775 100644 --- a/skaffold.yaml +++ b/skaffold.yaml @@ -76,11 +76,6 @@ profiles: nodeSelector.hostname: "{{.SPEAKER_NODE}}" # Shared models configuration global.sharedModels.enabled: "true" - global.sharedModels.useHostPath: "true" - global.sharedModels.size: "20Gi" - global.sharedModels.hostPath: "/shared/models" - global.sharedModels.nodes[0]: "anubis" - global.sharedModels.nodes[1]: "babel" # Infrastructure profile - deploy once, rarely updated - name: infrastructure @@ -151,8 +146,10 @@ profiles: # Ingress configuration ingress.hosts[0].host: "{{.BACKEND_HOST}}" ingress.hosts[1].host: "{{.EXTERNAL_DOMAIN}}" - # Node selector - nodeSelector.kubernetes\.io/hostname: anubis + # Empty APP_NODE: any node. Empty TAILSCALE_HOSTNAME: no Tailscale ingress. + node: "{{.APP_NODE}}" + tailscale.hostname: "{{.TAILSCALE_HOSTNAME}}" + tailscale.proxyGroup: "{{.TAILSCALE_PROXY_GROUP}}" - name: webui chartPath: backends/charts/webui @@ -164,8 +161,7 @@ profiles: # Ingress configuration ingress.hosts[0].host: "{{.WEBUI_HOST}}" ingress.hosts[1].host: "{{.EXTERNAL_DOMAIN}}" - # Node selector - nodeSelector.kubernetes\.io/hostname: anubis + node: "{{.APP_NODE}}" - name: test-env portForward: