From d6fdc3da837d745e9c03cc08268be95d1d13acd3 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Thu, 10 Sep 2026 13:46:03 -0500 Subject: [PATCH] docs(homelab): add Brain deployment pipeline and dispatcher architecture guides --- .../brain-gitops-deployment-pipeline.md | 172 +++++++++++++++ .../homelab-gitops-dispatcher-architecture.md | 207 ++++++++++-------- 2 files changed, 283 insertions(+), 96 deletions(-) create mode 100644 projects/homelab/guides/brain-gitops-deployment-pipeline.md diff --git a/projects/homelab/guides/brain-gitops-deployment-pipeline.md b/projects/homelab/guides/brain-gitops-deployment-pipeline.md new file mode 100644 index 0000000..048a396 --- /dev/null +++ b/projects/homelab/guides/brain-gitops-deployment-pipeline.md @@ -0,0 +1,172 @@ +--- +type: guide +project: homelab +tags: + - homelab + - brain + - gitops + - gitea + - cicd + - webhook + - doc2site +--- + +# 🧠 Brain GitOps & Auto-Sync Deployment Pipeline + +## 🎯 Overview & Objectives +The **Brain** repository is the canonical data vault and knowledge graph for the homelab ecosystem. To achieve frictionless authoring with absolute data integrity and instantaneous live publishing, Brain employs a zero-delay GitOps synchronization pipeline. + +Any change committed locally flows through a multi-stage pipeline: +1. **Local Pre-commit Gate**: 9-phase integrity check (`validate-brain.py`). +2. **Local Post-commit Trigger**: Automatic push over custom SSH port `2223`. +3. **Gitea CI & Hot Mirroring**: Server-side Actions validation (`act_runner`) and GitHub backup sync. +4. **Webhook Event Dispatch**: Internal HTTP POST to `homelab-gitops` on port `9000`. +5. **Host-Level GitOps Dispatcher**: Zero-delay fast-forward Git pull into the server's `/home/kiskaadee/Brain` instance. +6. **Live Consumer API & Presentation**: Instantaneous rendering via `homelab-doc2site` at `https://docs.roadtotech.me`. + +--- + +## 🏛️ End-to-End Pipeline Architecture + +```mermaid +flowchart TD + subgraph LocalWorkstation["1. Local Author Workstation (~/Brain)"] + AuthorEdit["Author writes note / code"] + GitCommit["git commit -m '...'"] + PreHook["pre-commit hook\n(validate-brain.py: 9 checks)"] + PostHook["post-commit hook\n(auto-push to origin)"] + + AuthorEdit --> GitCommit --> PreHook --> PostHook + end + + subgraph GiteaForge["2. Gitea Forge (gitea.roadtotech.me:2223)"] + GiteaSSH["SSH Port 2223 (git user)"] + ActionsCI["Gitea Actions\n(act_runner: validate.yaml)"] + PushMirror["Push Mirror\n(GitHub Hot Backup)"] + WebhookTrigger["Webhook Event\n(POST -> :9000/hooks/deploy)"] + + GiteaSSH --> ActionsCI + GiteaSSH --> PushMirror + GiteaSSH --> WebhookTrigger + end + + subgraph ServerHost["3. Homeserver Host (192.168.1.36)"] + WebhookDaemon["systemd: homelab-gitops\n(webhook daemon :9000)"] + Dispatcher["gitops_dispatcher.py\n(payload resolver)"] + BrainVault["/home/kiskaadee/Brain\n(git pull --ff-only)"] + + WebhookTrigger --> WebhookDaemon --> Dispatcher --> BrainVault + end + + subgraph Presentation["4. Consumer & Presentation Layer"] + Doc2Site["homelab-doc2site\n(FastAPI / reactive watcher)"] + PublicDocs["https://docs.roadtotech.me\n(Traefik + Authelia / Public)"] + + BrainVault --> Doc2Site --> PublicDocs + end + + PostHook -->|git push| GiteaSSH +``` + +--- + +## 🔍 Detailed Pipeline Stages + +### 1. Local Workstation Hooks (`.githooks/`) + +The repository uses native Git hooks located in `.githooks/` (configured via `git config core.hooksPath .githooks`): + +- **`pre-commit`**: Executes [`scripts/validate-brain.py`](file:///home/kiskaadee/Brain/scripts/validate-brain.py) before finalizing any commit. It enforces: + 1. *No deprecated directories* (`notes/`, `scratch/`, etc.). + 2. *Required root files* (`README.md`, `AGENTS.md`, `flake.nix`, etc.). + 3. *Frontmatter schema* (`type`, `status`, `topics`, `tags`, `project`). + 4. *Relative link validation* (all markdown links resolve to real files). + 5. *Markdown code fence balance*. + 6. *Mermaid diagram validation* (syntax balance, node label quoting). + 7. *Ruff code linting* (Python solutions & scripts). + 8. *Pyright static type checking* (strict typing standards). + 9. *Inbox Curation Exemption* (`inbox/*` is intentionally skipped to preserve zero-friction drafting). + +- **`post-commit`**: Synchronously pushes the current branch to `origin`: + ```bash + CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) + git push origin "$CURRENT_BRANCH" + ``` + It includes offline detection and detached HEAD guards so commits never fail if network connectivity is temporarily unavailable. + +--- + +### 2. Gitea Actions CI (`act_runner`) + +When commits reach Gitea, Gitea Actions triggers `.gitea/workflows/validate.yaml`: + +```yaml +name: Brain Structural Validation + +on: + push: + branches: ["**"] + pull_request: + +jobs: + validate: + name: Validate Markdown Structure & Links + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Run Brain Validator + run: python3 scripts/validate-brain.py +``` + +- **Execution Engine**: Handled by the `homelab-runner` container running `gitea/act_runner:latest` with the `ubuntu-latest:docker://node:18-bullseye` label. +- **Fail-Safe**: If a broken link or syntax defect ever bypassed local checks, the CI status immediately flags the commit in Gitea. + +--- + +### 3. Gitea Webhook & Host Dispatcher + +Upon push completion, Gitea delivers an HTTP POST event to the server's internal webhook daemon: +- **Endpoint**: `http://192.168.1.36:9000/hooks/deploy` +- **Payload**: Gitea JSON push payload detailing repository name (`second-brain`), branch (`refs/heads/main`), and commit SHAs. + +The server's systemd unit (`homelab-gitops`) pipes this payload directly into [`homelab-core/scripts/gitops_dispatcher.py`](file:///home/kiskaadee/Projects/active/homelab/homelab-core/scripts/gitops_dispatcher.py): + +1. `gitops_dispatcher.py` identifies `second-brain` as a core data vault. +2. It resolves the vault target directory to `/home/kiskaadee/Brain`. +3. It runs `git pull --ff-only origin main` in the background. +4. Total execution time from local `git commit` to server synchronization is typically **under 1.5 seconds**. + +--- + +### 4. Consumer API & Live Presentation (`doc2site`) + +- The documentation rendering service (`homelab-doc2site`) runs in Docker and mounts `/home/kiskaadee/Brain` directly into its container filesystem. +- Because `git pull` directly updates the underlying markdown files on the server host, `doc2site` serves the updated knowledge graph immediately upon HTTP request without needing a container rebuild, restart, or cache purge. +- The web portal is accessible at `https://docs.roadtotech.me`. + +--- + +### 5. GitHub Hot Mirroring + +Gitea maintains an automated push mirror to GitHub (`github.com/kiskaadee/second-brain`): +- **Trigger**: Every push event on Gitea immediately triggers an upstream mirror sync. +- **Purpose**: Provides an off-site, immutable disaster-recovery backup while keeping self-hosted Gitea as the primary source of truth. + +--- + +## 🛠️ Verification & Diagnostic Runbook + +| Step | Action | Expected Output | +| :--- | :--- | :--- | +| **1. Local Commit** | `git commit -m "docs: test update"` | Pre-commit passes 9 checks, post-commit auto-pushes to port 2223 | +| **2. Gitea Webhook** | Repository $\rightarrow$ Settings $\rightarrow$ Webhooks $\rightarrow$ Test Delivery | HTTP 200 `Deployment payload dispatched successfully.` | +| **3. Server Pull** | `ssh server-remote "cd ~/Brain && git status"` | `Your branch is up to date with 'origin/main'.` | +| **4. Live Web View** | Open `https://docs.roadtotech.me` | Edited content appears immediately | +| **5. CI Status** | Repository $\rightarrow$ Actions tab in Gitea | Pipeline `Brain Structural Validation` green (✓) | diff --git a/projects/homelab/guides/homelab-gitops-dispatcher-architecture.md b/projects/homelab/guides/homelab-gitops-dispatcher-architecture.md index f061f60..6e0264e 100644 --- a/projects/homelab/guides/homelab-gitops-dispatcher-architecture.md +++ b/projects/homelab/guides/homelab-gitops-dispatcher-architecture.md @@ -8,83 +8,135 @@ tags: - gitea - appctl - automation + - architecture --- # 🚀 Dynamic Decentralized GitOps Dispatcher Architecture -## 🎯 Motivation & Design Principles -In a modular homelab containing multiple containerized web applications (`~/Sites/*`) and data vaults (such as `~/Brain`), deployments must be: -1. **Decoupled from Core Infrastructure**: Deploying a new application or modifying deployment scripts should **never require editing or restarting Core control-plane services** (Traefik, Authelia, Webhook daemon). -2. **Zero Delay & Event-Driven**: Pushing changes to Gitea immediately triggers automated deployment and synchronization over internal LAN endpoints. -3. **Decentralized Self-Describing Manifests**: Each application repository in `~/Sites` defines its own deployment lifecycle inside its local `app.yaml`. -4. **Graceful Defaults for Data Vaults**: Repositories without container stacks (e.g., `second-brain`) automatically default to fast-forward Git pulls (`git pull --ff-only origin main`). +## 🎯 Motivation & Core Invariants + +In a modular homelab containing multiple containerized web applications (`~/Sites/*`), infrastructure control planes (`~/Core`), and data vaults (`~/Brain`), traditional centralized CI/CD configurations create unnecessary friction and blast radius. + +The **Dynamic GitOps Dispatcher** is built around four fundamental architectural invariants: + +1. **Zero Core Restarts (Decoupled Control Plane)**: + Deploying a new application, onboarding a service, or updating deployment routines must **never require restarting or modifying Core infrastructure services** (Traefik, Authelia, Webhook daemon). +2. **Decentralized Manifests (`app.yaml`)**: + Each application repository in `~/Sites` owns and declares its own deployment lifecycle directly within its local `app.yaml` manifest. +3. **Zero Schema Drift**: + There are no centralized deployment tables or static hardcoded lists. The dispatcher discovers target directories and deployment strategies dynamically at runtime. +4. **Graceful Data Vault Fallbacks**: + Repositories without Docker Compose stacks (e.g. `second-brain` data vault) automatically execute clean fast-forward Git pulls (`git pull --ff-only origin `). --- -## 🏛️ End-to-End System Topology +## 🏛️ System Architecture & Components ```mermaid flowchart TD - subgraph Author["1. Author Workstation"] - Commit["git commit"] - PreHook["pre-commit (validate-brain.py)"] - PostHook["post-commit (auto-push)"] - Commit --> PreHook --> PostHook + subgraph GitForge["1. Git Forge (Gitea)"] + Push["Developer Git Push"] + Webhook["HTTP POST (JSON Payload)\nhttp://192.168.1.36:9000/hooks/deploy"] + Push --> Webhook end - subgraph Gitea["2. Self-Hosted Gitea Forge (gitea.roadtotech.me)"] - PushRecv["Gitea receives push on port 2223"] - PushMirror["Push Mirror -> GitHub (Hot Backup)"] - Webhook["HTTP POST -> http://192.168.1.36:9000/hooks/deploy"] - PushRecv --> PushMirror - PushRecv --> Webhook + subgraph CoreDaemon["2. Homelab Control Plane (NixOS systemd)"] + Daemon["homelab-gitops.service\n(pkgs.webhook on port 9000)"] + Engine["gitops_dispatcher.py\n(Dynamic Python 3 Engine)"] + Webhook --> Daemon + Daemon -->|Pipes JSON via stdin| Engine end - subgraph Core["3. Homelab Control Plane (~/Core & NixOS)"] - Daemon["Webhook Daemon (:9000)\n(Permanent 24/7 background service)"] - Engine["gitops_dispatcher.py\n(Dynamic Runtime Discovery)"] - Webhook --> Daemon --> Engine + subgraph Discovery["3. Dynamic Target Resolution Engine"] + Engine --> CheckType{"Resolve Payload"} + CheckType -->|"second-brain"| BrainTarget["Target: ~/Brain\nAction: git pull --ff-only"] + CheckType -->|"homelab- / "| SiteTarget["Target: ~/Sites/\nRead local app.yaml"] + CheckType -->|"Override Registry"| CustomTarget["Target: ~/.config/homelab/deployments.yaml"] end - subgraph Resolution["4. Dynamic Target Resolution"] - Engine --> TypeCheck{"Target Type?"} - TypeCheck -->|"~/Sites/"| AppStack["Read ~/Sites//app.yaml\nExecute declared deployment actions"] - TypeCheck -->|"Data Vault (second-brain)"| BrainSync["Execute git pull --ff-only in ~/Brain"] - TypeCheck -->|"Custom Override"| CustomRegistry["Read ~/.config/homelab/deployments.yaml"] + subgraph Execution["4. Deployment Execution Lifecycle"] + SiteTarget --> ReadManifest["Parse app.yaml (deployment block)"] + ReadManifest --> Actions{"Execute Actions"} + Actions -->|git_pull| GitPull["git pull --ff-only origin main"] + Actions -->|compose_up| ComposeUp["docker compose up -d --remove-orphans"] + Actions -->|compose_build| ComposeBuild["docker compose build && up -d"] + Actions -->|compose_restart| ComposeRestart["docker compose restart"] + Actions -->|custom| CustomCmd["Execute shell command"] end - subgraph Live["5. Live Services"] - AppStack --> Docker["docker compose up -d / appctl"] - BrainSync --> DocSite["homelab-doc2site\n(Live docs.roadtotech.me updated in <1s)"] + subgraph LiveRuntime["5. Live Application State"] + GitPull --> LiveApps["Container / Vault Updated Live (<2s)"] + ComposeUp --> LiveApps + ComposeBuild --> LiveApps + CustomCmd --> LiveApps + BrainTarget --> LiveApps end - - PostHook -->|git push| PushRecv ``` --- -## ⚙️ Manifest Standard (`app.yaml`) +## 🧩 Key System Components -Applications in `~/Sites` can declare an optional `deployment:` block in their `app.yaml`: +### 1. The Declarative Webhook Daemon (`pkgs.webhook`) +The webhook listener is declared immutably via NixOS in [`Config/hosts/server/homeserver.nix`](file:///home/kiskaadee/Config/hosts/server/homeserver.nix): +- **Port**: `9000` (Internal LAN / Tailscale only). +- **Service Name**: `homelab-gitops.service`. +- **Payload Handling**: Configured with `pass-stdin-to-command: true`, streaming the complete Gitea JSON event payload directly into the standard input of the Python dispatcher. + +### 2. The Dynamic Dispatcher Engine ([`gitops_dispatcher.py`](file:///home/kiskaadee/Projects/active/homelab/homelab-core/scripts/gitops_dispatcher.py)) +A zero-dependency Python 3 engine executing on the server host: +- Parses the repository name and ref (`branch`) from standard input. +- Dynamically locates the target directory in `~/Sites` (matching ``, `homelab-`, or data vaults). +- Parses `app.yaml` using a built-in lightweight YAML parser. +- Sequentially executes declared deployment actions. + +### 3. Application Manifest Standard (`app.yaml`) +Placed in the root of each application repository in `~/Sites//app.yaml`: ```yaml name: "doc2site" +aliases: + - "docs" domain: "docs.roadtotech.me" -description: "Reactive Markdown Viewer" +description: "Documentation portal" +visible: true +auth: false +# Deployment Lifecycle Specification deployment: branch: "main" # Target branch to trigger on actions: - - git_pull # Runs: git pull --ff-only origin - - compose_up # Runs: docker compose up -d --remove-orphans - # Optional alternative actions: - # - compose_build # Rebuilds and restarts containers - # - compose_restart # Restarts containers without rebuild - # - custom: "make deploy" # Custom shell command + - git_pull # 1. Pull latest commit via --ff-only + - compose_up # 2. Run docker compose up -d --remove-orphans ``` -If no `deployment:` section is specified, the dispatcher defaults to: +#### Available Deployment Actions: +| Action | Execution Command | Use Case | +| :--- | :--- | :--- | +| `git_pull` | `git -C pull --ff-only origin ` | Standard for code/content updates | +| `compose_up` | `docker compose -f up -d --remove-orphans` | Recreate containers with new config/env | +| `compose_build` | `docker compose build && docker compose up -d` | Applications with local Dockerfiles | +| `compose_restart`| `docker compose restart` | Quick container restart without recreation | +| `custom: ""`| `subprocess.run(cmd, shell=True)` | Custom database migrations or build scripts | + +--- + +## 🛠️ End-to-End Onboarding Guide for New Services + +To onboard any new service into the automated GitOps deployment pipeline: + +### Step 1: Create the Application Repository +Create your repository on Gitea (e.g. `homelab-myapp` or `myapp`). + +### Step 2: Add `app.yaml` Manifest +In the root of your application repository, create `app.yaml`: ```yaml +name: "myapp" +domain: "myapp.roadtotech.me" +description: "My new homelab application" +visible: true +auth: true + deployment: branch: "main" actions: @@ -92,60 +144,23 @@ deployment: - compose_up ``` ---- - -## 🔧 NixOS Server Configuration - -The receiver runs as a declarative systemd unit in `~/Config/hosts/server/homeserver.nix`: - -```nix -# Declarative Dynamic GitOps Webhook Service (Internal Port 9000) -systemd.services.homelab-gitops = { - description = "Dynamic Homelab GitOps Webhook Dispatcher"; - after = [ "network-online.target" "docker.service" ]; - wants = [ "network-online.target" ]; - wantedBy = [ "multi-user.target" ]; - - path = with pkgs; [ git docker docker-compose python3 coreutils bash ]; - - serviceConfig = { - Type = "simple"; - User = "kiskaadee"; - WorkingDirectory = "/home/kiskaadee/Core"; - ExecStart = "${pkgs.webhook}/bin/webhook -hooks ${pkgs.writeText "hooks.json" (builtins.toJSON [ - { - id = "deploy"; - execute-command = "${pkgs.python3}/bin/python3"; - pass-arguments-to-command = [ - { arg = "/home/kiskaadee/Core/scripts/gitops_dispatcher.py"; } - ]; - pass-stdin-to-command = true; - command-working-directory = "/home/kiskaadee/Core"; - response-message = "Deployment payload dispatched successfully."; - } - ])} -port 9000 -verbose"; - Restart = "on-failure"; - RestartSec = "5s"; - }; -}; - -# Open port 9000 in the server firewall -networking.firewall.allowedTCPPorts = [ 80 443 2223 9000 ]; +### Step 3: Clone to Server Host +Clone the repository into `~/Sites` on the server: +```bash +git clone ssh://git@gitea.roadtotech.me:2223/kiskaadee/homelab-myapp.git ~/Sites/homelab-myapp ``` ---- +### Step 4: Configure Webhook in Gitea +1. In Gitea, navigate to **Repository Settings** $\rightarrow$ **Webhooks** $\rightarrow$ **Add Webhook** $\rightarrow$ **Gitea**. +2. **Target URL**: `http://192.168.1.36:9000/hooks/deploy` +3. **HTTP Method**: `POST` +4. **Trigger On**: `Push Events` +5. Click **Add Webhook**. -## 🌐 Configuring Gitea Webhook - -To connect Gitea to the GitOps Dispatcher: - -1. In Gitea, open repository **Settings** $\rightarrow$ **Webhooks** (or **Site Administration** $\rightarrow$ **System Webhooks** for all repositories). -2. Click **Add Webhook** $\rightarrow$ **Gitea**. -3. Set **Target URL**: - ```text - http://192.168.1.36:9000/hooks/deploy - ``` -4. **HTTP Method**: `POST`. -5. **Trigger On**: `Push Events` on `main`. -6. Click **Add Webhook**. -7. Test delivery: Click **Test Delivery** $\rightarrow$ Verify HTTP 200 with response `Deployment payload dispatched successfully.`. +### Step 5: Test & Verify +Push a commit from your workstation: +```bash +git commit -m "feat: initial feature release" +git push origin main +``` +The Gitea webhook fires $\rightarrow$ `gitops_dispatcher.py` pulls the update $\rightarrow$ Docker recreates containers $\rightarrow$ Service is updated live with zero manual SSH commands required.