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/Makefile b/Makefile index 2f19a318a..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-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 @@ -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" @@ -160,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..."; \ @@ -206,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 python3 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..." - @python3 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?)" @@ -265,18 +267,15 @@ 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-k8s-full: deploy-infrastructure deploy-apps ## Deploy infrastructure + applications to Kubernetes - @echo "βœ… Full 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-infrastructure: ## Deploy infrastructure services to Kubernetes - @echo "πŸ—οΈ Deploying infrastructure services..." - @kubectl apply -f k8s-manifests/ - @echo "βœ… Infrastructure deployment completed" +deploy-k8s-full: setup-infrastructure deploy-k8s ## Deploy infrastructure + applications to Kubernetes + @echo "βœ… Full Kubernetes 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 @@ -300,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..." diff --git a/README-K8S.md b/README-K8S.md index ea19c5049..c955ba096 100644 --- a/README-K8S.md +++ b/README-K8S.md @@ -1,824 +1,245 @@ -# 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 - ``` - -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 + 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`. -## 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 +## 2. Prepare the build machine -# Force pod scheduling to specific node (if needed) -kubectl label node k8s_worker_01 node-role.kubernetes.io/worker=true +Install these tools: -# Check node capacity and allocatable resources -kubectl describe node k8s_worker_01 | grep -A 5 "Allocated resources" -``` +| 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`) | -### **Worker Node Maintenance** +Then clone the repository: ```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 +git clone https://github.com/SimpleOpenSoftware/chronicle.git +cd chronicle ``` -## Additional Services Deployment +## 3. Configure -**Run on: Build Machine (Your Development Machine)** - -### 1. **Speaker Recognition Service** +All deploy settings live in one file, `config.env`. It is gitignored. ```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 +cp config.env.template config.env ``` -### 2. **ASR (Automatic Speech Recognition) Services** - -```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 +Edit at least these values: -# Verify deployment -kubectl get pods -n asr -kubectl get svc -n asr -``` +| 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 | -### 3. **NVIDIA GPU Operator Setup** +For speaker recognition, also set: -**Prerequisites:** -- NVIDIA GPU(s) installed on the Kubernetes node -- NVIDIA drivers installed on the host system +| 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 | -**Installation:** -```bash -# Use the automated setup script -./scripts/setup-nvidia-operator.sh +Optional. Leave a value empty to turn it off: -# Or manually install: -# Add NVIDIA Helm repository -helm repo add nvidia https://helm.ngc.nvidia.com/nvidia -helm repo update +| 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 | -# Install NVIDIA GPU Operator -helm install gpu-operator nvidia/gpu-operator \ - --namespace gpu-operator \ - --create-namespace \ - --set driver.enabled=false \ - --set toolkit.enabled=false +Application settings (models, memory, plugins) live in `config/config.yml`, +`config/defaults.yml` and `config/plugins.yml`, the same as for Docker Compose. -# 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 +`make config-k8s` turns these into the files the deploy uses. It runs before +every deploy, so you do not edit these files: -# Verify GPU detection -kubectl get nodes -o json | jq '.items[] | {name: .metadata.name, gpu: .status.allocatable."nvidia.com/gpu"}' +| 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 GPU operator pods -kubectl get pods -n gpu-operator -``` +It applies the ConfigMap and Secret to `APPLICATION_NAMESPACE`, and copies them +to the `speech` namespace. All three files are gitignored. -**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"] -``` +## 4. First-time setup -**Test GPU Access:** ```bash -# Test GPU functionality -./scripts/test-gpu-pod.sh - -# Test with multiple GPUs -./scripts/test-gpu-pod.sh 2 +make setup-k8s ``` -## Verification +It asks for the registry node's IP address, then: -**Run on: Build Machine (Your Development Machine)** +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. **Check Application Health** - ```bash - # Check backend health - curl -k https://chronicle.192-168-1-42.nip.io:32623/health +For Tailscale access, set `TAILSCALE_HOSTNAME` in `config.env`. `make deploy` +then creates the ingress with the backend chart. - # Check WebUI - curl -k https://chronicle.192-168-1-42.nip.io:32623/ - ``` +## 5. Deploy -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 +| 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 | -3. **Test WebSocket Connection** - - Open browser console - - Check for WebSocket connection success - - Verify audio recording works +`make deploy-apps` and `make deploy-k8s` are the same as `make deploy` in +Kubernetes mode. -## Troubleshooting +Every deploy runs `make config-k8s` first, then `skaffold run` with a profile. +The backend profile builds two images: -### Common Issues +- `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`. -1. **Registry Access Issues** - ```bash - # Test registry connectivity (run on Kubernetes node) - curl http://k8s_control_plane:32000/v2/ - - # Check MicroK8s containerd config (run on Kubernetes node) - sudo cat /var/snap/microk8s/current/args/certs.d/k8s_control_plane:32000/hosts.toml - ``` - -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 - -```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 -``` - -## 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 - ``` - -**Run on: Kubernetes Node (k8s_control_plane)** - -1. **System Updates** - ```bash - # Update system packages - sudo apt update && sudo apt upgrade -y - - # Update MicroK8s - sudo snap refresh microk8s - ``` - -2. **Backup Configuration** - ```bash - # Backup environment files (run on build machine) - cp backend/.env backend/.env.backup - cp skaffold.env skaffold.env.backup - - # 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 - ``` - -## Alternative: Docker Compose Setup - -If you prefer to use Docker Compose instead of Kubernetes, use the `init.sh` script: - -**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 + +- 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/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/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/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..c30af64ce 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 }} @@ -14,11 +18,37 @@ 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 }} 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 }} @@ -34,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 @@ -51,16 +87,17 @@ 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 }} - 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) @@ -78,30 +115,52 @@ 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 }} - 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 + {{- 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: claimName: {{ include "backend.fullname" . }}-data {{- end }} - - name: mem0-ca-cert - configMap: - name: mem0-ca-cert - {{- with .Values.nodeSelector }} + {{- with .Values.hostAliases }} + hostAliases: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- $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 3ee77ee4a..051ceae64 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: @@ -17,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 }}" @@ -33,29 +55,51 @@ 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 }} - 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 + {{- 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: claimName: {{ include "backend.fullname" . }}-data {{- end }} - - name: mem0-ca-cert - configMap: - name: mem0-ca-cert - {{- with .Values.workers.nodeSelector | default .Values.nodeSelector }} + {{- with .Values.hostAliases }} + hostAliases: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- $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 }} @@ -67,3 +111,4 @@ spec: tolerations: {{- toYaml . | nindent 8 }} {{- end }} +{{- end }} diff --git a/backends/charts/backend/values.yaml b/backends/charts/backend/values.yaml index 28c3452af..dbaa22bf4 100644 --- a/backends/charts/backend/values.yaml +++ b/backends/charts/backend/values.yaml @@ -89,6 +89,21 @@ persistence: size: 10Gi mountPath: /app/data +# 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 3f85beba1..15cc8f82c 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 @@ -97,11 +99,26 @@ 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 +# 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 + # React UI settings for speaker recognition REACT_UI_HOST = 0.0.0.0 REACT_UI_PORT = 5173 @@ -119,7 +136,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 d1bafedd6..724f70cd6 100644 --- a/extras/speaker-recognition/Dockerfile-k8s +++ b/extras/speaker-recognition/Dockerfile-k8s @@ -26,12 +26,13 @@ COPY src/ src/ # Install dependencies and package # Use build arg to control CPU vs GPU mode +# 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 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 \ + 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 RUN mkdir -p /app/audio_chunks /app/debug /app/data /models @@ -55,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/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/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 ee4633b54..e43dd4ace 100755 --- a/scripts/generate-k8s-configs.py +++ b/scripts/generate-k8s-configs.py @@ -11,7 +11,35 @@ # 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 ( + OPTIONAL_SKAFFOLD_VARIABLES, + 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() - OPTIONAL_SKAFFOLD_VARIABLES) + 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.get(name, ""), "skaffold") + "\n") + print(" - skaffold.env") def generate_k8s_manifests(namespace: str = "chronicle"): @@ -45,9 +73,22 @@ def generate_k8s_manifests(namespace: str = "chronicle"): escaped_value = var_value.replace('"', '\\"') f.write(f' {var_name}: "{escaped_value}"\n') + # 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 + 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") @@ -78,6 +119,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/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 1cebdb4e4..b2a6e8775 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: @@ -77,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 @@ -124,9 +118,9 @@ profiles: docker: dockerfile: Dockerfile.k8s - image: webui - context: backend/webui + context: . docker: - dockerfile: Dockerfile + dockerfile: backend/webui/Dockerfile.k8s deploy: helm: @@ -142,7 +136,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" @@ -150,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 @@ -163,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: