Compare commits

...
102 Commits
Author SHA1 Message Date
yukkop fbb43b1db9 fix: flake check
runner nix smoke / nix label and flake smoke (push) Canceled after 0s
2026-10-06 21:58:50 +00:00
yukkop 69ee136349 fix: something
runner nix smoke / nix label and flake smoke (push) Canceled after 0s
2026-10-03 16:21:28 +00:00
yukkop be4ea774b2 refactor: gitea runners
runner nix smoke / nix label and flake smoke (push) Failing after 1m22s
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s
2026-10-03 12:30:42 +00:00
yukkop e215c11b0b fix: kanban tui
runner nix smoke / nix label and flake smoke (push) Failing after 1m38s
2026-10-01 23:07:54 +00:00
yukkop a4dfcd3e0f fix: disable http2
runner nix smoke / nix label and flake smoke (push) Failing after 1m15s
2026-10-01 11:41:11 +00:00
yukkop daa61d2253 feat: git lfs to neuro
runner nix smoke / nix label and flake smoke (push) Failing after 1m11s
2026-09-30 23:39:53 +00:00
yukkop e22dcdda80 feat: kanban: coments
runner nix smoke / nix label and flake smoke (push) Failing after 1m17s
2026-09-29 19:48:14 +00:00
yukkop c93dee27b3 feat: gitea: queries
runner nix smoke / nix label and flake smoke (push) Failing after 1m16s
2026-09-29 17:23:48 +00:00
yukkop 3f7856b4aa feat: update pz
runner nix smoke / nix label and flake smoke (push) Failing after 1m50s
2026-09-28 14:50:05 +00:00
yukkop 5b0ae6be5e feat: kanban cli
runner nix smoke / nix label and flake smoke (push) Failing after 1m20s
2026-09-28 09:25:04 +00:00
yukkop 54eb69d1c7 feat: clear unneccessary backend from kanban
runner nix smoke / nix label and flake smoke (push) Failing after 35s
2026-09-28 00:24:44 +00:00
yukkop 0cbf267474 feat: more crud for kanban
runner nix smoke / nix label and flake smoke (push) Failing after 2m6s
2026-09-28 00:08:44 +00:00
yukkop 335a74010d feat: kanban tui
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s
2026-09-27 15:42:51 +00:00
yukkop 4c9611a2d2 some
runner nix smoke / nix label and flake smoke (push) Failing after 1m12s
2026-09-27 08:25:06 +00:00
yukkop 5681519b6f fix: global update
runner nix smoke / nix label and flake smoke (push) Failing after 30s
2026-09-26 22:01:43 +00:00
yukkop fd59158ed6 feat: update nixpkgs
runner nix smoke / nix label and flake smoke (push) Failing after 40s
2026-09-26 21:44:19 +00:00
yukkop d9b2a4e787 feat: update gitea vendor
runner nix smoke / nix label and flake smoke (push) Failing after 1m28s
2026-09-26 21:18:24 +00:00
yukkop c439c1b948 fix: ssh extra debug
runner nix smoke / nix label and flake smoke (push) Failing after 57s
2026-09-26 19:11:41 +00:00
yukkop 0fe85c67d9 ci: staging server
runner nix smoke / nix label and flake smoke (push) Failing after 50s
2026-09-26 13:59:59 +00:00
yukkop 09eecf5969 feat: lfs
runner nix smoke / nix label and flake smoke (push) Failing after 1m59s
2026-09-24 23:15:43 +00:00
yukkop e444ea5936 fix: world-of-sosal
runner nix smoke / nix label and flake smoke (push) Failing after 59s
2026-09-23 19:26:19 +00:00
yukkop c917e4908c feat: zomboid backups
runner nix smoke / nix label and flake smoke (push) Failing after 54s
2026-09-22 17:15:18 +00:00
yukkop ef849b085f fix: wow-minecraft: finish configurations
runner nix smoke / nix label and flake smoke (push) Failing after 56s
2026-09-19 09:04:05 +00:00
yukkop a09f247290 fix: wow-minecraft: mirror on bfs.band
runner nix smoke / nix label and flake smoke (push) Failing after 22s
2026-09-19 08:27:33 +00:00
yukkop 3a52023082 fix: configure minecraft 2026-09-19 08:13:49 +00:00
yukkop 2bd466b652 feat: configure minecraft and zomboid
runner nix smoke / nix label and flake smoke (push) Failing after 1m13s
2026-09-19 07:37:19 +00:00
yukkop 83cf9ff32f .
runner nix smoke / nix label and flake smoke (push) Failing after 55s
2026-09-17 08:37:12 +00:00
yukkop a9e538fc76 feat: prism launcher link 2026-09-16 12:48:15 +00:00
yukkop 88ec8a59d8 feat: site lessons
runner nix smoke / nix label and flake smoke (push) Failing after 17s
2026-09-15 19:48:13 +00:00
yukkopandSisyphus 417820544e fix: raise runner monthly budget
runner nix smoke / nix label and flake smoke (push) Failing after 27s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-15 00:58:07 +00:00
yukkop 1cba36e76e feat: neuro: minecraft mods
runner nix smoke / nix label and flake smoke (push) Has been cancelled
2026-09-14 12:22:10 +00:00
yukkop 4f97fb3244 feat: neuro: new minecraft
runner nix smoke / nix label and flake smoke (push) Failing after 22s
2026-09-13 22:36:11 +00:00
yukkop 252d3418a5 fix: immitch 502
runner nix smoke / nix label and flake smoke (push) Failing after 1m15s
2026-09-13 21:49:57 +00:00
yukkop 96882fd8cd fix: immitch 502
runner nix smoke / nix label and flake smoke (push) Failing after 50s
2026-09-13 19:11:59 +00:00
yukkop 522010b7e6 fix: minecraft
runner nix smoke / nix label and flake smoke (push) Failing after 54s
2026-09-13 18:04:18 +00:00
yukkop 761120b211 fix: anitcheat in project zomboid
runner nix smoke / nix label and flake smoke (push) Failing after 1m21s
2026-09-13 12:58:01 +00:00
yukkop a04a58b792 fix: immich; feat: zomboid settings 2026-09-13 09:38:32 +00:00
yukkop 1e973e7b33 feat: configure immich
runner nix smoke / nix label and flake smoke (push) Failing after 25s
2026-09-12 22:21:33 +00:00
yukkop 66a502b1dd fix: project zomboid module
runner nix smoke / nix label and flake smoke (push) Failing after 1m24s
2026-09-12 21:56:31 +00:00
yukkopandSisyphus fce9ae07be fix: configure Dify Redis connection
runner nix smoke / nix label and flake smoke (push) Failing after 1m18s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-12 19:59:21 +00:00
yukkop a8c4a52a68 feat: olama fix
runner nix smoke / nix label and flake smoke (push) Failing after 1m22s
2026-09-12 18:57:21 +00:00
yukkop 078e01c87f feat: some
runner nix smoke / nix label and flake smoke (push) Failing after 55s
2026-09-11 20:20:57 +00:00
yukkop 6bc564de59 feat: some 2026-09-11 19:31:04 +00:00
yukkop cc8a7cf80e fix: reconcile healthy terminal runners
runner nix smoke / nix label and flake smoke (push) Failing after 28s
2026-09-11 09:19:04 +00:00
yukkop 279df769db fix: retain healthy terminal runners 2026-09-11 09:19:03 +00:00
yukkop 069b18daa3 fix: check runner health before reuse 2026-09-11 09:19:03 +00:00
yukkop 37bd69e90e fix: avoid Cargo metadata IFD 2026-09-11 09:19:03 +00:00
yukkopandSisyphus 572133a941 fix: avoid p4d init IFD
runner nix smoke / nix label and flake smoke (push) Failing after 59s
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-11 08:36:59 +00:00
yukkopandSisyphus ed721dd961 fix: avoid smtp source IFD
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-11 08:36:46 +00:00
yukkop 4a88e7c6e8 fix: runners
runner nix smoke / nix label and flake smoke (push) Failing after 1m1s
2026-09-11 05:58:04 +00:00
yukkop f0317efb6e fix: runners not runs
runner nix smoke / nix label and flake smoke (push) Failing after 41s
2026-09-11 02:22:07 +00:00
yukkop cb62bd3044 feat: maintain server until hour
runner ubuntu smoke / ubuntu-latest label smoke (push) Has been cancelled
runner nix smoke / nix label and flake smoke (push) Has been cancelled
2026-09-11 02:05:39 +00:00
yukkop ee8a33c3b0 feat: move all workers to zero-idle
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s
runner nix smoke / nix label and flake smoke (push) Failing after 7s
2026-09-10 22:30:58 +00:00
yukkop 0a2b96abc2 feat: highmem
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s
runner nix smoke / nix label and flake smoke (push) Failing after 9s
2026-09-10 17:44:56 +00:00
yukkop f286ab632c feat: avility disable cache 2026-09-10 17:24:56 +00:00
yukkop df0638a0f7 feat: new diagnostics
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 15:31:13 +00:00
yukkop b3bcd6d5a8 chore: +ssh key
runner nix smoke / nix label and flake smoke (push) Failing after 7s
2026-09-10 13:32:11 +00:00
yukkop a4a7656459 feat: oh ah
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 13:17:05 +00:00
yukkop 4e1c4638cd feat: nix on runner updated
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 12:44:06 +00:00
yukkop baff2bc29b feat: workflow for deploy hectic-lab 2026-09-10 12:05:46 +00:00
yukkop 76096b4221 feat: immich srorage box config
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 11:57:21 +00:00
yukkop bbe48685fa feat: accurate workflow 2026-09-10 10:29:43 +00:00
yukkop 560eeae963 feat: +nix-downloaf-buffer-check 2026-09-10 10:21:50 +00:00
yukkop 3bb2b05fad feat: +nix-downloaf-buffer-check 2026-09-10 10:19:07 +00:00
yukkop 1665aaf90a fix: workflow neuro timeouts
runner ubuntu smoke / ubuntu-latest label smoke (push) Successful in 0s
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 10:00:28 +00:00
yukkop a100ff2ca7 feat!: migrate attic to 1mb chanks
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 07:23:38 +00:00
yukkop 03ee994482 feat: immich
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-10 06:14:29 +00:00
yukkop 9eb7eb2e5d fix!: attic chaces with hatzner limites
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-09 23:35:45 +00:00
yukkop a5eeacd611 fix: workflow cache
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-09 19:04:13 +00:00
yukkop 6dc2391b13 feat: workflow save to cache
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-09 15:05:34 +00:00
yukkop 906e56a78a fix: include nixos-rebuild in deploy
runner nix smoke / nix label and flake smoke (push) Failing after 9s
2026-09-09 12:24:00 +00:00
yukkop aeeee27a3d fix: pass deploy SSH config
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-09 12:17:09 +00:00
yukkop 4253270da9 fix: override invalid runner cache key 2026-09-09 12:08:54 +00:00
yukkop 7580202c13 fix: use local deploy flake 2026-09-09 12:01:04 +00:00
yukkop 44fc755f41 fix: deploy neuro workflow 2026-09-09 11:36:12 +00:00
yukkop 68a4dd1900 fix: deploy neuro workflow 2026-09-09 11:23:58 +00:00
yukkop 059e2a8533 fix: deploy neuro workflow
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-09 09:04:15 +00:00
yukkop 93171355a7 fix: deploy neuro workflow 2026-09-09 08:56:24 +00:00
yukkop 2045ba76ed fix: remove microOS
runner nix smoke / nix label and flake smoke (push) Failing after 9s
2026-09-09 08:03:15 +00:00
yukkop 702f93f891 fix: microOS
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-08 23:33:08 +00:00
yukkop 728814c04d fix: pg init
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-08 20:03:57 +00:00
yukkop 58d590b2be fix: pg init
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-08 19:56:06 +00:00
yukkop beeb73736c gross
runner nix smoke / nix label and flake smoke (push) Failing after 8s
2026-09-08 19:31:04 +00:00
yukkop 6f80f672f2 rework: fix all vulnerabilities
runner nix smoke / nix label and flake smoke (push) Failing after 7s
2026-09-08 10:36:38 +00:00
yukkop 01a0d6e00a ci: fix: nix runners
runner nix smoke / nix label smoke (push) Successful in 7s
2026-09-08 09:34:22 +00:00
yukkop 4cbd8c6921 fix: use checkout tag in nix smoke
runner nix smoke / nix label smoke (push) Failing after 16s
2026-09-08 09:10:20 +00:00
yukkop 78403f6a44 ci: new workflow
runner nix smoke / nix label smoke (push) Failing after 16s
2026-09-08 08:59:03 +00:00
yukkop 006ea7f52b fix: gite nix runners 2026-09-07 18:07:59 +00:00
yukkop 8cfc7463c6 ci!: deploy workflow 2026-09-07 10:59:36 +00:00
yukkop 2fbd776fc1 feat: performace lables for gitea 2026-09-03 09:00:07 +00:00
yukkop 2ca6e3deae feat: hectic-lab: volume -> /nix 2026-09-03 06:51:35 +00:00
yukkop 27ccff23f3 fix: gitea runner 2026-09-03 06:49:45 +00:00
yukkop fd6c9536e7 fix: finaly gitea runners can works 2026-09-02 13:51:11 +00:00
yukkop 07689e1a9e feat: p4 on hectic-lab 2026-08-31 10:51:38 +00:00
yukkop 31cac93a4c feat: zomboid: server but you cannot connect to it 2026-08-27 19:37:37 +00:00
yukkop cadc6c44be feat: projectzomboid 2026-08-27 15:08:38 +00:00
yukkop c5026d3e9d feat: zero-idle gite runners infra
runner ubuntu smoke / ubuntu-latest label smoke (push) Has been cancelled
runner nix smoke / nix label smoke (push) Has been cancelled
2026-08-27 12:34:23 +00:00
yukkop 56c033a541 feat: gitea runners infra, but it is so expancive
runner nix smoke / nix label smoke (push) Has been cancelled
runner ubuntu smoke / ubuntu-latest label smoke (push) Has been cancelled
2026-08-25 14:44:45 +00:00
yukkop eb16104545 fix: optimize outputs
runner nix smoke / nix label smoke (push) Has been cancelled
2026-08-23 08:06:57 +00:00
yukkop 7fcf054c16 feat: gitea: +runner 2026-08-20 22:13:19 +00:00
yukkop 557b6e9ef0 fix: migrator 2026-07-24 15:21:19 +04:00
yukkop e49f497045 fix: aga 2026-07-24 15:21:11 +04:00
3685 changed files with 135190 additions and 44794 deletions
@@ -0,0 +1,41 @@
---
# yamllint disable rule:line-length
name: check Nix download buffer
on: # yamllint disable-line rule:truthy
workflow_dispatch:
concurrency:
group: check-nix-download-buffer
cancel-in-progress: true
jobs:
check:
name: check Nix download buffer
runs-on: gross-nix-x86-perf
timeout-minutes: 20
env:
NIX_CONFIG: |
fallback = false
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Inspect Nix client
run: |
set -eu
nix --version
nix config show download-buffer-size
nix config show http2
nix config show fallback
nix config show substituters
- name: Ping Attic cache
run: |
set -eu
nix store ping --store https://cache.hectic-lab.com/hectic
- name: Download small cache path
run: |
set -eu
nix build --no-link --print-out-paths nixpkgs#hello
+86
View File
@@ -0,0 +1,86 @@
---
# yamllint disable rule:line-length
name: deploy hectic-lab
on: # yamllint disable-line rule:truthy
workflow_dispatch:
concurrency:
group: deploy-hectic-lab
cancel-in-progress: false
jobs:
deploy:
name: deploy hectic-lab with Attic cache
if: ${{ gitea.ref == 'refs/heads/master' }}
runs-on: nix
timeout-minutes: 435
env:
NIX_CONFIG: |
fallback = true
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout dispatched revision
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Show runner and cache configuration
run: |
set -eu
uname -a
nix --version
nix config show http2
nix config show fallback
nix config show download-buffer-size
nix config show substituters
- name: Configure SSH for hectic-lab
env:
HECTIC_LAB_SSH_PRIVATE_KEY: ${{ secrets.HECTIC_LAB_SSH_PRIVATE_KEY }}
HECTIC_LAB_SSH_KNOWN_HOSTS: ${{ secrets.HECTIC_LAB_SSH_KNOWN_HOSTS }}
run: |
set -eu
test -n "$HECTIC_LAB_SSH_PRIVATE_KEY"
test -n "$HECTIC_LAB_SSH_KNOWN_HOSTS"
ssh_home=$(mktemp -d)
trap 'rm -rf "$ssh_home"' EXIT
install -d -m 700 "$ssh_home/.ssh"
printf '%s\n' "$HECTIC_LAB_SSH_PRIVATE_KEY" > "$ssh_home/.ssh/id_ed25519"
printf '%s\n' "$HECTIC_LAB_SSH_KNOWN_HOSTS" > "$ssh_home/.ssh/known_hosts"
chmod 600 "$ssh_home/.ssh/id_ed25519" "$ssh_home/.ssh/known_hosts"
printf '%s\n' \
'Host hectic-lab' \
' HostName 128.140.75.58' \
' User root' \
" IdentityFile $ssh_home/.ssh/id_ed25519" \
' IdentitiesOnly yes' \
' StrictHostKeyChecking yes' \
" UserKnownHostsFile $ssh_home/.ssh/known_hosts" \
> "$ssh_home/.ssh/config"
chmod 600 "$ssh_home/.ssh/config"
printf '%s\n' "$ssh_home" > "$RUNNER_TEMP/hectic-lab-ssh-home"
- name: Deploy hectic-lab and save cache
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
WITH_ATTIC_BUILD_TIMEOUT: "21600"
WITH_ATTIC_DRAIN_TIMEOUT: "3600"
WITH_ATTIC_UPLOAD_TIMEOUT: "600"
WITH_ATTIC_UPLOAD_RETRIES: "3"
WITH_ATTIC_BATCH_SIZE: "2"
run: |
set -eu
test -n "$ATTIC_TOKEN"
ssh_home=$(cat "$RUNNER_TEMP/hectic-lab-ssh-home")
trap 'rm -rf "$ssh_home"' EXIT
export HOME="$ssh_home"
export HECTIC_DEPLOY_SSH_CONFIG="$HOME/.ssh/config"
export NIX_SSHOPTS="-F $HOME/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$HOME/.ssh/known_hosts -o IdentitiesOnly=yes -i $HOME/.ssh/id_ed25519"
ssh -F "$HOME/.ssh/config" -o BatchMode=yes hectic-lab true
nix run --refresh '.#with-attic-cache' -- -- \
nix run --refresh '.#deploy' -- \
push -- --flake '.#hectic-lab|x86_64-linux' --target-host hectic-lab --use-remote-sudo
+113
View File
@@ -0,0 +1,113 @@
---
# yamllint disable rule:line-length
name: deploy neuro
on: # yamllint disable-line rule:truthy
workflow_dispatch:
inputs:
upload_cache:
description: Upload build outputs to Attic
required: false
type: boolean
default: true
runner_label:
description: Runner label for deploy job
required: false
type: choice
default: nix
options:
- nix
- gross-nix-x86-perf
- gross-nix-x86-highmem
concurrency:
group: deploy-neuro
cancel-in-progress: false
jobs:
deploy:
name: deploy neuro from performance node
if: ${{ gitea.ref == 'refs/heads/master' }}
runs-on: ${{ gitea.event.inputs.runner_label || 'nix' }}
timeout-minutes: 435
env:
NIX_CONFIG: |
fallback = true
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout dispatched revision
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Show runner and cache configuration
run: |
set -eu
uname -a
nix --version
nix config show http2
nix config show fallback
nix config show substituters
nix config show trusted-public-keys
- name: Deploy neuro
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
UPLOAD_CACHE: ${{ inputs.upload_cache }}
WITH_ATTIC_BUILD_TIMEOUT: "21600"
WITH_ATTIC_DRAIN_TIMEOUT: "3600"
WITH_ATTIC_UPLOAD_TIMEOUT: "600"
WITH_ATTIC_BATCH_SIZE: "4"
NEURO_SSH_PRIVATE_KEY: ${{ secrets.NEURO_SSH_PRIVATE_KEY }}
NEURO_SSH_KNOWN_HOSTS: ${{ secrets.NEURO_SSH_KNOWN_HOSTS }}
run: |
set -eu
test -n "$NEURO_SSH_PRIVATE_KEY"
test -n "$NEURO_SSH_KNOWN_HOSTS"
ssh_home=$(mktemp -d)
trap 'rm -rf "$ssh_home"' EXIT
install -d -m 700 "$ssh_home/.ssh"
printf '%s\n' "$NEURO_SSH_PRIVATE_KEY" > "$ssh_home/.ssh/id_ed25519"
printf '%s\n' "$NEURO_SSH_KNOWN_HOSTS" > "$ssh_home/.ssh/known_hosts"
chmod 600 "$ssh_home/.ssh/id_ed25519" "$ssh_home/.ssh/known_hosts"
printf '%s\n' \
'Host neuro' \
' HostName 95.31.254.84' \
' User root' \
' Port 34457' \
" IdentityFile $ssh_home/.ssh/id_ed25519" \
' IdentitiesOnly yes' \
' StrictHostKeyChecking yes' \
" UserKnownHostsFile $ssh_home/.ssh/known_hosts" \
> "$ssh_home/.ssh/config"
chmod 600 "$ssh_home/.ssh/config"
export HOME="$ssh_home"
export HECTIC_DEPLOY_SSH_CONFIG="$HOME/.ssh/config"
export NIX_SSHOPTS="-F $HOME/.ssh/config -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$HOME/.ssh/known_hosts -o IdentitiesOnly=yes -i $HOME/.ssh/id_ed25519"
ssh -F "$HOME/.ssh/config" -o BatchMode=yes -o ConnectTimeout=10 \
-o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$HOME/.ssh/known_hosts" \
-o IdentitiesOnly=yes \
-i "$HOME/.ssh/id_ed25519" \
neuro true
# Run deploy tool from checked-out Gitea revision; repository is not mirrored on GitHub.
case "$UPLOAD_CACHE" in
true)
nix run --refresh '.#with-attic-cache' -- -- \
nix run --refresh '.#deploy' -- \
push -- --flake '.#neuro|x86_64-linux' --target-host neuro
;;
false)
unset ATTIC_TOKEN
timeout --kill-after=60s 21600s \
nix run --refresh '.#deploy' -- \
push -- --flake '.#neuro|x86_64-linux' --target-host neuro
;;
*)
printf 'unsupported upload_cache value: %s\n' "$UPLOAD_CACHE" >&2
exit 64
;;
esac
+16 -2
View File
@@ -10,20 +10,34 @@ on:
- flake.lock
- flake.nix
- infra/gitea-runners/**
- lib/**
- legacy/**
- nixos/**
- package/**
- test/**
jobs:
smoke:
name: nix label smoke
name: nix label and flake smoke
runs-on: nix
env:
NIX_CONFIG: |
http2 = false
extra-substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
extra-trusted-public-keys = hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
steps:
- name: Checkout repository
uses: actions/checkout@v4.2.2
- name: Nix version and cache configuration
run: |
set -eu
nix --version
nix config show http2
nix config show substituters
nix config show trusted-public-keys
- name: Repository flake evaluation
run: |
set -eu
nix flake check --no-build
nix --option eval-cache false flake check --no-build --no-write-lock-file
+8 -1
View File
@@ -6,12 +6,19 @@ keys:
- &bfs-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &bfs-pol-server age1fpytf05sg9n6ywpwkmn09lhpfvgtud9h75h76jhxha475zpnasqq952rpu
- &bfs-new-server age17yx98qk9gzgcf2q6zhhp05p6mmtrkgz66dvyk9gqclypvlr8rersxjy5v7
- &neuro-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &neuro-server age1ak7heljpr0pjr4m0rcwxgn3sp0jjxw03lxyf33r8lcemqh2u2sgqx0aplq
- &games-server age15yzgmsvl3ku2w863h6gw2vpmw37m9aruv6xrj4fue6n2jpm7pyuqk9xjmj
- &hectic-lab-server age13h8twnwvgxn04l5ywtru89a6psw5d0uckr2eghxsjp88a5augvsstq5ard
- &umbriel-bfs age1jxntjca8q2vxvf2jaal4xyvm2ae6sh62fhv897694kuzawfrk5asj00zdt
creation_rules:
- path_regex: sus/neuro-minecraft.yaml$
key_groups:
- age:
- age1r25zdeqq8nac6dgca9en28r57ffyz9u9d8z5yc25gc8xqz747vaqmdtk0h
- age1ak7heljpr0pjr4m0rcwxgn3sp0jjxw03lxyf33r8lcemqh2u2sgqx0aplq
- age1ev53mzse6rg4ffwtcwtq4e93c7x7s4d0eyu89jrsahrke8r4yamsseu8h4
- path_regex: sus/home.xray.yaml$
key_groups:
- age:
+4 -29
View File
@@ -1,4 +1,5 @@
{
flake,
pkgs,
lib,
...
@@ -42,6 +43,9 @@ in {
home-manager.useGlobalPkgs = true;
home-manager.useUserPackages = true;
home-manager.backupFileExtension = "backup";
home-manager.sharedModules = [
(flake + "/home/module/program/tmux.nix")
];
home-manager.users.${name} = {
home.stateVersion = "25.11";
@@ -84,35 +88,6 @@ in {
'';
};
programs.tmux = {
enable = true;
plugins = with pkgs.tmuxPlugins; [ resurrect continuum ];
keyMode = "vi";
escapeTime = 500;
historyLimit = 50000;
newSession = true;
extraConfig = ''
# resurrect
set -g @resurrect-strategy-vim 'session'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-capture-pane-contents 'on'
resurrect_dir="$HOME/.tmux/resurrect"
set -g @resurrect-dir $resurrect_dir
set -g @resurrect-hook-post-save-all 'target=$(readlink -f $resurrect_dir/last); sed "s| --cmd .*-vim-pack-dir||g; s|/etc/profiles/per-user/$USER/bin/||g; s|/home/$USER/.nix-profile/bin/||g" $target | sponge $target'
# continuum
set -g @continuum-restore 'on'
set -g @continuum-boot 'on'
set -g @continuum-save-interval '10'
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi C-v send-keys -X rectangle-toggle
bind-key O select-pane -t :.-
'';
};
xdg.configFile."aerospace/aerospace.toml".text = ''
start-at-login = false
+1
View File
@@ -5,6 +5,7 @@
postgres-c = import ./postgres-c.nix { inherit self system pkgs; };
pure-c = import ./pure-c.nix { inherit self system pkgs; };
rust = import ./rust.nix { inherit self system pkgs; };
ratatui = import ./ratatui.nix { inherit self system pkgs; };
haskell = import ./haskell.nix { inherit self system pkgs; };
neuro = import ./neuro.nix { inherit self system pkgs; };
xmpp = import ./xmpp.nix { inherit self system pkgs; };
+213 -9
View File
@@ -5,13 +5,217 @@
exec ${pkgs.nix}/bin/nix run ${opentofuUnstable} -- "$@"
'';
packer = pkgs.stdenvNoCC.mkDerivation {
pname = "packer";
version = "1.16.0";
src = pkgs.fetchurl {
url = "https://releases.hashicorp.com/packer/1.16.0/packer_1.16.0_linux_amd64.zip";
hash = "sha256-XtzRSrWbU1BAxRLb7Nbsnvl2oACwc8Gdk+TEMclIWB4=";
};
nativeBuildInputs = [ pkgs.unzip ];
dontUnpack = true;
dontConfigure = true;
dontBuild = true;
installPhase = ''
install -d $out/bin
unzip -p $src packer > $out/bin/packer
chmod 755 $out/bin/packer
'';
};
buildMicroosSnapshots = pkgs.writeShellScriptBin "gitea-runners-build-microos-snapshots" ''
set -eu
: "''${HCLOUD_TOKEN:?HCLOUD_TOKEN is not set}"
architecture="''${1:-both}"
x86_location="''${GITEA_RUNNERS_X86_LOCATION:-nbg1}"
x86_server_type="''${GITEA_RUNNERS_X86_SERVER_TYPE:-cx23}"
case "$architecture" in
x86|arm|both) ;;
*)
printf 'usage: gitea-runners-build-microos-snapshots [x86|arm|both]\n' >&2
exit 2
;;
esac
workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT HUP INT TERM
ssh_private_key_file="$workdir/packer-ssh-key"
ssh-keygen -q -t ed25519 -N "" -f "$ssh_private_key_file"
: "''${GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE:?GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE is not set}"
image_public_key_file="$GITEA_RUNNERS_IMAGE_SSH_PUBLIC_KEY_FILE"
test -r "$image_public_key_file"
packer_public_key_b64="$(base64 -w0 "$ssh_private_key_file.pub")"
image_public_key_b64="$(base64 -w0 "$image_public_key_file")"
curl -fsSL \
https://raw.githubusercontent.com/kube-hetzner/terraform-hcloud-kube-hetzner/master/scripts/create.sh \
-o "$workdir/create.sh"
chmod +x "$workdir/create.sh"
(
cd "$workdir"
folder_name="runner-images" \
folder_path="$workdir" \
create_snapshots=none \
HCLOUD_TOKEN="$HCLOUD_TOKEN" \
"$workdir/create.sh"
)
packer_dir="$workdir/runner-images/packer"
"$packer_dir/scripts/install-verified-packer-plugin-hcloud.sh"
# Packer may try to remove its remote script after the image-writing reboot,
# while SSH is already unavailable. Keep that cleanup from aborting builds.
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.write_x86_image\]/a\ skip_clean = true' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.write_arm_image\]/a\ skip_clean = true' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/inline[[:space:]]*=[[:space:]]*\[local\.install_packages\]/a\ start_retry_timeout = "15m"' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
sed -i \
'/ssh_username[[:space:]]*=[[:space:]]*"root"/a\ temporary_key_pair_type = "ed25519"' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
awk \
-v ssh_private_key_file="$ssh_private_key_file" \
'/token[[:space:]]*=[[:space:]]*var[.]hcloud_token/ {
print
print " ssh_private_key_file = \"" ssh_private_key_file "\""
next
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
cat > "$workdir/image-key-injection.txt" <<'EOF'
partprobe /dev/sda || true
udevadm settle
root_device=""
for candidate in /dev/sda[0-9]*; do
if [ "$(blkid -s TYPE -o value "$candidate" 2>/dev/null || true)" = btrfs ]; then
root_device="$candidate"
break
fi
done
test -n "$root_device"
mount -o subvolid=5,rw "$root_device" /mnt
default_subvolume="$(btrfs subvolume get-default /mnt | awk 'NR == 1 { print $2 }')"
umount /mnt
mount -o subvolid="$default_subvolume",rw "$root_device" /mnt
btrfs property set -ts /mnt ro false || true
install -d -m 0755 /mnt/nix /mnt/var/lib/gcr-nix
install -d -m 0700 /mnt/root/.ssh
printf '%s' '__IMAGE_PUBLIC_KEY_B64__' | base64 -d > /mnt/root/.ssh/gcr_authorized_keys
printf '\n%s' '__PACKER_PUBLIC_KEY_B64__' | base64 -d >> /mnt/root/.ssh/gcr_authorized_keys
chmod 0600 /mnt/root/.ssh/gcr_authorized_keys
install -d -m 0755 /mnt/etc/ssh/sshd_config.d
printf '%s\n' 'PermitRootLogin prohibit-password' 'PubkeyAuthentication yes' 'AuthorizedKeysFile .ssh/authorized_keys .ssh/gcr_authorized_keys' > /mnt/etc/ssh/sshd_config.d/99-gcr-root.conf
chmod 0644 /mnt/etc/ssh/sshd_config.d/99-gcr-root.conf
sync
umount /mnt
EOF
sed -i "s|__PACKER_PUBLIC_KEY_B64__|$packer_public_key_b64|" \
"$workdir/image-key-injection.txt"
sed -i "s|__IMAGE_PUBLIC_KEY_B64__|$image_public_key_b64|" \
"$workdir/image-key-injection.txt"
awk -v inject_file="$workdir/image-key-injection.txt" \
'/rm -f \/root\/.ssh\/authorized_keys/ {
cleanup=1
}
cleanup && /sleep 1/ {
print
while ((getline line < inject_file) > 0) print line
close(inject_file)
cleanup=0
next
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
cat > "$workdir/cloud-init-cleanup.txt" <<'EOF'
cloud-init clean --logs --machine-id --seed --configs all || true
rm -rf /run/cloud-init/* /var/lib/cloud/*
EOF
awk -v cleanup_file="$workdir/cloud-init-cleanup.txt" \
'/# Cleanup some logs/ {
while ((getline line < cleanup_file) > 0) print "- [sh, -c, \"" line "\"]"
close(cleanup_file)
}
{ print }' \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl" \
> "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp"
mv "$packer_dir/hcloud-microos-snapshots.pkr.hcl.tmp" \
"$packer_dir/hcloud-microos-snapshots.pkr.hcl"
x86_base='https://download.opensuse.org/tumbleweed/appliances'
x86_file='openSUSE-MicroOS.x86_64-ContainerHost-OpenStack-Cloud.qcow2'
x86_url="$x86_base/$x86_file"
arm_base='https://download.opensuse.org/ports/aarch64/tumbleweed/appliances'
arm_file='openSUSE-MicroOS.aarch64-ContainerHost-OpenStack-Cloud.qcow2'
arm_url="$arm_base/$arm_file"
x86_sha="$(curl -fsSL "$x86_url.sha256" | awk '{print $1; exit}')"
arm_sha="$(curl -fsSL "$arm_url.sha256" | awk '{print $1; exit}')"
test -n "$x86_sha"
test -n "$arm_sha"
printf 'x86 digest: %s\n' "$x86_sha"
printf 'arm digest: %s\n' "$arm_sha"
(
cd "$packer_dir"
packer init hcloud-microos-snapshots.pkr.hcl
case "$architecture" in
x86)
packer build \
-only=hcloud.microos-x86-snapshot \
-var 'selinux_package_to_install=k3s' \
-var "x86_location=$x86_location" \
-var "x86_server_type=$x86_server_type" \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
arm)
packer build \
-only=hcloud.microos-arm-snapshot \
-var 'selinux_package_to_install=k3s' \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
both)
packer build \
-var 'selinux_package_to_install=k3s' \
-var "x86_location=$x86_location" \
-var "x86_server_type=$x86_server_type" \
-var "opensuse_microos_x86_expected_sha256=$x86_sha" \
-var "opensuse_microos_arm_expected_sha256=$arm_sha" \
hcloud-microos-snapshots.pkr.hcl
;;
esac
)
'';
giteaRunnersSetup = pkgs.writeShellScriptBin "gitea-runners-setup" /* sh */ ''
cat <<'EOF'
Gitea runners setup checklist
Tools available in this shell:
tofu, kubectl, kustomize, kubeconform, sops, age, awscli2, hcloud, tea,
docker, skopeo, go-containerregistry, jq, yq-go, curl, git, openssh, nix
tofu, packer, gitea-runners-build-microos-snapshots [x86|arm|both], kubectl, kustomize,
kubeconform, sops, age, awscli2, hcloud,
tea, docker, skopeo, go-containerregistry, jq, yq-go, curl, git, openssh, nix
Environment expected before real deploy/apply:
TF_VAR_hcloud_token
@@ -20,18 +224,15 @@ Environment expected before real deploy/apply:
S3 backend credentials and endpoint access
a matching SOPS age identity for sus/gitea-runners.yaml
kubectl access to the target cluster
a concrete registry digest for the pushed Nix-capable runner image if enabling
the nix label
a valid Hetzner Nix image ID in the controller host configuration
OpenTofu validation gate:
tofu version
tofu -chdir=infra/gitea-runners/opentofu validate
Nix image build/publish/digest gate:
Nix image build/publish gate:
nix build .#gitea-runner-nix-image
publish the archive, then pin the registry-reported digest in the runner label
mapping
nix:docker://gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image@sha256:<registry-digest>
publish/import image, then set nixImageId / GCR_NIX_IMAGE_ID to its Hetzner ID
SOPS token Secret creation gate:
kubectl apply -f infra/gitea-runners/k8s/namespace.yaml
@@ -68,7 +269,7 @@ Verification commands:
Main blockers and gates:
do not run tofu apply without all external inputs
do not apply the k8s overlay until the gitea-runner-token Secret exists
do not enable the nix label until the image has been published with a concrete digest
do not dispatch nix jobs until nixImageId / GCR_NIX_IMAGE_ID is valid
do not print, load, or require secrets on shell entry
EOF
'';
@@ -77,6 +278,8 @@ in pkgs.mkShell {
buildInputs = [
tofu
packer
buildMicroosSnapshots
giteaRunnersSetup
pkgs.nix
pkgs.kubectl
@@ -95,6 +298,7 @@ in pkgs.mkShell {
pkgs.curl
pkgs.git
pkgs.openssh
pkgs.unzip
];
shellHook = ''
+19
View File
@@ -0,0 +1,19 @@
{
self,
pkgs,
system
}: let
rustToolchain =
if builtins.pathExists ./rust-toolchain.toml
then pkgs.pkgsBuildHost.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml
else pkgs.pkgsBuildHost.rust-bin.stable."1.81.0".default;
in
self.devShells.${system}.default
// (pkgs.mkShell {
nativeBuildInputs = [
rustToolchain
pkgs.pkg-config
pkgs.gcc
pkgs.gnumake
];
})
+34
View File
@@ -1,3 +1,37 @@
# Documentation
- [Using the `hectic` Attic Cache](./attic-cache.md)
- [Minecraft incident log](./minecraft-incidents.md)
- [Project Zomboid backups](./project-zomboid-backups.md)
- [Gitea Kanban CLI](./gitea-kanban-cli.md)
## Gitea runner labels
Common labels for controller-managed on-demand runners:
- `ubuntu-latest` — on-demand alias for `gross-x86`
- `nix` — on-demand Nix alias with 480-minute TTL
- `gross-x86` — x86 fallback chain `cx53` / `cx43` / `cx33`
- `gross-arm` — ARM fallback chain `cax41` / `cax31` / `cax21`
- `gross-x86-perf` — x86 performance chain `cx53` / `cpx62` / `cpx52`
- `gross-mixed-econ` — mixed chain `cx53` / `cax41` / `cx43`
- `gross-nix-x86` — `gross-x86` + Nix bootstrap
- `gross-nix-arm` — `gross-arm` + Nix bootstrap
- `gross-nix-x86-perf` — `gross-x86-perf` + Nix bootstrap
- `gross-nix-x86-highmem` — CCX53-only Nix runner, 480-minute TTL
- `gross-nix-mixed-econ` — `gross-mixed-econ` + Nix bootstrap
Region order for fallback: `nbg1`, then `fsn1`, then `hel1`.
The legacy Kubernetes persistent pool is disabled (`replicas: 0`) and has no
registered labels. All listed labels are handled by the VM controller. After a
successful job, a bootstrapped VM remains running and idle until its next hourly
lifetime boundary, capped by its original hard TTL. Before becoming generic
idle, its repository runner registration is disabled, deleted, and confirmed
absent. A queued job from any allowed repository may claim a VM with an exact
compatible server type, location, architecture, and image profile. The
controller rebuilds it from that clean image and registers a fresh runner
identity; reuse creates no second VM or budget reservation.
Operational details: `infra/gitea-runners/runbook.md` and
`package/gitea-runner-controller/decide.sh`.
+93
View File
@@ -171,6 +171,83 @@ nix shell nixpkgs#attic-client -c attic cache info local:hectic
nix shell nixpkgs#attic-client -c attic login local https://cache.hectic-lab.com "<NEW_TOKEN>"
```
## Automatic uploads from trusted CI
The `deploy-neuro` workflow uses `with-attic-cache` around its deployment command:
```sh
# ATTIC_TOKEN must be supplied through a secret, not committed or printed.
nix run '.#with-attic-cache' -- -- nix build '.#my-package'
```
The wrapper installs a temporary Nix `post-build-hook`. Each successful local
build queues all output paths, including build-only dependencies and multiple
outputs. A separate worker uploads batches with `attic push --stdin --no-closure`
and two concurrent uploads. Pending outputs have registered garbage-collection
roots until uploaded. Substituted paths and the initial bootstrap of the wrapper
itself are not uploaded; this avoids copying the public NixOS cache into Attic.
The worker runs during the build and drains after success or failure. Uploads
have bounded retries; exhausted uploads fail an otherwise successful command.
If the build failed, its original exit status is preserved. Defaults are 30
minutes for the wrapped command, 10 minutes for the final drain, and three
120-second attempts per batch of up to 32 paths. These limits can be adjusted with
`WITH_ATTIC_BUILD_TIMEOUT`, `WITH_ATTIC_DRAIN_TIMEOUT`,
`WITH_ATTIC_UPLOAD_TIMEOUT`, `WITH_ATTIC_UPLOAD_RETRIES`, and
`WITH_ATTIC_BATCH_SIZE` (positive integer seconds/counts without leading zeros).
The heavier `deploy-neuro` workflow overrides these defaults: 6 hours for the
build/deploy command, batches of at most 8 paths, and 600 seconds per upload attempt. The
upload deadline covers the **whole batch**, not each individual path. Its final
drain is bounded at 1 hour; the 435-minute job budget leaves 15 minutes for setup
and cleanup. The `gross-nix-x86-perf` runner limit and Gitea's endless-task
watchdog are 8 hours. VM hard lifetime starts at allocation and has no controller
destruction grace. A prolonged cache outage can still exhaust the drain before
every queued path is uploaded.
The build timeout covers the entire wrapped command, not each derivation.
Completed outputs can be reused from the cache, but an interrupted CUDA/Magma
compilation does not produce a cacheable output or resume on the next ephemeral
runner. Exit code 124 with `interrupted by the user` can therefore mean the
wrapper deadline expired, not that someone manually cancelled the job.
The workflow also sets `fallback = true` in `NIX_CONFIG`, inherited by nested
Nix commands. If substitution fails, Nix can build the affected derivation from
source instead of aborting solely because the cache is unavailable. Caches and
signature checks remain enabled. Fallback cannot fix an unavailable upstream
source or a genuine compilation error, and rebuilding can consume more time.
Uploader logs report each attempt's batch size, whole-batch deadline and exit
status, distinguish deadline expiration from other failures, and list paths in
exhausted batches. The final summary counts queue records: acknowledged,
unconfirmed after exhausted attempts, pending and in flight. These are not
unique artifact counts: an unsuccessful batch may already have uploaded some
paths, and a successful retry can reuse those cached results.
This integration targets the root, single-user Nix environment on the ephemeral
runner. It refuses to replace an existing post-build hook. SIGINT/SIGTERM stop
the command and attempt a bounded drain; SIGKILL, VM destruction, or a hard
runner timeout cannot guarantee uploads. A failed upload remains a visible CI
failure, not a claim that the artifact was cached.
### CI credentials and rollout
- `ATTIC_TOKEN` is a Gitea repository secret for `hinterland/hearth`, passed only
to the deployment step. The workflow remains manual and restricted to `master`.
- The token grants pull/push only for `hectic`, without deletion or cache
administration. The current token expires **2027-09-09**; rotate it before then.
- The wrapper stores it in a private temporary `0600` file, references that file
from Attic configuration, and removes `ATTIC_TOKEN` from child environments.
Neither the hook nor `NIX_CONFIG` contains the token. Cleanup removes private
files after the worker stops.
- Never expose this credential to untrusted PR workflows or bake it into runner
images. A writer to this cache can publish artifacts trusted by its consumers.
- The `hectic` cache is public for reads. Build outputs must not contain secrets
or content that must remain private; the wrapper uploads every successful local
output, not just the final system.
- Workflow/package changes must be published to `master` before dispatched runs
use them. Creating the secret alone does not enable uploads in an existing run.
## Common issues
### `flake 'nixpkgs' does not provide attribute 'attic'`
@@ -199,6 +276,22 @@ Usually means:
- timeout/reverse proxy issue
- bad token permissions
On `hectic-lab`, the upload API has separate nginx locations for
`/_api/v1/upload-path` and `/next/_api/v1/upload-path`. Requests stream to Attic
without whole-body buffering, using HTTP/1.1 upstream and 600-second
`proxy_send_timeout` and `proxy_read_timeout` values. These are inactivity
timeouts, not an upload throughput guarantee. The CI wrapper still enforces its
own whole-batch deadline. The legacy `/previous/` endpoint stays read-only.
The host's Attic package also restricts its AWS SDK rustls connector to HTTP/1.1
after observed S3 `REFUSED_STREAM` failures. This is a reproducible, host-scoped
derived Cargo vendor tree; the pinned input tree and Cargo.lock are unchanged.
TLS certificate verification remains enabled. Nix clients now force HTTP/1.1 for
cache pulls because the cache endpoint has produced HTTP/2 framing errors; the
Attic upload client separately uses HTTP/1.1 upstream. The pinned crate path
makes upstream changes fail visibly during a future upgrade. This mitigates the
observed transport error, not every possible Hetzner S3 timeout.
### Cache pulls do not work
Check:
+141
View File
@@ -0,0 +1,141 @@
# Gitea Kanban CLI
`gitea-kanban` is the non-interactive interface for native Gitea Projects.
It shares its configuration, API client, models, permissions, and operations
with `gitea-kanban-tui`.
## Installation
The Nix package installs both binaries:
```sh
nix build .#gitea-kanban-tui
./result/bin/gitea-kanban --help
./result/bin/gitea-kanban-tui --help
```
For development:
```sh
cargo run --manifest-path package/gitea-kanban-tui/Cargo.toml \
--bin gitea-kanban -- --help
```
## Configuration
Configuration can be supplied with flags or environment variables. A project
selector is required, and exactly one selector must be supplied.
| Flag | Environment | Description |
| --- | --- | --- |
| `--url` | `GITEA_URL` | Gitea base URL |
| `--token-file PATH` | `GITEA_TOKEN_FILE` | File containing API token |
| — | `GITEA_TOKEN` | Token fallback when no token file is configured |
| `--project NAME` | `GITEA_PROJECT` | Exact, case-sensitive project name |
| `--project-id ID` | `GITEA_PROJECT_ID` | Project ID; useful for duplicate names |
| `OWNER` | `GITEA_OWNER` | Repository owner |
| `REPO` | `GITEA_REPO` | Repository name |
Precedence:
1. Command-line flags and positional arguments.
2. Token file from `--token-file` or `GITEA_TOKEN_FILE`.
3. `GITEA_TOKEN` when no token file is configured.
Token files must be regular files and must not be group- or world-readable on
Unix. Remote URLs must use HTTPS. Plain HTTP is accepted only for literal
loopback IP addresses (`127.0.0.1` or `::1`) during local development.
Example:
```sh
export GITEA_URL=https://gitea.example
export GITEA_TOKEN_FILE="$HOME/.config/gitea/token"
gitea-kanban --project Kanban owner repo board
```
## Commands
### `board`
Print selected project, columns, and issues:
```sh
gitea-kanban --project Kanban owner repo board
```
Output includes issue numbers and titles. Server-provided terminal control
characters are removed before output.
### `create`
Create an issue and assign it to selected project. The issue starts in the
project's default column.
```sh
gitea-kanban --project Kanban owner repo create \
--title "Fix deployment" \
--body "Investigate failed rollout"
```
### `edit`
Replace issue title and body. Issue must be assigned to selected project.
```sh
gitea-kanban --project Kanban owner repo edit 42 \
--title "Updated title" \
--body "Updated description"
```
### `move`
Move an issue to a project column. `ISSUE_ID` is the global Gitea issue ID,
not the repository issue number. `--sorting` is optional.
```sh
gitea-kanban --project Kanban owner repo move 123 --column-id 7
gitea-kanban --project Kanban owner repo move 123 --column-id 7 --sorting 2
```
### `comment`
Comments are managed on issues assigned to the selected project. Issue values
are repository issue numbers. Comment values are global Gitea comment IDs.
```sh
gitea-kanban --project Kanban owner repo comment list 42
gitea-kanban --project Kanban owner repo comment add 42 --body "Investigating"
gitea-kanban --project Kanban owner repo comment edit 42 9001 --body "Resolved"
gitea-kanban --project Kanban owner repo comment delete 42 9001 --yes
```
The CLI verifies that the issue belongs to the selected project and that the
comment belongs to that issue before editing or deleting it.
### `delete`
Delete an issue assigned to selected project. This is irreversible and requires
explicit confirmation with `--yes`:
```sh
gitea-kanban --project Kanban owner repo delete 42 --yes
```
Deletion also requires repository administrator permission in this Gitea fork.
## Permissions and server behavior
- The repository Projects unit must be enabled.
- Project operations require repository Projects write permission.
- Issue create/edit follows Gitea issue permissions.
- Delete requires repository administrator permission.
- Closed projects, archived repositories, disabled Projects units, foreign
project IDs, and issues outside selected project are rejected.
- API failures return a non-zero exit status. Authentication and HTTP status
guidance is shown without printing server response bodies or tokens.
## Related interface
Use `gitea-kanban-tui` for keyboard navigation over the same native Projects
API. Both binaries use the same configuration and server-side authorization.
+101
View File
@@ -0,0 +1,101 @@
# Minecraft incident log
This file records only observed evidence, actions, and verification results.
An entity appearing in a stack trace is a trigger-path observation, not a
proven root cause.
## 2026-09-19 — WorldOfSosal crashes in Sable block-change handling
### Impact
- `minecraft-server-wowMineMap.service` terminates while a player is online.
- Public Minecraft endpoint is `store.hectic-lab.com:25568`.
- Server is intentionally stopped after the latest crash to prevent repeated
crash-save cycles while recovery is investigated.
### Observed evidence
All crash reports contain `sable@2.0.5` in
`LevelAccelerator.getBlockState`, followed by
`ArrayIndexOutOfBoundsException` where the requested section index exceeds
the world section array length of `24`.
| UTC timestamp | Crash report | Observed trigger path | Exception |
| --- | --- | --- | --- |
| 18:47:03 | `crash-2026-09-19_18.47.03-server.txt` | `EnderMan$EndermanTakeBlockGoal.tick` | index `38` / length `24` |
| 18:52:17 | `crash-2026-09-19_18.52.17-server.txt` | `GlowSquid.aiStep` → `RedStoneOreBlock.stepOn` | index `33` / length `24` |
| 19:14:46 | `crash-2026-09-19_19.14.46-server.txt` | `Skeleton.tick` → `RedStoneOreBlock.stepOn` | index `34` / length `24` |
Evidence locations on `neuro`:
```text
/srv/minecraft/wowMineMap/crash-reports/
/srv/minecraft/wowMineMap/logs/latest.log
```
### Actions performed
| UTC timestamp | Action | Result |
| --- | --- | --- |
| 17:51 | Archived current world before recovery | Archive checksum recorded |
| 18:08 | Set `randomTickSpeed=0` | Server started, but later crashed from an entity block change |
| 18:48 | Set `mobGriefing=false` | Prevented Enderman block pickup only; later crashes still occurred |
| 18:54 | Archived post-crash world | Archive checksum recorded |
| 19:00 | Moved Boss offline player NBT from `(3299.067, 142.630, 8613.742)` to `(3296, 500, 8608)` in `crafting_azeroth:azeroth` | Only `Pos` and `Dimension` changed; later crash still occurred |
| after 19:14 crash | Stopped `minecraft-server-wowMineMap.service` | Prevented further automatic crash/restart saves |
### Recovery artifacts
```text
/srv/minecraft/backups/wowMineMap-before-sable-recovery-20260919T175139Z.tar.zst
/srv/minecraft/backups/wowMineMap-after-sable-crashes-20260919T185445Z.tar.zst
/srv/minecraft/wowMineMap/world/playerdata/1c189af5-2713-3fa6-bcc4-893dfadedfa4.dat.before-relocation
```
### Conclusions supported by evidence
- Public proxy and reverse tunnel are not the failure point: server-list ping
succeeded before later in-world crashes.
- The failure is not limited to Endermen, random ticks, or one player
position.
- Sable's block-change callback is present in every captured crash.
### Not established
- Exact corrupt chunk, block, or mod data.
- Whether world data is corrupt, Sable itself is defective, or another mod is
supplying incompatible world state.
- Whether deleting any chunk, region, or Sable state would be safe.
### External research
No exact upstream match was found for Sable `2.0.5` on NeoForge `1.21.1` with
`LevelAccelerator.getBlockState` and a requested section index of `33`, `34`,
or `38` against a section array of length `24`.
Related but non-identical upstream reports:
- [Sable #776](https://github.com/ryanhcode/sable/issues/776) documents an
`ArrayIndexOutOfBoundsException` associated with unusual dimension height
bounds. This is relevant to section-coordinate handling, but is an older
version and different stack trace.
- [Sable #1087](https://github.com/ryanhcode/sable/issues/1087) documents a
`LevelAccelerator.getBlockState` recursion during block-shape processing.
The failure type differs.
- [Sable #820](https://github.com/ryanhcode/sable/issues/820) documents a
ticking-entity block-change crash. The reported downgrade to `1.1.3` helped
that distinct recursive-update failure; it is not evidence for this crash.
- [Sable #1223](https://github.com/ryanhcode/sable/issues/1223) documents a
different `ArrayIndexOutOfBoundsException` in voxel-neighborhood handling.
Its suggested Lithium setting only reduced crashes for some reporters and is
not a verified mitigation here.
Sable `2.0.4` and `2.0.5` release notes mention other block or contraption
crash fixes, but not this exception. No version upgrade or downgrade is
currently evidence-backed as a production fix.
### Next recovery step
Use a disposable full-world copy to test a supported Sable/physics integration
mitigation. Do not restart production, delete region files, or overwrite a
backup until that test gives reproducible evidence.
+231
View File
@@ -0,0 +1,231 @@
# WorldOfSosal: Prism automatic updates
The published client entry points are:
- https://store.bfs.band/minecraft/ (BFS / Element host)
- https://store.hectic-lab.com/minecraft/world-of-sosal/ (hectic-lab)
Each site provides its own Prism ZIP with that site's update URL and matching
server address. Both installs use the same Minecraft world and modpack release.
Players import `WorldOfSosal-Prism.zip` into Prism once and approve its pre-launch
command. Before each launch, packwiz-installer reconciles the client with the
published pack: it adds, replaces, and removes managed files, checking hashes.
`options.txt` is seeded once and preserved. Pack configuration files are managed
and can be replaced. Upstream mods do not update independently of your release.
Minecraft 1.21.1, NeoForge 21.1.250, Java 21; the instance reserves up to 8 GiB.
The original `.mrpack` alone does not provide this automatic update mechanism.
Official workflow: https://packwiz.infra.link/tutorials/installing/packwiz-installer/
## Publishing a tested update
Keep the authoritative `.mrpack` in Storage Box at
`minecraft/pack/WorldOfSosal.mrpack`. For a server update, replace that archive,
set its new SHA-256 in `nixos/system/neuro/minecraft/world-of-sosal.nix`,
and rebuild/switch neuro before publishing the corresponding client export. The server importer and the
client export must consume the same archive; publishing only the client can make
it incompatible with the running server.
```sh
# Test the client and deploy the matching server release first.
python3 script/publish-prism-mirrors.py WorldOfSosal.mrpack
```
The mirror publisher creates temporary build directories and sets each server
address and update URL automatically. The builder downloads a SHA-256-pinned bootstrap from the
packwiz project's release, or accepts it via `--bootstrap /path/to/file.jar`.
External mods retain their original URLs and SHA-512 checksums. Embedded mods and
configuration are hosted with the release. Both required and optional client mods
are included, matching the current server importer's optional-mod behavior.
Publishing uploads an immutable directory, checks it if it already exists, and
atomically switches `current`. Previous directories remain available for rollback.
Do not remove a release while clients may still be reading it. Hash checks cause
an overlapping update to fail safely rather than silently accept mixed contents;
retry the launch if a publication overlapped a download.
The files live under `/var/www/store/minecraft/world-of-sosal` on `hectic-lab`,
served by the existing `store.hectic-lab.com` nginx virtual host. No nginx reload
is needed for pack updates. Keep `current/pack.toml` as the stable client URL.
The index must be alongside pack.toml: putting a release prefix in `[index].file`
also prefixes client installation paths with that directory in packwiz-installer.
If Minecraft/NeoForge versions change, update and test both the server pin and
client pack. packwiz-installer 0.5.14 understands NeoForge components in Prism's
`mmc-pack.json`; a launcher restart/relaunch may be necessary after changing them.
## Verification on 2026-09-18
- Source archive SHA-256:
`f8c18acb9208e4592725632ae50dab4f9c308483b34fd43a6507c74fdbf8169f`.
- Public HTTPS installation into a clean Prism-format instance passed: all 141
client mods and all overrides match the original archive. A second launch
performed no downloads and preserved personal options.
- Direct probes of neuro public ports 25565, 25567, and 25568 timed out;
the configured relay now provides the public entry point.
- Live WoW server reached `Done` with all 135 server mod SHA-512 hashes
matching the same archive used for the Prism client.
- Public `store.hectic-lab.com:25568` status/ping succeeded (about 111 ms);
a login handshake reached the online authentication encryption request.
An authenticated Windows Prism session was subsequently verified on 2026-09-19 (see below).
- Server and tunnel are enabled at boot; relay and both NixOS configurations
are deployed. No failed systemd units remain on neuro.
- Loader package `neoforge-1.21.1-21.1.250` built successfully in Nix.
- Automatic updater add/remove/config-update and options-preservation behavior
tested with an actual packwiz-installer run against a controlled update fixture.
## WoW server and public entry point
The WoW map and WorldOfSosal mods share the `wowMineMap` server on neuro,
listening on 25567. There is no separate WorldOfSosal world/server on 25568.
The client pack and server both pin Minecraft 1.21.1 / NeoForge 21.1.250.
Map import runs before mod import, and both finish before Minecraft starts.
The public entry point is `store.hectic-lab.com:25568`:
```
Prism -> hectic-lab:25568 -> loopback:25577 -> SSH tunnel -> neuro:25567
```
`minecraft-wow-proxy.socket` and its socket-proxyd service run on hectic-lab.
`minecraft-wow-tunnel.service` on neuro establishes a reverse SSH forward and
reconnects after failures. A dedicated SSH identity may listen only on
127.0.0.1:25577 at the relay; it has no interactive shell or other forwarding.
Both services and firewall rules are in Nix and start on boot. The SSH client
uses an explicit AES-CTR / HMAC-SHA256-ETM / curve25519 transport profile with
IPQoS=none, tested on the neuro-to-lab route. The default profile stalled after
the handshake on this route. Both ends check peer liveness so stale listeners
are eventually released. Minecraft initially used `online-mode=true`. It now uses offline mode at the
owner's request; see the RCON and authentication section below.
For a temporary direct local tunnel, use:
```sh
ssh -NTL 0.0.0.0:25568:127.0.0.1:25567 \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 -o ServerAliveCountMax=3 neuro
```
That command exposes the local 25568 listener on all interfaces, as requested.
Use 127.0.0.1 instead of the first 0.0.0.0 if only this computer should use it.
Credentials are encrypted in `sus/neuro-minecraft.yaml` with the actual neuro
host identity and owner keys. The existing `sus/neuro.yaml` is unchanged.
The source WoW archive remains untouched in Storage Box. Import is idempotent:
an existing world with level.dat is preserved. Never delete the world to update
mods; publish/deploy a matching modpack release instead.
Useful checks:
```sh
ssh neuro systemctl status minecraft-world-import-wowMineMap \
minecraft-modpack-import-worldOfSosal minecraft-server-wowMineMap \
minecraft-wow-tunnel --no-pager
ssh hectic-lab systemctl status minecraft-wow-proxy.socket --no-pager
ssh neuro journalctl -u minecraft-server-wowMineMap -n 80 --no-pager
```
The initial isolated server compatibility test reached `Done` and answered the
Minecraft status/ping protocol. Its logs also contain nonfatal recipe and class
function errors from the supplied modpack; successful startup does not imply that
every recipe or RPG class feature works correctly.
The imported map metadata is `wow mine`, DataVersion 3953 (Minecraft 1.21),
spawn 0 / 68 / -32; extracted size is approximately 11.7 GiB. The archive
SHA-256 was verified before extraction.
## Windows Prism GUI verification on 2026-09-19
- Downloaded the published ZIP through the browser and imported it in Prism 8.4.
- Fixed the generated instance.cfg: ConfigVersion=1.2 is required. Without it,
Prism selects its legacy INI parser and corrupts the quoted pre-launch command.
The corrected ZIP is published at the same URL. Previously imported copies
need the command corrected in Settings / Custom commands, or a fresh import.
- Used Java 21.0.4; the first packwiz download hit two transient timeouts.
Cancelled the incomplete launch and retried successfully. All 141 downloaded
client mod hashes match the original mrpack. NeoForge reports 202 mods when
bundled/internal mod components are included.
- Joined store.hectic-lab.com:25568 in the actual Minecraft GUI. The server
confirmed the authenticated join, and the client reached the Origins selection
screen. No character origin was selected during testing.
- Tested a separate copy of the pack manifest with an inert config text file:
launching from Prism added it; restoring the production manifest and launching
again automatically deleted it. Existing files were reused from cache, and
options.txt retained its checksum. The production pack contents were unchanged.
- Restored the instance's regular current/pack.toml update URL.
## Independent BFS entry point (2026-09-19)
- Server: `wow.bfs.band`; downloads: https://store.bfs.band/minecraft/.
- BFS is `bfs.poland.xray` (91.198.166.181), the host of Element.
- `minecraft-wow-tunnel-bfs` connects neuro directly to BFS. The BFS path does
not transit hectic-lab; both tunnels have independent reconnecting services.
- Shared proxy implementation: `nixos/module/generic/minecraft-public-relay.nix`.
Host settings remain in `minecraft-wow-proxy.nix` (hectic-lab) and
`minecraft-wow.nix` (BFS). A dedicated HTTPS virtual host serves `store.bfs.band`. The legacy
`bfs.band/minecraft/` URLs remain available for already imported instances.
- Downloaded BFS ZIP seeds `wow.bfs.band` and uses the stable manifest
`https://store.bfs.band/minecraft/world-of-sosal/current/pack.toml`. It does not
redirect installation metadata to hectic-lab. Upstream mod and Java/loader
downloads still use their original providers (e.g. Modrinth, GitHub, Mojang).
- Existing hectic-lab instances can be migrated without reinstalling mods:
in Edit / Settings / Custom commands, replace only the manifest URL in
Pre-launch command with the BFS URL above. Change the multiplayer server
address to wow.bfs.band. New users should import the ZIP from BFS.
- `script/publish-prism-mirrors.py` builds host-specific ZIPs from one archive
and publishes both mirrors. It checks that the running neuro server's cached
archive has the same SHA-256. Each host's switch is atomic; publication across
two hosts is sequential, so rerun the command if it exits unsuccessfully.
- Both configurations were deployed; public Minecraft status/ping succeeds
on BFS (~125 ms), HTTPS serves the pack, and Element/Matrix HTTP checks pass.
Clean installation through the BFS manifest passed: all 141 client mods and
all overrides match the source archive. A second updater run performed no
downloads and preserved options.txt. The public BFS login protocol reached
online authentication; the earlier full GUI login used hectic-lab.
## BFS DNS and dedicated download site (2026-09-19)
Porkbun DNS, TTL 600:
| Type | Name | Value |
| --- | --- | --- |
| A | store.bfs.band | 91.198.166.181 |
| A | wow.bfs.band | 91.198.166.181 |
| SRV | _minecraft._tcp.wow.bfs.band | 0 0 25568 wow.bfs.band |
Players enter `wow.bfs.band` without a port in Minecraft Java. In Porkbun,
SRV Priority is `0`, and Target is `0 25568 wow.bfs.band` (weight, port, host).
The root download URL https://store.bfs.band/ redirects to the WorldOfSosal page.
The NixOS virtual host obtains and renews its HTTPS certificate automatically.
The publication script now seeds this update URL and the port-free game address.
Existing BFS instances retain working legacy update URLs; switching their
pre-launch manifest to the new store host is optional. Root bfs.band remains
the existing Element entry point.
## RCON and authentication (2026-09-19)
The WoW server now has `online-mode=false`. Account authentication is disabled;
player names can be impersonated, and offline UUIDs differ from online UUIDs.
Existing inventory/permissions may require a separate UUID migration.
RCON listens on TCP 25575 on neuro; its port is not opened in the firewall or
forwarded through the public Minecraft relays. The server-specific automatic
firewall is disabled and only game port 25567 is explicitly permitted.
A random password is stored in SOPS as `minecraft/rcon-password`, injected into
server.properties at startup with mode 0600, and is absent from the Nix store.
Start a local-only SSH tunnel and leave it running:
```sh
ssh -NT -L 127.0.0.1:25575:127.0.0.1:25575 -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 neuro
```
Retrieve the password in another terminal (do not paste it into logs):
```sh
ssh neuro cat /run/secrets/minecraft/rcon-password
```
Configure the RCON client with host `127.0.0.1`, port `25575`, and that password.
There is no RCON username. These changes apply to wowMineMap only.
+119
View File
@@ -0,0 +1,119 @@
# Project Zomboid backups
`hectic.services."project-zomboid".backup` creates local backups without stopping
or pausing the server. The default schedule is every 30 minutes. Each run:
1. sends the local RCON `save` command and waits for the configured save grace
period;
2. rsyncs `Zomboid/Saves/Multiplayer/<serverName>` and non-secret server
settings (`SandboxVars`, spawn-points, and spawn-regions) from
`Zomboid/Server` into a private staging tree;
3. waits five seconds and repeats the rsync to narrow the live-write window;
4. publishes a timestamped `tar.zst` archive; and
5. uploads it to S3 when enabled, then applies local retention.
With `backup.retentionDays = 0`, local timestamped archives are removed after a
successful S3 upload (or after local creation when S3 is disabled). A failed
upload leaves the current archive locally and the next run retries that archive
before creating a new one. Restore archives named `pre-restore` are not managed
by this cleanup.
The service lock prevents overlapping runs. Missing save or server-config paths
skip the run through systemd `ConditionPathExists` checks.
## Consistency and secrets
This is a best-effort backup. It does not stop Project Zomboid and does not use
an atomic filesystem snapshot. The RCON save command flushes the world before
copying, and the second rsync narrows the remaining live-write window, but
neither makes the filesystem copy an atomic snapshot.
Archives do not include the generated server INI, `admin-password`,
host-generated password files, or the S3 credentials file. The server INI is
generated again during service startup; provision secret-backed values separately
after a restore.
## hectic-lab
hectic-lab runs the timer every 30 minutes and stores timestamped backups in
S3 for 14 days. It keeps no regular timestamped backup archives locally:
```text
/var/lib/project-zomboid/backups/archive/
```
The existing `project-zomboid-restore.sh` helper expects the fresh backup it
creates to remain in this directory for rollback. Therefore, with local
retention set to zero, do not use the helper until it is adapted for S3-only
retention; temporarily configure positive local retention for a restore.
Check it with:
```sh
systemctl list-timers project-zomboid-backup.timer
systemctl status project-zomboid-backup.service
journalctl -u project-zomboid-backup.service
```
RCON is enabled on localhost port `27015`; the firewall does not expose this
port. The password is generated at
`/var/lib/project-zomboid/rcon-password` with mode `0600`. The server also uses
`SaveWorldEveryMinutes=15` as a periodic persistence fallback.
## Optional S3 upload
S3 upload is disabled by default. Enabling it requires `bucket`, `endpoint`,
`region`, and an absolute runtime `credentialsFile` outside `/nix/store`. The
endpoint must use HTTPS. systemd reads the environment file without executing
it; this host keeps it owned by `project-zomboid` with mode `0400`:
```sh
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
```
Set `backup.s3.prefix` to choose the object-key prefix and
`backup.s3.remoteRetentionDays` to prune old archives from that prefix. Remote
deletion runs only after a successful upload and only matches this server's
archive name prefix. Configure bucket lifecycle expiration/versioning too when
available; it remains the stronger recovery and cleanup control.
## Restore
Restoring must be done while the server is stopped so it cannot modify files
during extraction:
On hectic-lab, regular timestamped archives are retained only in S3. With
valid S3 credentials, download the chosen archive before restoring it:
```sh
aws s3 cp \
s3://backup-hectic-lab/project-zomboid/project-zomboid-servertest-<timestamp>.tar.zst \
/var/lib/project-zomboid/backups/archive/<archive>.tar.zst \
--endpoint-url https://hel1.your-objectstorage.com \
--region hel1
```
The versioned helper creates a fresh current-state backup, stops the timer and
server, validates archive paths, restores the save, and starts both services:
```sh
sudo ./docs/project-zomboid-restore.sh \
/var/lib/project-zomboid/backups/archive/<archive>.tar.zst
```
It writes a rollback archive named
`project-zomboid-<serverName>-pre-restore-<timestamp>.tar.zst` before changing
the save.
```sh
systemctl stop project-zomboid.service
tar --zstd --no-same-owner --no-same-permissions \
-xf /var/lib/project-zomboid/backups/archive/<archive>.tar.zst \
-C /var/lib/project-zomboid
chown -R project-zomboid:project-zomboid /var/lib/project-zomboid/Zomboid
systemctl start project-zomboid.service
```
Re-provision password files and secret-backed INI values before starting.
Verify the restored save and server name before allowing players to reconnect.
+143
View File
@@ -0,0 +1,143 @@
#!/bin/sh
set -eu
SERVER_NAME=${SERVER_NAME:-servertest}
DATA_DIR=${DATA_DIR:-/var/lib/project-zomboid}
ARCHIVE=${1:-}
usage() {
printf '%s\n' "Usage: $0 /path/to/project-zomboid-${SERVER_NAME}-<timestamp>.tar.zst"
printf '%s\n' "Environment: SERVER_NAME, DATA_DIR"
}
if [ "$(id -u)" -ne 0 ]; then
printf '%s\n' 'Run as root.' >&2
exit 1
fi
if [ -z "$ARCHIVE" ]; then
usage >&2
exit 2
fi
if [ ! -r "$ARCHIVE" ]; then
printf 'Backup archive is not readable: %s\n' "$ARCHIVE" >&2
exit 1
fi
ARCHIVE_DIR="$DATA_DIR/backups/archive"
SAVE_DIR="$DATA_DIR/Zomboid/Saves/Multiplayer/$SERVER_NAME"
SERVER_DIR="$DATA_DIR/Zomboid/Server"
TMP_LIST=$(mktemp)
ROLLBACK_ARCHIVE=''
SERVER_STOPPED=0
RESTORE_SUCCEEDED=0
cleanup() {
rm -f "$TMP_LIST"
}
on_exit() {
status=$?
if [ "$status" -ne 0 ] && [ "$SERVER_STOPPED" -eq 1 ] \
&& [ "$RESTORE_SUCCEEDED" -eq 0 ] && [ -n "$ROLLBACK_ARCHIVE" ]; then
set +e
rm -rf "$SAVE_DIR"
rm -f \
"$SERVER_DIR/${SERVER_NAME}_SandboxVars.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnpoints.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnregions.lua"
tar --zstd --no-same-owner --no-same-permissions \
-xpf "$ROLLBACK_ARCHIVE" -C "$DATA_DIR"
chown -R project-zomboid:project-zomboid "$SAVE_DIR" "$SERVER_DIR"
systemctl start project-zomboid.service
systemctl start project-zomboid-backup.timer
printf '%s\n' "Restore failed; current state restored from $ROLLBACK_ARCHIVE" >&2
fi
cleanup
exit "$status"
}
trap on_exit EXIT
if ! tar --zstd -tf "$ARCHIVE" >"$TMP_LIST"; then
printf 'Archive integrity check failed: %s\n' "$ARCHIVE" >&2
exit 1
fi
while IFS= read -r member; do
case "$member" in
Zomboid/*) ;;
*)
printf 'Unsafe archive member: %s\n' "$member" >&2
exit 1
;;
esac
case "$member" in
/*|*../*)
printf 'Path traversal member: %s\n' "$member" >&2
exit 1
;;
esac
done <"$TMP_LIST"
if ! systemctl start project-zomboid-backup.service; then
printf '%s\n' 'Could not create fresh backup of current state.' >&2
exit 1
fi
CURRENT_ARCHIVE=$(find "$ARCHIVE_DIR" -maxdepth 1 -type f \
-name "project-zomboid-$SERVER_NAME-*.tar.zst" \
-printf '%T@ %p\n' | sort -nr | awk 'NR == 1 {sub(/^[^ ]* /, ""); print}')
if [ -z "$CURRENT_ARCHIVE" ]; then
printf '%s\n' 'Fresh current-state backup was not found.' >&2
exit 1
fi
stamp=$(date -u +%Y%m%dT%H%M%SZ)
ROLLBACK_ARCHIVE="$ARCHIVE_DIR/project-zomboid-$SERVER_NAME-pre-restore-$stamp.tar.zst"
cp --reflink=auto "$CURRENT_ARCHIVE" "$ROLLBACK_ARCHIVE" 2>/dev/null \
|| cp "$CURRENT_ARCHIVE" "$ROLLBACK_ARCHIVE"
chmod 0600 "$ROLLBACK_ARCHIVE"
chown project-zomboid:project-zomboid "$ROLLBACK_ARCHIVE"
systemctl stop project-zomboid-backup.timer
systemctl stop project-zomboid.service
SERVER_STOPPED=1
if [ "$(systemctl show project-zomboid --property=ActiveState --value)" != inactive ]; then
printf '%s\n' 'Project Zomboid did not stop; refusing to restore.' >&2
exit 1
fi
rm -rf "$SAVE_DIR"
rm -f \
"$SERVER_DIR/${SERVER_NAME}_SandboxVars.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnpoints.lua" \
"$SERVER_DIR/${SERVER_NAME}_spawnregions.lua"
tar --zstd --no-same-owner --no-same-permissions \
-xpf "$ARCHIVE" -C "$DATA_DIR"
chown -R project-zomboid:project-zomboid "$SAVE_DIR" "$SERVER_DIR"
systemctl start project-zomboid.service
started=0
for _ in $(seq 1 90); do
if [ "$(systemctl show project-zomboid --property=ActiveState --value)" = active ] \
&& [ "$(systemctl show project-zomboid --property=SubState --value)" = running ]; then
started=1
break
fi
sleep 2
done
if [ "$started" -ne 1 ]; then
printf 'Restore completed, but service did not become healthy. Rollback: %s\n' \
"$ROLLBACK_ARCHIVE" >&2
exit 1
fi
systemctl start project-zomboid-backup.timer
RESTORE_SUCCEEDED=1
printf 'Restore completed.\n'
printf 'Rollback archive: %s\n' "$ROLLBACK_ARCHIVE"
Generated
+62 -1
View File
@@ -625,6 +625,28 @@
"type": "github"
}
},
"iana-angl": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-overlay": "rust-overlay"
},
"locked": {
"lastModified": 1789498292,
"narHash": "sha256-bsrT7MWTXL+tpwDZmI5xWLPZZPYAzU1WjcGlNmqpePw=",
"ref": "refs/heads/master",
"rev": "2937d257d601b40de2437a51ebc3c7b61b40f679",
"revCount": 37,
"type": "git",
"url": "https://gitea.hectic-lab.com/yukkop/learning.git"
},
"original": {
"rev": "2937d257d601b40de2437a51ebc3c7b61b40f679",
"type": "git",
"url": "https://gitea.hectic-lab.com/yukkop/learning.git"
}
},
"impermanence": {
"locked": {
"lastModified": 1737831083,
@@ -893,6 +915,22 @@
"type": "github"
}
},
"nixpkgs-gitea": {
"locked": {
"lastModified": 1790323409,
"narHash": "sha256-VVTPf+Hyd5ebpjBMHmrLMSBIeW6ls48Bqtosj7CNKLA=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e94cb152ed51bd6e24eb4a41f1460252beb52cd2",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1779796641,
@@ -986,6 +1024,7 @@
"hectic-landing": "hectic-landing",
"home-manager": "home-manager",
"hyprland": "hyprland",
"iana-angl": "iana-angl",
"impermanence": "impermanence",
"mechabellum-replay-analysis": "mechabellum-replay-analysis",
"nix-darwin": "nix-darwin",
@@ -995,12 +1034,34 @@
"nixos-mailserver": "nixos-mailserver",
"nixos-wsl": "nixos-wsl",
"nixpkgs": "nixpkgs_2",
"nixpkgs-gitea": "nixpkgs-gitea",
"nixvim": "nixvim",
"rust-overlay": "rust-overlay",
"rust-overlay": "rust-overlay_2",
"sops-nix": "sops-nix"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"iana-angl",
"nixpkgs"
]
},
"locked": {
"lastModified": 1789457514,
"narHash": "sha256-Aggle++fTyAifBy+QBPxjM+obO5iepKW/8MDxQtgGvI=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "89e99bf0778a8f2cd18c9360c3f19c1ee47fc739",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"rust-overlay_2": {
"inputs": {
"nixpkgs": [
"nixpkgs"
+8 -3
View File
@@ -2,6 +2,7 @@
description = "yukkop's nix utilities";
nixConfig = {
http2 = false;
extra-substituters = [
"https://cache.nixos.org"
"https://cache.hectic-lab.com/hectic"
@@ -13,6 +14,7 @@
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
nixpkgs-gitea.url = "github:NixOS/nixpkgs/nixos-unstable";
rust-overlay = {
url = "github:oxalica/rust-overlay";
inputs = {
@@ -72,6 +74,10 @@
url = "git+ssh://git@github.com/liquizz/hectic-landing.git";
inputs.nixpkgs.follows = "nixpkgs";
};
iana-angl = {
url = "git+https://gitea.hectic-lab.com/yukkop/learning.git?rev=2937d257d601b40de2437a51ebc3c7b61b40f679";
inputs.nixpkgs.follows = "nixpkgs";
};
mechabellum-replay-analysis = {
# NOTE(yukkop): private repo - SSH access required.
# Only evaluated when nixosConfigurations."hectic-lab|x86_64-linux" is built.
@@ -83,7 +89,6 @@
outputs = {
self,
nixpkgs,
rust-overlay,
...
}@inputs: let
flake = ./.;
@@ -96,13 +101,13 @@
legacyPackages = import ./legacy { inherit system pkgs self; };
pkgs = import nixpkgs {
inherit system;
overlays = [ (import rust-overlay) ];
overlays = [ (import inputs.rust-overlay) ];
};
in
baseOverlay // legacyPackages;
overlays = [ self.overlays.default ];
in self-lib.forAllSystemsWithPkgs ([(import rust-overlay)] ++ overlays) ({
in self-lib.forAllSystemsWithPkgs ([(import inputs.rust-overlay)] ++ overlays) ({
system,
pkgs,
}: {
+30
View File
@@ -0,0 +1,30 @@
{ pkgs, ... }: {
programs.tmux = {
enable = true;
plugins = with pkgs.tmuxPlugins; [ resurrect continuum ];
keyMode = "vi";
escapeTime = 500;
historyLimit = 50000;
newSession = true;
extraConfig = ''
# resurrect
set -g @resurrect-strategy-vim 'session'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-capture-pane-contents 'on'
resurrect_dir="$HOME/.tmux/resurrect"
set -g @resurrect-dir $resurrect_dir
set -g @resurrect-hook-post-save-all 'target=$(readlink -f $resurrect_dir/last); sed "s| --cmd .*-vim-pack-dir||g; s|/etc/profiles/per-user/$USER/bin/||g; s|/home/$USER/.nix-profile/bin/||g" $target | sponge $target'
# continuum
set -g @continuum-restore 'on'
set -g @continuum-boot 'on'
set -g @continuum-save-interval '10'
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi C-v send-keys -X rectangle-toggle
bind-key O select-pane -t :.-
'';
};
}
+2
View File
@@ -0,0 +1,2 @@
__pycache__/
*.py[cod]
+162
View File
@@ -0,0 +1,162 @@
# Attic repack migration helper
Local-only operator tool for safe resumable Attic cache repack/migration. Parent automation starts old/new services, supplies secrets, seeds spool, and runs this CLI.
## Deployment layout
### Operational state — 2026-09-10
The primary `/hectic` endpoint now serves `nix-cache-hectic-lab` through
`atticd-repacked`; the cutover was applied with NixOS `switch`. The original
bucket/database remain preserved and readable at `/previous/hectic`.
`/next/hectic` is an alias for the new backend. Existing public keys and CI
tokens remain valid, and the primary endpoint is writable again.
The migrated inventory contains 1343 paths and 1195 unique NAR hashes. The
independent inventory comparison and aggregate full-read receipts are recorded
in `/var/lib/attic-repack/verification-receipt.json`. Transient S3 504/read errors
required retries; this is data-integrity evidence, not a claim that Hetzner's
read availability is fixed.
All migration, verification, seeding, and watcher jobs have been stopped for
user-controlled load testing. Do not automatically restart bulk verification.
The transport-fix generation is
`/nix/store/mjx3gzrh03vq22j5nmrzwa56kfhdn702-nixos-system-hectic-lab-25.11.20260526.25f5383`
with the HTTP/1.1 S3 transport and upload-proxy timeout correction. Check
`/run/current-system` to confirm the active deployment.
The pinned rollback generation remains at
`/var/lib/attic-repack/rollback-system`; backups remain private under
`/var/lib/attic-repack/backups` and include the cache signing key.
- Original backend: `atticd`, port 8081, `/var/lib/atticd/server.db`, bucket
`cache-hectic-lab` in HEL1.
- During the write freeze and after cutover the original backend runs in
`api-server` mode, without its garbage collector, to preserve the comparison
dataset. Public write methods remain blocked by nginx.
- Repacked backend: `atticd-repacked`, port 8082,
`/var/lib/atticd-repacked/server.db`, bucket `nix-cache-hectic-lab` in HEL1.
- Both use the same `hectic` signing key and existing JWT verification secret;
clients do not need a new trusted public key or token.
- New chunk settings: threshold/minimum 1 MiB, average 2 MiB, maximum 4 MiB.
- `https://cache.hectic-lab.com/next/hectic` selects the new backend.
- `https://cache.hectic-lab.com/previous/hectic` selects the original backend;
nginx permits GET/HEAD only there.
- `repackedActive` in `nixos/system/hectic-lab/attic.nix` selects which backend
owns the original `/hectic` URL. Keep it false until all cutover gates pass.
## Cutover and rollback gates
1. Finish all migration partitions, then run an unfiltered migration/delta pass.
2. Confirm no CI writers remain. Set `migrationWriteFreeze = true` while
`repackedActive = false`, apply the small NixOS change, and briefly stop the
original Attic to drain/cancel any prior in-flight writes.
3. Take a SQLite backup with SQLite's backup API, not a raw live-file copy.
Keep backups and manifests under private `/var/lib/attic-repack`; the SQLite
backup includes the cache's private signing key.
4. Restart the original backend for reads only, refresh the complete inventory,
migrate any final delta, then run unfiltered `verify` across all 1343 old
paths. Its exit status must be zero with zero exhausted payload verification
failures; independently compare old/new store-path, NAR hash, size and
metadata inventories from the databases. `status` alone is not a cutover
certificate.
5. Pin the old/staging NixOS generation as a GC root, set `repackedActive = true`,
build, inspect dry activation, and switch. `/hectic` now reaches the new
backend; old data and `/previous/hectic` remain available.
6. Test public reads, signatures, and an authenticated upload at the original
URL. Do not remove the old bucket or database as part of this procedure.
Rollback reapplies the pinned staging generation. The new backend and its data
must remain preserved: paths first uploaded after cutover may exist only there.
When editing the flags manually, clear `migrationWriteFreeze` explicitly if
writes to the original backend are intended after rollback.
## Throughput comparison
Compare the same store-path hashes at `/next/hectic` and `/previous/hectic` with
the same request concurrency. For example, fetch
`https://cache.hectic-lab.com/next/hectic/nar/<store-path-hash>.nar` with
`curl --fail --location --output /dev/null --write-out 'bytes=%{size_download} seconds=%{time_total}\n'`.
Do not print effective redirect URLs: S3 redirects contain temporary signatures.
Compare wall time and error rate as well as bytes/second because compressed sizes
can differ after rechunking. Do not use a build with source fallback as a pure
cache throughput measurement. The two endpoints share the VPS and nginx, so run
the comparison sequentially or account for shared-resource contention.
## Spool/state convention
Default state dir: `/var/lib/attic-repack` (`0700`). Raw NAR spool path:
```text
/var/lib/attic-repack/raw/{sha256hex}.nar
```
Parent may seed this file directly. Tool always verifies SHA-256 and byte length before upload. Checkpoints live under `checkpoints/{store_path_hash}.json` and contain no keypair/token. Forced payload verification records a receipt with `payload_verified_at`, `payload_verify_attempts`, `payload_sha256`, and `payload_bytes` only after a complete successful read.
## Commands
```sh
attic-repack init \
--old-db file:/var/lib/atticd/server.db?mode=ro \
--old-url http://127.0.0.1:8081 \
--new-url http://127.0.0.1:8082 \
--host cache.hectic-lab.com \
--atticadm /run/current-system/sw/bin/atticadm \
--server-config /etc/atticd/server.toml
attic-repack inventory --state-dir /var/lib/attic-repack > inventory.json
attic-repack status --state-dir /var/lib/attic-repack
attic-repack migrate --state-dir /var/lib/attic-repack --workers 2 --limit 20
attic-repack verify --state-dir /var/lib/attic-repack --workers 2
```
`ATTIC_MIGRATION_TOKEN` may be set for manual/tests. Otherwise token is minted in memory with `atticadm make-token` for hectic pull/push/create-cache/configure-cache. Token/keypair are never printed.
## Inventory JSON
`inventory` writes `attic-repack-inventory-v1`:
```json
{
"format": "attic-repack-inventory-v1",
"cache": "hectic",
"spool_dir": "/var/lib/attic-repack/raw",
"raw_nar_filename": "{sha256hex}.nar",
"records": [
{"nar_hash":"sha256:...","nar_size":123,"store_path":"/nix/store/...","metadata_fingerprint":"..."}
]
}
```
Records also include upload metadata: `store_path_hash`, `references`, `system`, `deriver`, `sigs`, `ca`.
## Safety
- Checkpoints and `status` are progress information, not a final cutover proof.
After stopping old writers and taking a consistent snapshot, run an unfiltered
`verify` (no `--paths-file` or `--limit`) to reread every new NAR and reconcile
all paths, metadata, hashes, and sizes before switching the primary endpoint.
Do not skip files, change expected hashes, or relax server/client timeouts to
pass this gate.
- A local store path can differ from the historical cached NAR. Such a local
copy is rejected and recovered from the original S3 chunks instead.
- Old DB is opened readonly; old SQL NAR/chunk tables are never copied.
- Missing local raw NARs are reconstructed from old S3 chunkrefs with per-object retries and chunk/full hash checks.
- Upload uses Attic `PUT /_api/v1/upload-path` with JSON preamble plus raw uncompressed NAR.
- New cache verification compares immutable metadata against old rendered narinfo
and reads/decompresses one payload per verified path invocation. Payload reads
make up to three fresh attempts for transport HTTP 408/429/5xx and truncated
body/decompressor EOF failures only. Each attempt follows a new GET/redirect,
starts SHA-256 and byte counts from zero, closes failed readers, and fails
immediately on hash mismatch, full-size mismatch, oversized payload, missing
URL, unsupported compression, or HTTP 4xx other than 408/429.
- A receipt with retries proves the path was fully read and matched integrity; it
does not prove the storage provider is healthy. Treat retry events as provider
health signals separate from cutover correctness.
- Authenticated HTTP is refused unless URL host is loopback.
## Local build/test
```sh
nix build --option eval-cache false --impure --expr "let flake = builtins.getFlake \"git+file://$PWD\"; pkgs = import flake.inputs.nixpkgs { system = builtins.currentSystem; }; in pkgs.callPackage ./infra/attic-migration {}"
nix build --option eval-cache false --impure --expr "let flake = builtins.getFlake \"git+file://$PWD\"; pkgs = import flake.inputs.nixpkgs { system = builtins.currentSystem; }; p = pkgs.callPackage ./infra/attic-migration {}; in p.passthru.tests.unittest"
```
+48
View File
@@ -0,0 +1,48 @@
{ pkgs }:
let
source = pkgs.lib.cleanSourceWith {
src = ./.;
filter = path: type:
builtins.baseNameOf path != "__pycache__"
&& !(pkgs.lib.hasSuffix ".pyc" path);
};
pythonEnv = pkgs.python3.withPackages (ps: [
ps.requests
ps.boto3
ps.zstandard
]);
in
pkgs.stdenv.mkDerivation {
pname = "attic-repack";
version = "0.1.0";
src = source;
nativeBuildInputs = [ pkgs.makeWrapper ];
installPhase = ''
mkdir -p $out/bin $out/libexec/attic-repack
cp $src/repack.py $out/libexec/attic-repack/repack.py
chmod +x $out/libexec/attic-repack/repack.py
makeWrapper ${pythonEnv}/bin/python3 $out/bin/attic-repack \
--add-flags $out/libexec/attic-repack/repack.py \
--prefix PATH : ${pkgs.lib.makeBinPath [ pkgs.nix ]}
'';
doCheck = true;
checkPhase = ''
${pythonEnv}/bin/python3 -m unittest discover -s $src -p 'test_*.py'
'';
passthru = {
inherit pythonEnv;
tests.unittest = pkgs.runCommand "attic-repack-unittest" {
nativeBuildInputs = [ pythonEnv pkgs.nix ];
} ''
cp -r ${source} ./src
chmod -R u+w ./src
${pythonEnv}/bin/python3 -m unittest discover -s ./src -p 'test_*.py'
mkdir -p $out
'';
};
}
File diff suppressed because it is too large Load Diff
+562
View File
@@ -0,0 +1,562 @@
import argparse
import hashlib
import http.server
import io
import json
import os
import pathlib
import sqlite3
import tempfile
import threading
import time
import unittest
from unittest import mock
import repack
def sha(data):
return hashlib.sha256(data).hexdigest()
class FakeResponse:
def __init__(self, status_code=200, content=b"", json_data=None, raw=None, headers=None):
self.status_code = status_code
self.content = content
self._json = json_data
self.raw = raw or io.BytesIO(content)
self.headers = headers or {}
self.close_count = 0
def json(self):
return self._json
def close(self):
self.close_count += 1
class FakeSession:
def __init__(self):
self.calls = []
self.routes = {}
def request(self, method, url, **kwargs):
self.calls.append((method, url, kwargs))
key = (method, pathlib.PurePosixPath(url.split("?", 1)[0]).as_posix())
response = self.routes.get(key) or self.routes.get((method, url))
if callable(response):
return response(method, url, kwargs)
return response or FakeResponse(404)
class ThreadedHTTP:
def __init__(self, handler):
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
@property
def url(self):
host, port = self.server.server_address[:2]
return f"http://{host}:{port}"
def __enter__(self):
self.thread.start()
return self
def __exit__(self, *_args):
self.server.shutdown()
self.thread.join(timeout=5)
self.server.server_close()
class RepackTests(unittest.TestCase):
def test_options_before_subcommand_are_preserved(self):
parser = repack.build_parser()
args = parser.parse_args(["--atticadm", "/safe/atticadm", "--server-config", "/safe/config", "--workers", "1", "init"])
self.assertEqual(args.atticadm, "/safe/atticadm")
self.assertEqual(args.server_config, "/safe/config")
self.assertEqual(args.workers, 1)
args = parser.parse_args(["--workers", "1", "migrate", "--workers", "2"])
self.assertEqual(args.workers, 2)
def test_inventory_reads_sqlite_reserved_references_column(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript('''
CREATE TABLE cache(id INTEGER, name TEXT, deleted_at TEXT);
CREATE TABLE nar(id INTEGER, nar_hash TEXT, nar_size INTEGER, state TEXT);
CREATE TABLE object(cache_id INTEGER, nar_id INTEGER,
store_path_hash TEXT, store_path TEXT, "references" TEXT,
system TEXT, deriver TEXT, sigs TEXT, ca TEXT);
INSERT INTO cache VALUES(1, 'hectic', NULL);
''')
con.execute("INSERT INTO nar VALUES(1, ?, 7, 'V')", ("sha256:" + "a" * 64,))
con.execute("INSERT INTO object VALUES(1, 1, ?, ?, ?, NULL, NULL, ?, NULL)",
("b" * 32, "/nix/store/" + "b" * 32 + "-test", '["dependency"]', '[]'))
con.commit()
con.close()
rows = repack.InventoryDB(str(db), "hectic").records()
self.assertEqual(len(rows), 1)
self.assertEqual(rows[0]["references"], ["dependency"])
def test_metadata_import_keypair_capital(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period integer,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'["up"]',3600,null);
""")
con.close()
args = self.args(td, old_db=str(db))
mig = repack.Migrator(args)
old = mock.Mock()
old.get_cache_config.return_value = {"public_key": "pub"}
new = mock.Mock()
new.get_cache_config.side_effect = [None, {"public_key": "pub"}]
mig.old_client = old
mig.new_client = new
mig.init_cache()
body = new.create_cache.call_args.args[0]
self.assertEqual(body["keypair"], {"Keypair": "priv"})
new.patch_retention.assert_called_with({"Period": 3600})
def test_bad_hash_rejects_raw_spool(self):
with tempfile.TemporaryDirectory() as td:
args = self.args(td)
mig = repack.Migrator(args)
record = self.record(b"good")
raw = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
raw.write_bytes(b"bad")
with self.assertRaises(repack.RepackError):
mig.ensure_raw_nar(record)
def test_local_mismatch_recovers_original_from_old_s3(self):
with tempfile.TemporaryDirectory() as td:
original = b"original cached NAR"
record = self.record(original)
local = pathlib.Path(td) / "different-local-copy"
local.write_bytes(b"different")
record["store_path"] = str(local)
mig = repack.Migrator(self.args(td))
def recover(_record, path):
path.write_bytes(original)
with mock.patch.object(mig, "dump_local_store_path", side_effect=repack.RepackError("nix dump-path NAR hash/size mismatch")), \
mock.patch.object(mig.s3, "assemble", side_effect=recover) as assemble:
result = mig.ensure_raw_nar(record)
self.assertEqual(result.read_bytes(), original)
assemble.assert_called_once()
def test_no_compile_subprocess_commands(self):
with tempfile.TemporaryDirectory() as td:
args = self.args(td)
mig = repack.Migrator(args)
data = b"nar"
record = self.record(data)
store = pathlib.Path(record["store_path"])
with mock.patch("subprocess.run") as run:
def fake_run(cmd, check, stdout, stderr, env):
self.assertEqual(cmd[:3], ["nix", "nar", "pack"])
self.assertNotIn("build", cmd)
self.assertNotIn(repack.TOKEN_ENV, env)
stdout.write(data)
return mock.Mock()
run.side_effect = fake_run
path = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
mig.dump_local_store_path(record, path)
self.assertEqual(path.read_bytes(), data)
self.assertTrue(str(store).startswith("/nix/store/"))
def test_resumable_checkpoint(self):
with tempfile.TemporaryDirectory() as td:
state = repack.State(pathlib.Path(td))
record = self.record(b"abc")
state.set_checkpoint(record, "verified", 2)
cp = state.get_checkpoint(record)
self.assertEqual(cp["status"], "verified")
self.assertEqual(cp["tries"], 2)
self.assertEqual(cp["metadata_fingerprint"], repack.metadata_fingerprint(record))
def test_root_backend_upload_preamble(self):
data = b"abc"
record = self.record(data)
with tempfile.TemporaryDirectory() as td:
nar = pathlib.Path(td) / "x.nar"
nar.write_bytes(data)
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", "cache.hectic-lab.com", repack.TokenProvider(None, None, "hectic"))
assert client.token_provider is not None
client.token_provider._token = "tok"
client.token_provider._expires = repack.now() + 3600
sess = FakeSession()
client._local.session = sess
def put(method, url, kwargs):
self.assertTrue(url.endswith("/_api/v1/upload-path"))
self.assertIn("X-Attic-Nar-Info-Preamble-Size", kwargs["headers"])
self.assertEqual(len(kwargs["data"]), int(kwargs["headers"]["Content-Length"]))
body = kwargs["data"].read()
pre = int(kwargs["headers"]["X-Attic-Nar-Info-Preamble-Size"])
meta = json.loads(body[:pre])
self.assertEqual(meta["store_path"], record["store_path"])
self.assertEqual(body[pre:], data)
return FakeResponse(200)
sess.routes[("PUT", "http://127.0.0.1:8082/_api/v1/upload-path")] = put
client.upload(record, nar)
def test_real_http_upload_has_content_length_no_chunked(self):
try:
repack.requests_module()
except ModuleNotFoundError:
self.skipTest("requests not installed outside Nix test env")
data = b"nar-bytes"
record = self.record(data)
seen = {}
class Handler(http.server.BaseHTTPRequestHandler):
def do_PUT(self):
seen["path"] = self.path
seen["host"] = self.headers.get("Host")
seen["te"] = self.headers.get("Transfer-Encoding")
length = int(self.headers["Content-Length"])
body = self.rfile.read(length)
pre = int(self.headers["X-Attic-Nar-Info-Preamble-Size"])
seen["meta"] = json.loads(body[:pre])
seen["nar"] = body[pre:]
self.send_response(200); self.end_headers()
def log_message(self, format, *args):
pass
with tempfile.TemporaryDirectory() as td, ThreadedHTTP(Handler) as srv:
nar = pathlib.Path(td) / "x.nar"
nar.write_bytes(data)
tp = repack.TokenProvider(None, None, "hectic")
tp._token = "tok"; tp._expires = repack.now() + 3600
repack.AtticClient(srv.url, "hectic", "cache.hectic-lab.com", tp).upload(record, nar)
self.assertEqual(seen["path"], "/_api/v1/upload-path")
self.assertEqual(seen["host"], "cache.hectic-lab.com")
self.assertIsNone(seen["te"])
self.assertEqual(seen["meta"]["store_path"], record["store_path"])
self.assertEqual(seen["nar"], data)
def test_payload_relative_url_and_redirect_strips_host(self):
try:
repack.requests_module()
except ModuleNotFoundError:
self.skipTest("requests not installed outside Nix test env")
data = b"nar"
seen = {}
class S3Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
seen["s3_path"] = self.path
seen["s3_host"] = self.headers.get("Host")
seen["s3_auth"] = self.headers.get("Authorization")
self.send_response(200); self.end_headers(); self.wfile.write(data)
def log_message(self, format, *args):
pass
with ThreadedHTTP(S3Handler) as s3:
class CacheHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
seen["cache_path"] = self.path
seen["cache_host"] = self.headers.get("Host")
seen["cache_auth"] = self.headers.get("Authorization")
self.send_response(302)
self.send_header("Location", s3.url + "/object")
self.end_headers()
def log_message(self, format, *args):
pass
with ThreadedHTTP(CacheHandler) as cache:
client = repack.AtticClient(cache.url, "hectic", "cache.hectic-lab.com", None)
client.verify_payload({"URL":"nar/x","Compression":"none"}, sha(data), len(data), cache.url + "/hectic/abcd.narinfo")
self.assertEqual(seen["cache_path"], "/hectic/nar/x")
self.assertEqual(seen["cache_host"], "cache.hectic-lab.com")
self.assertIsNone(seen["cache_auth"])
self.assertEqual(seen["s3_path"], "/object")
self.assertNotEqual(seen["s3_host"], "cache.hectic-lab.com")
self.assertIsNone(seen["s3_auth"])
def test_payload_retry_truncated_then_full_resets_hash(self):
data = b"complete NAR bytes"
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
responses = [FakeResponse(200, content=data[:4]), FakeResponse(200, content=data)]
def get(_method, _url, _kwargs):
return responses.pop(0)
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = get
with mock.patch("time.sleep") as sleep:
receipt = client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(data), len(data), "http://127.0.0.1:8082/hectic/abcd.narinfo", "/nix/store/abcd-name")
self.assertEqual(receipt, {"attempts": 2, "sha256": sha(data), "bytes": len(data)})
self.assertEqual(len(sess.calls), 2)
self.assertEqual(sleep.call_count, 1)
def test_payload_persistent_timeouts_fail_after_three(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
def timeout(_method, _url, _kwargs):
raise TimeoutError()
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = timeout
with mock.patch("time.sleep") as sleep, self.assertRaises(TimeoutError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"x"), 1, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 3)
self.assertEqual(sleep.call_count, 2)
def test_payload_full_size_wrong_hash_fails_after_one(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = FakeResponse(200, content=b"bad")
with self.assertRaises(repack.PayloadIntegrityError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"nar"), 3, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
def test_payload_oversize_fails_after_one(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = FakeResponse(200, content=b"toolong")
with self.assertRaises(repack.PayloadIntegrityError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"too"), 3, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
def test_payload_http_403_no_retry_and_closes(self):
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession(); client._local.session = sess
resp = FakeResponse(403)
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x")] = resp
with self.assertRaises(repack.RepackError):
client.verify_payload({"URL": "nar/x", "Compression": "none"}, sha(b"x"), 1, "http://127.0.0.1:8082/hectic/abcd.narinfo")
self.assertEqual(len(sess.calls), 1)
self.assertEqual(resp.close_count, 1)
def test_auth_api_redirect_refused(self):
tp = repack.TokenProvider(None, None, "hectic")
tp._token = "tok"; tp._expires = repack.now() + 3600
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, tp)
sess = FakeSession(); client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/_api/v1/cache-config/hectic")] = FakeResponse(302, headers={"Location":"http://evil/"})
with self.assertRaises(repack.RepackError):
client.get_cache_config()
def test_concatenated_zstd_correct(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
plain = b"a" * 100 + b"b" * 100
cctx = zstd.ZstdCompressor()
payload = cctx.compress(plain[:100]) + cctx.compress(plain[100:])
narinfo = {"URL": "nar/x.nar.zst", "Compression": "zstd"}
client = repack.AtticClient("http://127.0.0.1:8082", "hectic", None, None)
sess = FakeSession()
client._local.session = sess
sess.routes[("GET", "http://127.0.0.1:8082/hectic/nar/x.nar.zst")] = FakeResponse(200, raw=io.BytesIO(payload))
client.verify_payload(narinfo, sha(plain), len(plain), "http://127.0.0.1:8082/hectic/abcd.narinfo")
def test_perchunk_retry_cache(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
plain = b"chunk"
comp = zstd.ZstdCompressor().compress(plain)
con = sqlite3.connect(db)
con.executescript("""
create table chunkref(nar_id integer,seq integer,chunk_id integer);
create table chunk(id integer primary key,state text,chunk_hash text,chunk_size integer,file_hash text,file_size integer,compression text,remote_file text);
""")
con.execute("insert into chunkref values(1,0,1)")
con.execute("insert into chunk values(1,'V',?,?,?,?,?,?)", (sha(plain), len(plain), sha(comp), len(comp), "zstd", json.dumps({"S3":{"region":"hel1","bucket":"cache-hectic-lab","key":"k"}})))
con.commit(); con.close()
state = repack.State(pathlib.Path(td) / "state")
asm = repack.OldS3Assembler(repack.InventoryDB(str(db), "hectic"), state, "https://example", "cache-hectic-lab", "hel1")
fake_client = mock.Mock()
fake_client.get_object.side_effect = [Exception("once"), {"Body": io.BytesIO(comp)}]
out = pathlib.Path(td) / "out.nar"
with mock.patch.object(asm, "client", return_value=fake_client):
asm.assemble({"nar_id": 1, "nar_hash": "sha256:" + sha(plain), "nar_size": len(plain)}, out)
self.assertEqual(out.read_bytes(), plain)
self.assertEqual(fake_client.get_object.call_count, 2)
fake_client.get_object.reset_mock()
self.assertEqual(asm._compressed_chunk(asm.db.chunk_rows(1)[0]), comp)
fake_client.get_object.assert_not_called()
def test_chunk_prefetch_is_bounded_and_preserves_order(self):
with tempfile.TemporaryDirectory() as td:
pieces = [f"chunk-{i}\n".encode() for i in range(12)]
rows = [{"seq": i, "compression": "none", "chunk_hash": sha(data), "chunk_size": len(data)}
for i, data in enumerate(pieces)]
db = mock.Mock()
db.chunk_rows.return_value = rows
asm = repack.OldS3Assembler(db, repack.State(pathlib.Path(td) / "state"), "https://example", "cache-hectic-lab", "hel1")
lock = threading.Lock()
active = 0
peak = 0
def fetch(row):
nonlocal active, peak
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.04 if row["seq"] == 0 else 0.01)
with lock:
active -= 1
return pieces[row["seq"]]
whole = b"".join(pieces)
out = pathlib.Path(td) / "result.nar"
with mock.patch.object(asm, "_compressed_chunk", side_effect=fetch):
asm.assemble({"nar_id": 1, "nar_hash": "sha256:" + sha(whole), "nar_size": len(whole)}, out)
self.assertEqual(out.read_bytes(), whole)
self.assertGreater(peak, 1)
self.assertLessEqual(peak, 4)
def test_zstd_chunk_no_content_size_concat(self):
try:
zstd = repack.zstd_module()
except ModuleNotFoundError:
self.skipTest("zstandard not installed outside Nix test env")
cctx = zstd.ZstdCompressor(write_content_size=False)
payload = cctx.compress(b"aa") + cctx.compress(b"bb")
self.assertEqual(repack.decompress_chunk(payload, "zstd"), b"aabb")
def test_mismatch_new_key_fails(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period text,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'[]',null,null);
""")
con.close()
mig = repack.Migrator(self.args(td, old_db=str(db)))
mig.old_client = mock.Mock(); mig.old_client.get_cache_config.return_value = {"public_key":"old"}
mig.new_client = mock.Mock(); mig.new_client.get_cache_config.return_value = {"public_key":"new","is_public":True,"store_dir":"/nix/store","priority":30,"upstream_cache_key_names":[]}
with self.assertRaises(repack.RepackError):
mig.init_cache()
def test_init_requires_old_public_key(self):
with tempfile.TemporaryDirectory() as td:
db = pathlib.Path(td) / "old.db"
con = sqlite3.connect(db)
con.executescript("""
create table cache(id integer primary key,name text,keypair text,is_public integer,store_dir text,priority integer,upstream_cache_key_names text,retention_period text,deleted_at text);
insert into cache values(1,'hectic','priv',1,'/nix/store',30,'[]',null,null);
""")
con.close()
mig = repack.Migrator(self.args(td, old_db=str(db)))
mig.old_client = mock.Mock(); mig.old_client.get_cache_config.return_value = {}
mig.new_client = mock.Mock(); mig.new_client.get_cache_config.return_value = None
with self.assertRaises(repack.RepackError):
mig.init_cache()
def test_verify_readonly_no_put(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
mig.selected_records = lambda: [record]
mig.new_client = mock.Mock()
mig.new_client.get_narinfo.return_value = {**repack.expected_narinfo(record), "URL": "nar/x", "Compression": "none"}
mig.new_client.verify_payload.return_value = {"attempts": 1, "sha256": sha(b"abc"), "bytes": 3}
mig.new_client.narinfo_url.return_value = "http://127.0.0.1:8082/hectic/abcd.narinfo"
mig.old_client = mock.Mock()
mig.old_client.get_narinfo.return_value = {**repack.expected_narinfo(record)}
mig.migrate(True)
mig.new_client.upload.assert_not_called()
mig.new_client.verify_payload.assert_called_once()
def test_payload_receipt_only_for_forced_successful_full_read(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
mig.selected_records = lambda: [record]
narinfo = {**repack.expected_narinfo(record), "URL": "nar/x", "Compression": "none"}
old_info = {**repack.expected_narinfo(record)}
mig.old_client = mock.Mock(); mig.old_client.get_narinfo.return_value = old_info
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = narinfo; mig.new_client.narinfo_url.return_value = "http://127.0.0.1/hectic/abcd.narinfo"
mig.new_client.verify_payload.return_value = {"attempts": 2, "sha256": sha(b"abc"), "bytes": 3}
self.assertEqual(mig.migrate(True), 0)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["payload_verify_attempts"], 2)
self.assertEqual(cp["payload_sha256"], sha(b"abc"))
self.assertEqual(cp["payload_bytes"], 3)
self.assertTrue(cp["payload_verified_at"].endswith("Z"))
first_verified_at = cp["payload_verified_at"]
mig.new_client.verify_payload.reset_mock()
self.assertEqual(mig.migrate(False), 0)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["payload_verified_at"], first_verified_at)
mig.new_client.verify_payload.assert_not_called()
mig.new_client.get_narinfo.return_value = narinfo
mig.new_client.verify_payload.side_effect = repack.PayloadIntegrityError("new NAR payload hash/size mismatch")
self.assertEqual(mig.migrate(True), 1)
cp = mig.state.get_checkpoint(record)
self.assertEqual(cp["status"], "failed")
self.assertNotIn("payload_verified_at", cp)
self.assertNotIn("payload_sha256", cp)
def test_key_redaction(self):
secret = "eyJhbGciOiPRIVATEKEYX-Amz-Signature=abc"
msg = repack.sanitized_error(RuntimeError("https://x/y?" + secret))
self.assertEqual(msg, "RuntimeError")
self.assertNotIn(secret, msg)
def test_old_new_narinfo_sig_compare_allows_db_sigs_empty(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
record["sigs"] = []
old_info = {**repack.expected_narinfo(record), "Sig": ["hectic:sig"]}
new_info = dict(old_info)
mig.old_client = mock.Mock(); mig.old_client.get_narinfo.return_value = old_info
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = new_info; mig.new_client.narinfo_url.return_value = "http://127.0.0.1/hectic/abcd.narinfo"
mig.new_client.verify_payload.return_value = None
self.assertTrue(mig.verify_record(record, False))
def test_migrate_record_missing_narinfo_raises(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
record = self.record(b"abc")
raw = mig.state.raw_path(repack.nar_hash_hex(record["nar_hash"]))
raw.write_bytes(b"abc")
mig.new_client = mock.Mock(); mig.new_client.get_narinfo.return_value = None
with self.assertRaises(repack.RepackError):
mig.migrate_record(record)
def test_migrate_returns_failed_count(self):
with tempfile.TemporaryDirectory() as td:
mig = repack.Migrator(self.args(td))
mig.selected_records = lambda: [self.record(b"abc")]
mig.migrate_record = mock.Mock(side_effect=repack.RepackError("new narinfo missing"))
self.assertEqual(mig.migrate(False), 1)
def test_readonly_old_db_rejects_rw_and_missing(self):
with self.assertRaises(repack.RepackError):
repack.InventoryDB("file:/tmp/x.db?mode=rwc", "hectic")
with self.assertRaises(repack.RepackError):
repack.InventoryDB("/tmp/definitely-missing-attic.db", "hectic")
def test_verify_hash_size_fail_closed_unknown_hash(self):
with self.assertRaises(repack.RepackError):
repack.verify_hash_size(b"x", "sha1:abc", 1, "chunk")
def args(self, td, old_db=":memory:"):
return argparse.Namespace(old_db=old_db, state_dir=str(pathlib.Path(td) / "state"), old_url="http://127.0.0.1:8081", new_url="http://127.0.0.1:8082", host="cache.hectic-lab.com", cache="hectic", atticadm=None, server_config=None, nix="nix", old_storage_endpoint="https://hel1.your-objectstorage.com", old_bucket="cache-hectic-lab", old_region="hel1", workers=2, limit=None, paths_file=None)
def record(self, data):
h = sha(data)
return {"cache":"hectic","nar_id":1,"store_path_hash":"abcd","store_path":"/nix/store/abcd-name","references":["/nix/store/ref-ref"],"system":"x86_64-linux","deriver":None,"sigs":["cache:sig"],"ca":None,"nar_hash":"sha256:" + h,"nar_size":len(data)}
if __name__ == "__main__":
unittest.main()
+14 -26
View File
@@ -24,43 +24,30 @@ Preferred registry:
gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image
```
Publish the archive without adding secrets to the image layers, then use the
registry-reported digest as the only final `nix` label image reference:
Publish the archive without adding secrets to the image layers. Controller-owned
zero-idle runners select this image through `nixImageId` / `GCR_NIX_IMAGE_ID`;
they do not use a Gitea label-to-container-image mapping:
```text
nix:docker://gitea.hectic-lab.com/hectic-lab/gitea-runner-nix-image@sha256:<registry-digest>
nixImageId = "<Hetzner-image-id>";
```
The `2026-06-07` tag may be pushed as a human-readable companion tag, but the
runner label mapping must use the `@sha256:` reference above. Keep
`ubuntu-latest` on the `gitea/runner` default image unless a later runner
configuration task explicitly changes it. Only the `nix` label should select
this custom image.
The `2026-06-07` tag may be pushed as a human-readable companion tag. The
legacy Kubernetes rollback pool is currently disabled and has no labels.
If it is restored, its Nix-capable image must be configured separately and
digest-pinned before enabling a `nix` label.
If the Gitea container registry is unavailable, select a private registry that
is reachable from the runner Kubernetes cluster and requires authentication that
can be provided through Kubernetes image-pull secrets. Record the selected
registry and replace the host in the same digest-pinned form:
```text
nix:docker://<private-registry>/<namespace>/gitea-runner-nix-image@sha256:<registry-digest>
```
Do not fall back to `latest` or a tag-only mapping.
Do not use a tag-only image for a restored Kubernetes rollback pool.
## Task 7 publication status
Local build evidence is recorded in
`.sisyphus/evidence/task-7-image-digest.txt`. In this environment, Docker could
load and tag the image, but pushing to the preferred registry failed with
`unauthorized: reqPackageAccess`, so no registry digest was available to pin as a
concrete final mapping. Kubernetes pull smoke is recorded in
`.sisyphus/evidence/task-7-image-digest.txt`. Kubernetes pull smoke is recorded in
`.sisyphus/evidence/task-7-image-pull.txt` and is blocked here because `kubectl`
is not installed or not on `PATH`.
Once registry credentials are available, rerun the push, capture the
registry-reported digest, and replace `<registry-digest>` in the mapping above
before Task 6/9 consumes the label configuration.
After importing the archive as a Hetzner image, record its image ID in the
controller host configuration before dispatching Nix jobs.
## Image contents
@@ -71,7 +58,8 @@ top-level `flake.nix`:
```text
experimental-features = nix-command flakes
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gW4x6l1xP+GxgH0r7u+f6p1VFlr0= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
http2 = false
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false
```
+2 -4
View File
@@ -19,10 +19,8 @@ data:
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
labels:
- ubuntu-latest
# The nix label is intentionally disabled until the runner image has a
# concrete registry-reported digest; see ../runbook.md before deploy.
# Persistent pool is disabled; controller owns all runner labels.
labels: []
cache:
enabled: true
+2 -1
View File
@@ -8,7 +8,8 @@ metadata:
app.kubernetes.io/part-of: gitea-actions
spec:
serviceName: gitea-runner
replicas: 5
# Rollback-only pool. Keep manifest present, default replicas 0.
replicas: 0
podManagementPolicy: Parallel
selector:
matchLabels:
+12 -6
View File
@@ -63,19 +63,25 @@ The default cluster is deliberately fixed-size:
- cluster name: `gitea-runners`
- Hetzner location: `fsn1`
- private network region: `eu-central`
- control plane: one `cpx21` node in pool `control-plane`
- workers: three `cpx31` nodes in pool `runner-workers`
- control plane: one `cpx22` node in pool `control-plane`
- workers: one `cpx22` node in pool `runner-workers`
- storage: Hetzner CSI enabled with expected StorageClass `hcloud-volumes`
- Longhorn: disabled
- autoscaling/KEDA: not enabled in this stack
The three default workers are sized for the initial five trusted privileged DinD
jobs. To scale toward ten jobs later, keep autoscaling disabled and either raise
`worker_count` to `5` or increase `worker_server_type`, then run a fresh
`tofu plan` and the Task 11 Kubernetes pressure checks before applying.
The default baseline uses one `cpx22` worker to keep the idle bill low while
still supporting trusted internal jobs. To scale toward higher concurrency
later, keep autoscaling disabled and either raise `worker_count` or increase
`worker_server_type`, then run a fresh `tofu plan` and the Task 11 Kubernetes
pressure checks before applying.
Required inputs must come from environment or secret injection, for example
`TF_VAR_hcloud_token`, `TF_VAR_ssh_public_key`, and `TF_VAR_ssh_private_key`.
Set `TF_VAR_firewall_ssh_source` and `TF_VAR_firewall_kube_api_source` explicitly
to trusted CIDR ranges before planning; the cluster must not expose SSH or port
6443 to `0.0.0.0/0`.
If the public key is already registered in Hetzner, set
`TF_VAR_hcloud_ssh_key_id` to reuse it instead of creating a duplicate key.
Do not commit `.tfvars` files. kube-hetzner v2.19.3 writes the generated
kubeconfig to `./<cluster_name>_kubeconfig.yaml` when `create_kubeconfig` is
enabled; this path is ignored as operational secret material.
+16 -5
View File
@@ -1,10 +1,21 @@
terraform {
backend "s3" {
bucket = "gitea-runner-hectic-lab"
key = "gitea-runners/kube-hetzner/terraform.tfstate"
region = "fsn1"
encrypt = true
use_lockfile = true
bucket = "gitea-runner-hectic-lab"
key = "gitea-runners/kube-hetzner/terraform.tfstate"
region = "hel1"
endpoints = {
s3 = "https://hel1.your-objectstorage.com"
}
skip_credentials_validation = true
skip_metadata_api_check = true
skip_region_validation = true
skip_requesting_account_id = true
use_path_style = true
encrypt = false
skip_s3_checksum = true
use_lockfile = true
}
}
@@ -0,0 +1,39 @@
"apiVersion": "kustomize.config.k8s.io/v1beta1"
"kind": "Kustomization"
"patches":
- "patch": |
apiVersion: apps/v1
kind: Deployment
metadata:
name: system-upgrade-controller
namespace: system-upgrade
spec:
template:
spec:
containers:
- name: system-upgrade-controller
volumeMounts:
- name: ca-certificates
mountPath: /var/lib/ca-certificates
volumes:
- name: ca-certificates
hostPath:
path: /var/lib/ca-certificates
type: Directory
"target":
"group": "apps"
"kind": "Deployment"
"name": "system-upgrade-controller"
"namespace": "system-upgrade"
"version": "v1"
- "path": "kured.yaml"
- "path": "ccm.yaml"
"resources":
- "https://github.com/kubereboot/kured/releases/download/1.23.0/kured-1.23.0-combined.yaml"
- "https://github.com/rancher/system-upgrade-controller/releases/download/v0.18.0/system-upgrade-controller.yaml"
- "https://github.com/rancher/system-upgrade-controller/releases/download/v0.18.0/crd.yaml"
- "https://github.com/hetznercloud/hcloud-cloud-controller-manager/releases/download/v1.35.0/ccm-networks.yaml"
- "hcloud-csi.yaml"
- "traefik_ingress.yaml"
- "flannel-rbac.yaml"
- "cert_manager.yaml"
+3
View File
@@ -47,6 +47,9 @@ module "kube_hetzner" {
load_balancer_location = var.hetzner_location
control_plane_nodepools = local.control_plane_nodepools
agent_nodepools = local.agent_nodepools
firewall_ssh_source = var.firewall_ssh_source
firewall_kube_api_source = var.firewall_kube_api_source
hcloud_ssh_key_id = var.hcloud_ssh_key_id
# Hetzner CSI is the required StorageClass provider for runner PVCs.
disable_hetzner_csi = false
+22 -6
View File
@@ -39,21 +39,21 @@ variable "network_region" {
}
variable "control_plane_server_type" {
description = "Default control-plane server type. cpx21 is small but leaves headroom for kube-system workloads."
description = "Default control-plane server type. cpx22 is small but leaves headroom for kube-system workloads."
type = string
default = "cpx21"
default = "cpx22"
}
variable "worker_server_type" {
description = "Default worker server type for the initial trusted DinD runner pool. Three cpx31 workers provide enough headroom for five privileged jobs before Task 11 scaling validation."
description = "Default worker server type for the budget trusted DinD cluster. One cpx22 worker keeps the cluster baseline cheap; scale out later if rollback capacity requires it."
type = string
default = "cpx31"
default = "cpx22"
}
variable "worker_count" {
description = "Fixed worker count. Increase to 5 or choose a larger worker_server_type later to target 10 concurrent DinD jobs; do not enable autoscaling in this stack."
description = "Fixed worker count. Default is a single cheap worker for low-cost baseline operation; increase later if concurrency requires it."
type = number
default = 3
default = 1
validation {
condition = var.worker_count >= 1
@@ -72,3 +72,19 @@ variable "base_domain" {
type = string
default = ""
}
variable "firewall_ssh_source" {
description = "CIDR ranges allowed to SSH to cluster nodes. Set explicitly; never expose SSH to the public internet."
type = list(string)
}
variable "firewall_kube_api_source" {
description = "CIDR ranges allowed to reach the Kubernetes API. Set explicitly; never expose port 6443 to the public internet."
type = list(string)
}
variable "hcloud_ssh_key_id" {
description = "Existing Hetzner SSH key ID. Set this when the public key is already registered in the project."
type = string
default = null
}
+215 -35
View File
@@ -2,15 +2,13 @@
## Scope
This directory is the repo-owned boundary for the first Gitea Actions runner
pool. Task 1 only establishes the scaffold and immutable decision contract;
downstream tasks will add OpenTofu backend/provider files, Kubernetes manifests,
and a Nix-capable runner image under the existing subdirectories.
This directory is the repo-owned boundary for the Gitea Actions runner pool.
The controller is the active on-demand path; Kubernetes manifests and the
Nix-capable image are retained for manual rollback and maintenance.
The target service is `https://gitea.hectic-lab.com` for the Gitea organization
`hectic-lab`. The first pool is fixed-size and trusted-only. "Ephemeral" means
workflow job containers are ephemeral, while each runner pod keeps its runner
identity in per-pod `/data/.runner` storage backed by a StatefulSet PVC.
`hectic-lab`. The pool is trusted-only. "Ephemeral" means each controller VM
and workflow job is disposable; the Kubernetes StatefulSet is rollback-only.
## Immutable decisions
@@ -27,21 +25,21 @@ identity in per-pod `/data/.runner` storage backed by a StatefulSet PVC.
`/data`, including `/data/.runner`.
- Container builds run through privileged rootful DinD inside trusted runner
pods; host Docker socket mounting is not an implementation path.
- The active runner label is `ubuntu-latest`. The `nix` label is not live until
the Nix-capable image has been pushed and a concrete registry-reported digest
is added to the runner ConfigMap.
- `ubuntu-latest` and `nix` are controller-managed on-demand aliases for
`gross-x86` and `gross-nix-x86`; the Kubernetes pool has no active labels.
- First scope is trusted internal workflows only, with no untrusted fork or PR
workflow support.
- First scope has no autoscaling, no KEDA, and no dynamic runner controller.
- On-demand allocation is handled by the repo-owned controller; Kubernetes is
not an active autoscaling path.
## Lifecycle boundaries
- `infra/gitea-runners/opentofu/`: downstream OpenTofu stack for the S3 backend
- `infra/gitea-runners/opentofu/`: OpenTofu stack for the S3 backend
contract, Hetzner provider configuration, and kube-hetzner module wiring.
- `infra/gitea-runners/k8s/`: downstream namespace, ConfigMap, Secret mount,
- `infra/gitea-runners/k8s/`: rollback-only namespace, ConfigMap, Secret mount,
StatefulSet, PVC, DinD sidecar, cleanup, and operational manifest work.
- `infra/gitea-runners/image/`: downstream notes or sources for the runner image
handoff; package or flake output changes are outside Task 1.
- `infra/gitea-runners/image/`: notes and handoff for the optional Kubernetes
rollback image; active on-demand Nix image is selected by Hetzner image ID.
- `infra/gitea-runners/runbook.md`: this contract plus later operational
commands, rollback notes, and acceptance evidence references.
@@ -52,8 +50,8 @@ identity in per-pod `/data/.runner` storage backed by a StatefulSet PVC.
instructions, or GitHub Actions ARC assumptions.
- Untrusted fork/PR workflows are out of first scope; privileged DinD is only
acceptable for trusted internal jobs.
- Autoscaling/KEDA is out of first scope; start with a fixed-size StatefulSet
runner pool.
- The persistent StatefulSet is rollback-only and defaults to zero replicas;
normal jobs use controller-managed on-demand VMs.
- No actual secrets are committed: no kubeconfig, runner token, Hetzner token,
S3 credentials, decrypted SOPS files, or SOPS age keys.
- OpenTofu must not manage plaintext Kubernetes Secrets containing the Gitea
@@ -248,8 +246,7 @@ These commands are executable only when the external inputs are available:
- S3 backend credentials and endpoint access
- a matching SOPS age identity for `sus/gitea-runners.yaml`
- `kubectl` access to the target cluster
- a concrete digest for the pushed Nix-capable runner image, if enabling the
`nix` label
- a valid `GCR_NIX_IMAGE_ID` for controller-managed Nix jobs
If any input is missing, stop before `tofu apply`. Do not guess values or reuse
stale kubeconfig files.
@@ -260,15 +257,12 @@ Before production Kubernetes apply or rollout, satisfy both manifest gates:
Kustomize overlay intentionally does not include a placeholder Secret, but
the StatefulSet still mounts `secretName: gitea-runner-token` as
`/runner-secrets/token` for `GITEA_RUNNER_REGISTRATION_TOKEN_FILE`.
2. Keep the active ConfigMap on `ubuntu-latest` only unless the Nix-capable
image has been pushed successfully. Enable the `nix` label only by adding a
digest-pinned `docker://` mapping with the exact registry-reported sha256
digest from that push.
2. Keep the persistent-pool ConfigMap labels empty. Runner labels belong to the
controller; Nix image readiness is governed by `GCR_NIX_IMAGE_ID`.
Use the same SOPS materialization pattern as token rotation before applying the
Kubernetes overlay. Applying the namespace alone is allowed so the Secret has a
target namespace; the full overlay remains gated on the Secret and digest
decisions:
target namespace; the full overlay remains gated on the Secret.
```sh
kubectl apply -f infra/gitea-runners/k8s/namespace.yaml
@@ -283,8 +277,7 @@ kubectl -n gitea-runners create secret generic gitea-runner-token \
```
Do not run `kubectl apply -k infra/gitea-runners/k8s` until the Secret command
above succeeds. Do not claim or enable the `nix` runner label until the image
publication step has produced the concrete digest.
above succeeds. The persistent pool ConfigMap must retain empty labels.
```sh
tofu -chdir=infra/gitea-runners/opentofu init
@@ -309,14 +302,14 @@ Expected status after deploy:
- `kubectl config current-context` names the runner cluster context.
- `kubectl get nodes -o wide` shows all expected Hetzner nodes Ready.
- `kubectl get sc` shows the Hetzner CSI storage class used by runner PVCs.
- `kubectl -n gitea-runners get statefulset gitea-runner` shows 5 desired and 5 ready replicas.
- `kubectl -n gitea-runners get pvc` shows 5 Bound PVCs.
- `kubectl -n gitea-runners logs statefulset/gitea-runner -c runner --tail=200` shows the runner daemon started and no token value.
- `kubectl -n gitea-runners get statefulset gitea-runner` shows 0 desired and 0 ready replicas.
- `kubectl -n gitea-runners get pvc` shows no active runner PVCs; retained PVCs are rollback-only.
- The controller host reports healthy and owns runner registrations; no persistent runner claims `ubuntu-latest` or `nix`.
## Scale 5 to 10 to 5
## Legacy rollback pool scaling (manual only)
Scaling is a temporary capacity exercise, not the steady-state setting. Scale up,
wait for readiness, run the concurrent smoke jobs, then scale back down to 5.
Persistent-pool scaling is not part of normal operation. Use only after restoring
its labels and disabling the zero-idle controller as described in `Rollback`.
```sh
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=10
@@ -324,7 +317,7 @@ kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
kubectl -n gitea-runners get pods -l app.kubernetes.io/name=gitea-runner -o wide
kubectl -n gitea-runners get pvc -l app.kubernetes.io/name=gitea-runner -o wide
# Run the concurrent smoke workflows now.
# Run only workflows supported by restored persistent labels.
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=5
kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
@@ -405,7 +398,7 @@ Do not run the delete command for a runner that still has an active
`gitea-runner-*` pod or retained `data-gitea-runner-*` PVC unless that PVC is
being intentionally reset for re-registration.
## Application rollback
## Legacy Kubernetes application rollback
Rollback the app layer only. Do not use this section to destroy the cluster.
@@ -501,3 +494,190 @@ Do not release unless the following evidence files exist and are readable:
If any evidence file is missing, stop and collect it before treating the runbook
as complete.
## Ephemeral VM runner cutover
This section governs replacing the legacy persistent K8s runner pool with the
ephemeral-VM controller (`package/gitea-runner-controller`) on this host.
The K8s pool above remains rollback-only until cutover is explicitly accepted.
### Operator gates (all three required before enable)
1. Secrets — add to `sus/gitea-runners.yaml` under
`gitea/hectic-lab/controller/*`:
```sh
sops sus/gitea-runners.yaml
# add keys:
# gitea:
# hectic-lab:
# controller:
# hcloud-token: <Hetzner API token, VM create/destroy scope>
# webhook-secret: <random 32+ bytes; also set as Gitea webhook secret>
# admin-token: <Gitea token with admin:runner scope for stale cleanup>
```
The org registration token key
`gitea/hectic-lab/org-runner-registration-token` already exists and is reused.
2. Base image — build the MicroOS snapshot and record its id:
```sh
nix develop .#gitea-runners -c gitea-runners-build-microos-snapshots x86
hcloud image list --selector '' -o json | jq '.[] | select(.type=="snapshot")'
```
3. DNS — A record `runners.hectic-lab.com -> 128.140.75.58` (ACME needs it).
### Enable
```sh
# nixos/system/hectic-lab/hectic-lab.nix: resolve the FIXME block
hectic.services.gitea-runner-controller = {
enable = true;
imageId = "<snapshot-id-from-gate-2>";
};
nixos-rebuild --target root@128.140.75.58 switch
systemctl status gitea-runner-controller.service gitea-runner-webhook.service
```
### Register the Gitea webhook
Org-level (preferred) or per-repo, on `https://gitea.hectic-lab.com`:
- URL: `https://runners.hectic-lab.com/`
- Method: `POST`, content type: JSON
- Secret: value of `gitea/hectic-lab/controller/webhook-secret`
- Trigger events: `Workflow jobs` only (`workflow_job`)
### Long CUDA/Magma deployment time budgets
The `deploy-neuro` workflow uses these nested limits:
| Layer | Limit |
| --- | --- |
| Wrapped build/deploy command | 6 hours (`WITH_ATTIC_BUILD_TIMEOUT=21600`) |
| Final cache drain | 1 hour (`WITH_ATTIC_DRAIN_TIMEOUT=3600`) |
| Workflow job | 435 minutes, including 15 minutes of setup/cleanup margin |
| `gross-nix-x86-perf` runner | 480 minutes |
| `gross-nix-x86-highmem` runner | 480 minutes |
| Gitea `actions.ENDLESS_TASK_TIMEOUT` | 8 hours |
| VM hard lifetime from allocation | 480 minutes; no destruction grace |
`ubuntu-latest` keeps a 180-minute limit; `nix` uses a 480-minute limit for
long-running Nix deployments. Deploy the controller and Gitea watchdog settings
before dispatching the longer workflow. Already
allocated VMs retain the TTL and runner configuration assigned when they were
created; updating the controller does not extend a running job.
`gross-nix-x86-highmem` is an explicit costly high-memory escape hatch backed
only by Hetzner CCX53 in `nbg1`, `fsn1`, or `hel1`; it may fall back by region
only, never to a lower-RAM server type. Current Hetzner public pricing for
Germany/Finland CCX53 is 0.8550 EUR/hour excluding IPv4, so one 480-minute
allocation reserves 6.84 EUR against the controller budget before VM creation.
These are maximum lifetimes. Unbootstrapped or profile-invalid VMs trigger
immediate teardown; failed jobs retain pre-destroy diagnostics. A healthy,
bootstrapped terminal VM may stay running until the next hourly boundary
measured from original VM creation, capped by its original hard TTL.
Retention first enters a durable retirement state. The controller disables the
exact repository runner registration, deletes it, and confirms its absence
before clearing repository, label, and runner ownership into generic idle. A
queued job from any allowed repository can atomically claim generic idle only
when persisted server type, location, architecture, and image match one of the
job label's candidates. The VM then remains unschedulable while Hetzner rebuilds
its root disk from that clean image. Controller verifies rebuild action and
server identity, current image/profile, and current IP before fetching a fresh
destination-repository token and bootstrapping a new runner name. Old runner
registration and filesystem are never reused.
For every creation and reuse rebuild, the controller generates a unique SSH
host key, injects it through authenticated Hetzner `user_data`, and pins that
exact public key before sending a registration token. Shared image host keys
and trust-on-first-use are not used. Runner images must process Hetzner
cloud-init `write_files` during create and rebuild; verify this image gate before
dispatching jobs. If host-key injection fails, bootstrap remains fail-closed.
Reuse preserves original Hetzner VM creation time, hard TTL, and budget charge;
it creates no server and makes no second reservation. Provider or registration
uncertainty remains in a non-schedulable durable state, and unrecoverable rebuild
uncertainty destroys the VM. Idle VMs are still billed: controller deletes them
at slot expiry and never relies on stopping a server to avoid charges. Allowed
repositories remain trusted-only and must not run untrusted fork or pull-request
code.
Active and idle VMs are deleted at profile hard TTL without grace. Idle reuse is
allowed only when at least one configured reconcile interval remains before both
slot expiry and hard TTL. Controller budget reservation still uses full label TTL
on initial creation, so a long-running label reserves more of existing monthly
budget. Do not raise that budget or disable timeout safeguards just to bypass a
refused allocation.
After changing any timeout, verify the complete chain rather than only
`timeout-minutes`; a shorter wrapper, runner, server watchdog, or VM TTL wins.
### Pre-flight verification (before first real job)
```sh
curl -fsS https://runners.hectic-lab.com/ -o /dev/null -w '%{http_code}\n' # any 4xx from handler = reachable
journalctl -u gitea-runner-webhook -n 20 --no-pager
hcloud server list -o json | jq '[.[] | select(.labels["gitea-runner-controller"]=="managed")] | length' # expect 0
```
Zero managed VMs is expected after retained billing slots expire. Immediately
after successful work, one managed VM per retained profile may remain until its
recorded hourly boundary.
### End-to-end acceptance (Task 9)
Trigger `.gitea/workflows/runner-nix-smoke.yaml` via workflow_dispatch, then:
```sh
watch_labels() { hcloud server list -o json | jq '[.[] | select(.labels["gitea-runner-controller"]=="managed") | {id,name,labels}]'; }
watch_labels # exactly one VM while queued/running
journalctl -f -u gitea-runner-controller # vm-created / vm-destroyed events
watch_labels # VM may remain until next hourly boundary
curl -fsS -H "Authorization: token $ADMIN" \
https://gitea.hectic-lab.com/api/v1/orgs/hectic-lab/actions/runners \
| jq '[.entries[] | select(.name | startswith("gcr-"))] | length' # may remain during retained slot
```
Failure paths to verify identically: duplicate delivery (send same webhook twice
via Gitea UI "Test delivery"), cancelled job, unknown-label job.
### Rollback
K8s rollback pool now defaults to deleted state:
- `infra/gitea-runners/k8s/statefulset.yaml` keeps `replicas: 0`
- old kube-hetzner nodes may be deleted to preserve zero idle cost
- PVCs and IaC remain for manual rollback only
Re-enable sequence:
```sh
# 1. edit nixos/system/hectic-lab/hectic-lab.nix and set
# services.gitea-runner-controller.enable = false, then rebuild:
nixos-rebuild --target root@128.140.75.58 switch
# 2. reprovision old kube-hetzner nodes when they were deleted:
tofu -chdir=infra/gitea-runners/opentofu apply
# 3. while controller is disabled, destroy every surviving managed VM and
# verify no gcr-* runner registration remains online:
hcloud server list -o json \
| jq -r '.[] | select(.labels["gitea-runner-controller"]=="managed") | .id' \
| xargs -r -n1 hcloud server delete
# 4. restore kubeconfig / cluster access, restore `ubuntu-latest` in the
# ConfigMap labels, then re-enable K8s runner pool. The legacy image does not
# provide `nix`; do not dispatch Nix workflows until a Nix-capable K8s image
# and label mapping are restored:
kubectl -n gitea-runners edit configmap/gitea-runner-config
kubectl -n gitea-runners scale statefulset/gitea-runner --replicas=5
kubectl -n gitea-runners rollout status statefulset/gitea-runner --timeout=10m
```
Any managed VM or `gcr-*` registration found after step 3 must be removed before
restoring persistent labels; otherwise both pools can claim the same job.
+1 -1
View File
@@ -126,7 +126,7 @@ in {
else throw (envErrorMessage varName);
# -- Cargo.toml --
cargoToml = src: (builtins.fromTOML (builtins.readFile "${src}/Cargo.toml"));
cargoToml = manifest: (builtins.fromTOML (builtins.readFile manifest));
# Consolidated SQL bundles for the `hectic` schema. Single source of truth
# for everything that creates objects in the `hectic` namespace, used by
@@ -0,0 +1,56 @@
{ ... }:
{ config, lib, pkgs, ... }:
let
cfg = config.services.minecraft-public-relay;
in {
options.services.minecraft-public-relay = {
enable = lib.mkEnableOption "restricted SSH relay for Minecraft";
publicPort = lib.mkOption { type = lib.types.port; default = 25568; };
tunnelPort = lib.mkOption { type = lib.types.port; default = 25577; };
publicKey = lib.mkOption {
type = lib.types.str;
description = "Public SSH key of the Minecraft tunnel client";
};
};
config = lib.mkIf cfg.enable {
networking.firewall.allowedTCPPorts = [ cfg.publicPort ];
users.groups.mc-wow-relay = { };
users.users.mc-wow-relay = {
isSystemUser = true;
group = "mc-wow-relay";
openssh.authorizedKeys.keys = [
"restrict,port-forwarding,permitlisten=\"127.0.0.1:${toString cfg.tunnelPort}\" ${cfg.publicKey}"
];
};
services.openssh.extraConfig = ''
Match User mc-wow-relay
ClientAliveInterval 15
ClientAliveCountMax 3
AllowTcpForwarding remote
PermitListen 127.0.0.1:${toString cfg.tunnelPort}
AllowAgentForwarding no
X11Forwarding no
PermitTTY no
ForceCommand ${pkgs.coreutils}/bin/false
Match all
'';
systemd.sockets.minecraft-wow-proxy = {
description = "WorldOfSosal WoW public Minecraft port";
wantedBy = [ "sockets.target" ];
listenStreams = [ "0.0.0.0:${toString cfg.publicPort}" ];
};
systemd.services.minecraft-wow-proxy = {
description = "Forward Minecraft to the neuro reverse tunnel";
requires = [ "minecraft-wow-proxy.socket" ];
after = [ "minecraft-wow-proxy.socket" ];
serviceConfig = {
ExecStart = "${pkgs.systemd}/lib/systemd/systemd-socket-proxyd 127.0.0.1:${toString cfg.tunnelPort}";
DynamicUser = true;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
};
};
};
}
@@ -132,7 +132,11 @@ in {
"${cfg.ipv6}::/64"
] ++ lib.optional (cfg.floatingIpv4 != null) "${cfg.floatingIpv4}/32";
routes = [
{ Gateway = "172.31.1.1"; GatewayOnLink = true; }
{
Gateway = "172.31.1.1";
GatewayOnLink = true;
PreferredSource = cfg.ipv4;
}
{ Gateway = "fe80::1"; }
];
};
+1 -30
View File
@@ -25,36 +25,7 @@ in {
programs.bash.shellAliases.tmux = "tmux a";
home-manager.sharedModules = [
{
programs.tmux = {
enable = true;
plugins = with pkgs.tmuxPlugins; [ resurrect continuum ];
keyMode = "vi";
escapeTime = 500;
historyLimit = 50000;
newSession = true;
extraConfig = ''
# resurrect
set -g @resurrect-strategy-vim 'session'
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-capture-pane-contents 'on'
resurrect_dir="$HOME/.tmux/resurrect"
set -g @resurrect-dir $resurrect_dir
set -g @resurrect-hook-post-save-all 'target=$(readlink -f $resurrect_dir/last); sed "s| --cmd .*-vim-pack-dir||g; s|/etc/profiles/per-user/$USER/bin/||g; s|/home/$USER/.nix-profile/bin/||g" $target | sponge $target'
# continuum
set -g @continuum-restore 'on'
set -g @continuum-boot 'on'
set -g @continuum-save-interval '10'
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi C-v send-keys -X rectangle-toggle
bind-key O select-pane -t :.-
'';
};
}
(flake + "/home/module/program/tmux.nix")
];
home-manager.users.root.home.stateVersion = lib.mkDefault "25.05";
+101
View File
@@ -0,0 +1,101 @@
{ ... }: {
lib,
config,
pkgs,
...
}: let
cfg = config.hectic.services.dify;
difySource = pkgs.fetchFromGitHub {
owner = "langgenius";
repo = "dify";
rev = "00e578606715a9da34488608edee8c68d4ef4893";
hash = "sha256-kLxMdmt1FtOl39C9SS7ZGY6C78e3hPiVI5Q3EdbkMPU=";
};
composeOverride = pkgs.writeText "dify-compose.override.yaml" ''
services:
nginx:
ports: !override
- "127.0.0.1:${toString cfg.port}:80"
plugin_daemon:
ports: !override
- "127.0.0.1:${toString cfg.pluginPort}:5003"
environment:
DB_USERNAME: ''${DB_USERNAME:-postgres}
DB_HOST: ''${DB_HOST:-db_postgres}
DB_PORT: ''${DB_PORT:-5432}
REDIS_HOST: ''${REDIS_HOST:-redis}
REDIS_PORT: ''${REDIS_PORT:-6379}
REDIS_DB: ''${REDIS_DB:-0}
'';
in {
options.hectic.services.dify = {
enable = lib.mkEnableOption "Dify self-hosted AI platform";
dataDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/dify";
description = "Persistent directory for Dify compose state and volumes.";
};
environmentFile = lib.mkOption {
type = lib.types.path;
description = ''
Environment file for Dify. Keep secrets here, including SECRET_KEY,
DB_PASSWORD, REDIS_PASSWORD, and plugin daemon credentials.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 80;
description = "Loopback HTTP port forwarded to Dify through SSH.";
};
pluginPort = lib.mkOption {
type = lib.types.port;
default = 5003;
description = "Loopback plugin daemon port forwarded through SSH when needed.";
};
composeProfiles = lib.mkOption {
type = lib.types.str;
default = "weaviate,postgresql,collaboration";
description = "Dify Docker Compose profiles to start.";
};
};
config = lib.mkIf cfg.enable {
virtualisation.docker.enable = true;
systemd.services.dify = {
description = "Dify Docker Compose stack";
wantedBy = [ "multi-user.target" ];
wants = [ "docker.service" ];
after = [ "docker.service" ];
requires = [ "docker.service" ];
restartIfChanged = true;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
WorkingDirectory = cfg.dataDir;
ExecStartPre = pkgs.writeShellScript "dify-prepare" ''
set -eu
install -d -m 0750 ${lib.escapeShellArg cfg.dataDir}
cp -R ${difySource}/docker/. ${lib.escapeShellArg cfg.dataDir}/
install -m 0600 ${lib.escapeShellArg cfg.environmentFile} ${lib.escapeShellArg cfg.dataDir}/.env
'';
ExecStart = "${pkgs.docker-compose}/bin/docker-compose --project-directory ${cfg.dataDir} --file ${cfg.dataDir}/docker-compose.yaml --file ${composeOverride} --env-file ${cfg.dataDir}/.env up --detach";
ExecStop = "${pkgs.docker-compose}/bin/docker-compose --project-directory ${cfg.dataDir} --file ${cfg.dataDir}/docker-compose.yaml --file ${composeOverride} --env-file ${cfg.dataDir}/.env down";
};
environment = {
COMPOSE_PROFILES = cfg.composeProfiles;
};
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 root root -"
];
};
}
@@ -0,0 +1,267 @@
{
inputs,
flake,
self,
}:
{
pkgs,
lib,
config,
...
}:
let
system = pkgs.stdenv.hostPlatform.system;
cfg = config.hectic.services.gitea-runner-controller;
secretPrefix = "gitea-runner-controller";
mkControllerSecret = name: {
name = "${secretPrefix}/${name}";
value = {
sopsFile = flake + "/sus/gitea-runners.yaml";
key = "gitea/hectic-lab/controller/${name}";
};
};
controllerSecrets = builtins.listToAttrs (map mkControllerSecret [
"hcloud-token"
"webhook-secret"
"admin-token"
"ssh-private-key"
]);
# Registration token is shared with the existing K8s/local runner setup.
registrationTokenPath = config.sops.secrets."gitea-runner/org-registration-token".path;
commonEnvironment =
[
"GCR_STATE_DIR=/var/lib/gitea-runner-controller"
"GCR_GITEA_URL=${cfg.giteaBaseUrl}"
"GCR_ALLOWED_REPOS=${lib.concatStringsSep "," cfg.allowedRepos}"
"GCR_CONCURRENCY_CAP=${toString cfg.concurrencyCap}"
"GCR_PER_REPO_CAP=${toString cfg.perRepoCap}"
"GCR_RECONCILE_INTERVAL_SEC=${toString cfg.reconcileIntervalSec}"
"GCR_BUDGET_EUR_MONTHLY=${cfg.budgetEurMonthly}"
"GCR_HETZNER_LOCATION=${cfg.hetznerLocation}"
"HCLOUD_TOKEN_FILE=${config.sops.secrets."${secretPrefix}/hcloud-token".path}"
"GITEA_WEBHOOK_SECRET_FILE=${config.sops.secrets."${secretPrefix}/webhook-secret".path}"
"GITEA_REGISTRATION_TOKEN_FILE=${registrationTokenPath}"
"GITEA_ADMIN_TOKEN_FILE=${config.sops.secrets."${secretPrefix}/admin-token".path}"
"GCR_SSH_PRIVKEY_FILE=${config.sops.secrets."${secretPrefix}/ssh-private-key".path}"
"GCR_HCLOUD_SSH_KEY_ID=${toString cfg.hcloudSshKeyId}"
"GCR_NIX_VERSION=${cfg.nixVersion}"
"GCR_NIX_TARBALL_SHA256=${cfg.nixTarballSha256}"
"GCR_ARM_NIX_TARBALL_SHA256=${cfg.armNixTarballSha256}"
"GCR_ACT_RUNNER_VERSION=${cfg.actRunnerVersion}"
"GCR_ACT_RUNNER_SHA256=${cfg.actRunnerSha256}"
]
++ lib.optional (cfg.debugSshPublicKey != null) "\"GCR_DEBUG_SSH_PUBKEY=${cfg.debugSshPublicKey}\""
++ lib.optionals (cfg.imageId != null) [ "GCR_IMAGE_ID=${cfg.imageId}" ]
++ lib.optionals (cfg.armImageId != null) [ "GCR_ARM_IMAGE_ID=${cfg.armImageId}" ]
++ lib.optionals (cfg.nixImageId != null) [ "GCR_NIX_IMAGE_ID=${cfg.nixImageId}" ]
++ lib.optionals (cfg.armNixImageId != null) [ "GCR_ARM_NIX_IMAGE_ID=${cfg.armNixImageId}" ];
in
{
options = {
hectic.services.gitea-runner-controller = {
enable = lib.mkEnableOption "gitea-runner-controller — ephemeral Hetzner VM runner controller";
listenAddr = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Address the webhook listener binds to.";
};
listenPort = lib.mkOption {
type = lib.types.port;
default = 8787;
description = "Port the webhook listener binds to.";
};
webhookHost = lib.mkOption {
type = lib.types.str;
default = "runners.hectic-lab.com";
description = "Public vhost Gitea delivers webhooks to. Requires a DNS A record to this host.";
};
giteaBaseUrl = lib.mkOption {
type = lib.types.str;
default = "https://gitea.hectic-lab.com";
description = "Public Gitea URL runners register against.";
};
allowedRepos = lib.mkOption {
type = with lib.types; listOf str;
default = [ "hectic-lab/util.nix" ];
description = "Repos whose workflow_job events may trigger VM creation.";
};
concurrencyCap = lib.mkOption {
type = lib.types.int;
default = 2;
description = "Maximum simultaneously assigned runner VMs (global); retained idle VMs do not count.";
};
perRepoCap = lib.mkOption {
type = lib.types.int;
default = 1;
description = "Maximum concurrently assigned runner VMs per repo; retained idle VMs do not count.";
};
reconcileIntervalSec = lib.mkOption {
type = lib.types.int;
default = 60;
description = "Seconds between reconciliation ticks.";
};
budgetEurMonthly = lib.mkOption {
type = lib.types.str;
default = "15";
description = "Soft monthly EUR ceiling for estimated VM spend.";
};
hetznerLocation = lib.mkOption {
type = lib.types.str;
default = "nbg1";
description = "Hetzner location for ephemeral VMs.";
};
imageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "174108912";
description = ''
Hetzner image/snapshot id for ephemeral VMs (MicroOS base from
gitea-runners-build-microos-snapshots). Controller refuses VM
creation while null.
'';
};
armImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "423979717";
description = ''
Hetzner ARM image/snapshot id for ephemeral VMs. Required for labels
whose fallback chain includes ARM server types.
'';
};
nixImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "161547269";
description = "Hetzner Ubuntu image id used by Nix-capable x86 runners.";
};
armNixImageId = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
example = "161547270";
description = "Hetzner Ubuntu image id used by Nix-capable ARM runners.";
};
actRunnerVersion = lib.mkOption {
type = lib.types.str;
default = "1.0.6";
description = "gitea-runner release version downloaded at VM bootstrap.";
};
actRunnerSha256 = lib.mkOption {
type = lib.types.str;
default = "d78ac11deed6580a2d88c1ef72c522aa7e2986d2d22b0d80edbee577b8f79b20";
description = "sha256 of the pinned gitea-runner linux-amd64 binary, verified at bootstrap.";
};
nixVersion = lib.mkOption {
type = lib.types.str;
default = "2.35.0";
description = "Nix release installed from the official static tarball at bootstrap.";
};
nixTarballSha256 = lib.mkOption {
type = lib.types.str;
default = "e828c574555f235f2ca47c4a1432f8a07905d5cf59f087e9581be56c238818db";
description = "sha256 of the pinned Nix x86_64-linux tarball, verified at bootstrap.";
};
armNixTarballSha256 = lib.mkOption {
type = lib.types.str;
default = "1916bd42cfd4a65d5642a4ca75be4fe55db0a67e5fa16e18808fb5b6d2365bf8";
description = "sha256 of the pinned Nix aarch64-linux tarball, verified at bootstrap.";
};
debugSshPublicKey = lib.mkOption {
type = with lib.types; nullOr str;
default = null;
description = ''
Injected into every ephemeral VM (project ssh-key "yukkop@nixos"
carries the matching public key; this value is informational and
used by gcr_bootstrap_script documentation).
'';
};
hcloudSshKeyId = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
description = "Hetzner project SSH key ID injected into ephemeral VMs at creation.";
};
bootstrapSshPrivateKeyFile = lib.mkOption {
type = lib.types.path;
description = ''
Path (sops-rendered) to the SSH private key the controller uses to
push bootstrap into ephemeral VMs. Public half must be registered
as Hetzner project ssh-key "yukkop@nixos".
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.imageId != null;
message = "gitea-runner-controller: imageId must be set to a MicroOS snapshot id before enabling";
}
];
sops.secrets = controllerSecrets;
systemd.services.gitea-runner-controller = {
description = "Gitea ephemeral runner controller — reconcile loop";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "simple";
ExecStart = "${self.packages.${system}.gitea-runner-controller}/bin/gitea-runner-controller";
Restart = "always";
RestartSec = "5s";
StateDirectory = "gitea-runner-controller";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
StandardOutput = "journal";
StandardError = "journal";
Environment = commonEnvironment;
};
};
systemd.services.gitea-runner-webhook = {
description = "Gitea ephemeral runner webhook receiver";
after = [
"network.target"
"gitea-runner-controller.service"
];
wantedBy = [ "multi-user.target" ];
partOf = [ "gitea-runner-controller.service" ];
serviceConfig = {
Type = "simple";
ExecStart = "${self.packages.${system}.gitea-runner-controller}/bin/gitea-runner-webhook";
Restart = "always";
RestartSec = "2s";
StateDirectory = "gitea-runner-controller";
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
StandardOutput = "journal";
StandardError = "journal";
Environment = commonEnvironment ++ [
"GCR_LISTEN_ADDR=${cfg.listenAddr}"
"GCR_LISTEN_PORT=${toString cfg.listenPort}"
];
};
};
services.nginx.virtualHosts."${cfg.webhookHost}" = {
enableACME = true;
forceSSL = true;
locations."/" = {
extraConfig = ''
proxy_pass http://${cfg.listenAddr}:${toString cfg.listenPort};
proxy_read_timeout 30s;
'';
};
};
};
}
+168
View File
@@ -0,0 +1,168 @@
{ ... }:
{
lib,
config,
...
}:
let
cfg = config.hectic.services.immich;
in
{
options.hectic.services.immich = {
enable = lib.mkEnableOption "Immich self-hosted photo and video service";
domain = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9.-]*";
description = "Public hostname used to reach Immich.";
};
mediaLocation = lib.mkOption {
type = lib.types.path;
default = "/var/lib/immich";
description = ''
Local filesystem path used for Immich media. Upstream Immich does not
support S3 as its media backend; use a local disk or block volume here.
'';
};
maxUploadSize = lib.mkOption {
type = lib.types.strMatching "[1-9][0-9]*[KMG]?";
default = "10G";
description = "Maximum request body accepted by nginx in front of Immich.";
};
secretsFile = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "/[^[:space:]]+");
default = null;
description = ''
SOPS-backed environment file passed to Immich. Use this for secrets
such as DB_PASSWORD; never put secret values in Nix configuration.
'';
};
machineLearning = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to enable Immich machine-learning features.";
};
};
accelerationDevices = lib.mkOption {
type = lib.types.nullOr (lib.types.listOf lib.types.str);
default = [ ];
description = "Device paths exposed to Immich for hardware acceleration.";
};
storageBox = {
enable = lib.mkEnableOption "Hetzner Storage Box media storage";
host = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9.-]*";
default = "u666713-sub1.your-storagebox.de";
description = "Hetzner Storage Box SMB hostname.";
};
username = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_-]*";
default = "u666713-sub1";
description = "Storage Box SMB username.";
};
share = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_-]*";
default = "u666713-sub1";
description = "SMB share exported by Storage Box.";
};
subdirectory = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "[A-Za-z0-9][A-Za-z0-9_./-]*");
default = null;
description = "Directory within the SMB share used by Immich.";
};
credentialsFile = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "/[^[:space:]]+");
default = null;
description = ''
Runtime file containing the SMB password. Keep this in a SOPS
secret, outside the Nix store.
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.secretsFile == null || !lib.hasPrefix "/nix/store/" cfg.secretsFile;
message = "hectic.services.immich.secretsFile must reference a runtime secret path, not /nix/store.";
}
{
assertion = !cfg.storageBox.enable || cfg.storageBox.credentialsFile != null;
message = "hectic.services.immich.storageBox.credentialsFile is required when Storage Box is enabled.";
}
{
assertion =
!cfg.storageBox.enable
|| cfg.storageBox.credentialsFile == null
|| !lib.hasPrefix "/nix/store/" cfg.storageBox.credentialsFile;
message = "hectic.services.immich.storageBox.credentialsFile must reference a runtime secret path, not /nix/store.";
}
];
services.immich = {
enable = true;
host = "127.0.0.1";
mediaLocation = cfg.mediaLocation;
secretsFile = cfg.secretsFile;
accelerationDevices = cfg.accelerationDevices;
machine-learning.enable = cfg.machineLearning.enable;
settings.server.externalDomain = "https://${cfg.domain}";
};
services.nginx = {
enable = true;
virtualHosts.${cfg.domain} = {
enableACME = true;
forceSSL = true;
extraConfig = lib.mkForce ''
client_max_body_size ${cfg.maxUploadSize};
'';
locations."/" = {
proxyPass = "http://127.0.0.1:${toString config.services.immich.port}";
proxyWebsockets = true;
extraConfig = ''
proxy_read_timeout 600s;
proxy_send_timeout 600s;
'';
};
};
};
fileSystems.${toString cfg.mediaLocation} = lib.mkIf cfg.storageBox.enable {
device = "//${cfg.storageBox.host}/${cfg.storageBox.share}";
fsType = "cifs";
options = [
"_netdev"
"nofail"
"x-systemd.mount-timeout=60s"
"vers=3.1.1"
"seal"
"cache=none"
"credentials=${cfg.storageBox.credentialsFile}"
"username=${cfg.storageBox.username}"
"uid=${config.services.immich.user}"
"gid=${config.services.immich.group}"
"file_mode=0660"
"dir_mode=0770"
] ++ lib.optional (cfg.storageBox.subdirectory != null)
"prefixpath=${cfg.storageBox.subdirectory}";
};
systemd.services.immich-server.unitConfig.RequiresMountsFor = lib.mkIf cfg.storageBox.enable [
cfg.mediaLocation
];
systemd.services.immich-server.serviceConfig.Restart = lib.mkForce "always";
};
}
+356
View File
@@ -0,0 +1,356 @@
{ ... }:
{
pkgs,
lib,
config,
...
}: let
cfg = config.hectic.services.p4d;
boolString = value: if value then "1" else "0";
serviceUser = cfg.user;
serviceGroup = cfg.group;
packageExe = if cfg.package != null then "${cfg.package}/bin/p4d" else "/run/current-system/sw/bin/false";
clientExe = if cfg.clientPackage != null then "${cfg.clientPackage}/bin/p4" else "/run/current-system/sw/bin/false";
journalFile = "${cfg.journalDir}/journal";
logFile = "${cfg.dataDir}/logs/p4d.log";
sslPort = if cfg.ssl.enable then "ssl:${cfg.listenAddress}:${toString cfg.port}" else "${cfg.listenAddress}:${toString cfg.port}";
bootstrapPort = "${cfg.bootstrap.listenAddress}:${toString cfg.bootstrap.port}";
typemapLines = [
"binary+l //....uasset"
"binary+l //....umap"
"binary+l //....upk"
"binary+l //....udk"
"binary+l //....ubulk"
"binary+l //....uexp"
"binary+l //....utoc"
"binary+l //....ucas"
"binary+w //....exe"
"binary+w //....dll"
"binary+w //....lib"
"binary+w //....app"
"binary+w //....dylib"
"binary+w //....stub"
"binary+w //....ipa"
"binary+w //....pdb"
] ++ cfg.typemap.extraLines;
typemapSpec = pkgs.writeText "p4d-unreal-typemap.txt" (
lib.concatStringsSep "\n" ([ "Typemap:" ] ++ map (line: "\t${line}") typemapLines) + "\n"
);
mainArgs = [
"-r" cfg.dataDir
"-p" sslPort
"-J" journalFile
"-L" logFile
] ++ lib.optional (!cfg.caseSensitive) "-C1";
bootstrapArgs = [
"-r" cfg.dataDir
"-p" bootstrapPort
"-J" journalFile
"-L" "${cfg.dataDir}/logs/bootstrap.log"
] ++ lib.optional (!cfg.caseSensitive) "-C1";
initScript = ''
set -eu
export P4ROOT=${lib.escapeShellArg cfg.dataDir}
export P4JOURNAL=${lib.escapeShellArg journalFile}
export P4SSLDIR=${lib.escapeShellArg cfg.ssl.dir}
marker_file="$P4ROOT/.hectic-p4d-initialized"
typemap_target="$P4ROOT/unreal-engine.typemap"
server_id_file="$P4ROOT/server.id"
${pkgs.coreutils}/bin/install -d -m 0750 "$P4ROOT"
${pkgs.coreutils}/bin/install -d -m 0750 ${lib.escapeShellArg cfg.journalDir}
${pkgs.coreutils}/bin/install -d -m 0750 ${lib.escapeShellArg cfg.checkpointDir}
${pkgs.coreutils}/bin/install -d -m 0750 "$P4ROOT/logs"
${pkgs.coreutils}/bin/install -d -m 0700 ${lib.escapeShellArg cfg.ssl.dir}
if [ ! -f "$server_id_file" ]; then
umask 077
${pkgs.coreutils}/bin/printf '%s\n' ${lib.escapeShellArg cfg.serverId} > "$server_id_file"
fi
if [ "${boolString cfg.typemap.enable}" = "1" ]; then
${pkgs.coreutils}/bin/install -m 0640 ${lib.escapeShellArg typemapSpec} "$typemap_target"
fi
if [ "${boolString cfg.ssl.enable}" = "1" ] && {
[ ! -f "$P4SSLDIR/privatekey.txt" ] || [ ! -f "$P4SSLDIR/certificate.txt" ];
}; then
${packageExe} -r "$P4ROOT" -Gc
fi
if [ ! -f "$marker_file" ] && [ "${boolString cfg.unicode}" = "1" ] && [ ! -e "$P4ROOT/db.counters" ]; then
${packageExe} ${lib.escapeShellArgs ([ "-r" cfg.dataDir ] ++ lib.optional (!cfg.caseSensitive) "-C1" ++ [ "-xi" ])}
fi
if [ ! -f "$marker_file" ] && [ "${boolString cfg.bootstrap.enable}" = "1" ]; then
temp_pid_file="$P4ROOT/bootstrap.pid"
cleanup() {
if [ -f "$temp_pid_file" ]; then
pid=$(cat "$temp_pid_file")
kill "$pid" 2>/dev/null || true
wait "$pid" 2>/dev/null || true
rm -f "$temp_pid_file"
fi
}
trap cleanup EXIT INT TERM
${packageExe} ${lib.escapeShellArgs bootstrapArgs} &
pid=$!
${pkgs.coreutils}/bin/printf '%s\n' "$pid" > "$temp_pid_file"
ready=0
tries=0
while [ "$tries" -lt 30 ]; do
if ${clientExe} -p ${lib.escapeShellArg bootstrapPort} info >/dev/null 2>&1; then
ready=1
break
fi
tries=$((tries + 1))
sleep 1
done
if [ "$ready" -ne 1 ]; then
printf 'p4d bootstrap server failed to become ready on %s\n' ${lib.escapeShellArg bootstrapPort} >&2
exit 1
fi
${lib.optionalString (cfg.securityLevel != null) ''
${clientExe} -p ${lib.escapeShellArg bootstrapPort} configure set security=${toString cfg.securityLevel}
''}
if [ "${boolString cfg.typemap.enable}" = "1" ]; then
${clientExe} -p ${lib.escapeShellArg bootstrapPort} typemap -i < "$typemap_target"
fi
${clientExe} -p ${lib.escapeShellArg bootstrapPort} admin stop || true
wait "$pid" 2>/dev/null || true
rm -f "$temp_pid_file"
trap - EXIT INT TERM
fi
if [ ! -f "$marker_file" ]; then
: > "$marker_file"
fi
'';
in {
options.hectic.services.p4d = {
enable = lib.mkEnableOption "Perforce Helix Core p4d server";
package = lib.mkOption {
type = with lib.types; nullOr package;
default = null;
defaultText = lib.literalExpression "pkgs.p4d";
description = ''
Package providing the `p4d` executable. Left null by default because
nixpkgs marks Perforce packages unfree.
'';
};
clientPackage = lib.mkOption {
type = with lib.types; nullOr package;
default = null;
defaultText = lib.literalExpression "pkgs.p4";
description = ''
Package providing the `p4` client executable used for optional local
bootstrap tasks like typemap installation and security configuration.
'';
};
user = lib.mkOption {
type = lib.types.str;
default = "p4d";
description = "System user running the p4d service.";
};
group = lib.mkOption {
type = lib.types.str;
default = "p4d";
description = "System group running the p4d service.";
};
dataDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d";
description = "Persistent P4ROOT directory for metadata and archives.";
};
journalDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/journal";
description = "Directory storing the live journal file.";
};
checkpointDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/checkpoints";
description = "Directory reserved for checkpoints and offline backups.";
};
listenAddress = lib.mkOption {
type = lib.types.str;
default = "0.0.0.0";
description = "Address p4d listens on for normal client traffic.";
};
port = lib.mkOption {
type = lib.types.port;
default = 1666;
description = "TCP port exposed by p4d.";
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to open the p4d TCP port in the firewall.";
};
serverId = lib.mkOption {
type = lib.types.str;
default = "master";
description = "Perforce server identifier written to P4ROOT/server.id.";
};
unicode = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Initialize Unicode mode on first boot. Irreversible after init.";
};
caseSensitive = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether the server remains case-sensitive. Linux default stays true.
Set false only when tooling requires case-insensitive behavior.
'';
};
securityLevel = lib.mkOption {
type = with lib.types; nullOr (ints.between 0 5);
default = 4;
description = ''
Optional `p4 configure set security=<level>` value applied during local
bootstrap. Set null to skip automatic security tuning.
'';
};
ssl = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether p4d listens with SSL enabled.";
};
dir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/p4d/ssl";
description = "Directory holding p4d SSL certificate and key material.";
};
};
bootstrap = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run one-time local bootstrap tasks on first start: optional security
level configuration and Unreal typemap installation.
'';
};
listenAddress = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Loopback address used by the local temporary bootstrap server.";
};
port = lib.mkOption {
type = lib.types.port;
default = 1667;
description = "Loopback-only port used by the temporary bootstrap server.";
};
};
typemap = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Generate the Unreal-focused typemap spec and optionally install it
during bootstrap.
'';
};
extraLines = lib.mkOption {
type = with lib.types; listOf str;
default = [ ];
description = "Extra lines appended to the generated Perforce typemap spec.";
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.package != null;
message = "hectic.services.p4d.package must be set, for example pkgs.p4d.";
}
{
assertion = !cfg.bootstrap.enable || cfg.clientPackage != null;
message = "hectic.services.p4d.clientPackage must be set when bootstrap.enable is true.";
}
];
users.groups.${serviceGroup} = { };
users.users.${serviceUser} = {
isSystemUser = true;
group = serviceGroup;
home = cfg.dataDir;
createHome = true;
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.journalDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.checkpointDir} 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.dataDir}/logs 0750 ${serviceUser} ${serviceGroup} - -"
"d ${cfg.ssl.dir} 0700 ${serviceUser} ${serviceGroup} - -"
];
systemd.services.p4d = {
description = "Perforce Helix Core p4d server";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
preStart = initScript;
serviceConfig = {
Type = "simple";
User = serviceUser;
Group = serviceGroup;
WorkingDirectory = cfg.dataDir;
Environment = lib.mkIf cfg.ssl.enable "P4SSLDIR=${cfg.ssl.dir}";
ExecStart = "${packageExe} ${lib.escapeShellArgs mainArgs}";
Restart = "on-failure";
RestartSec = "5s";
TimeoutStopSec = "30s";
KillSignal = "SIGTERM";
KillMode = "mixed";
UMask = "0077";
};
};
networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ cfg.port ];
};
}
@@ -0,0 +1,615 @@
{ ... }:
{
pkgs,
lib,
config,
...
}: let
cfg = config.hectic.services."project-zomboid";
serverProperties = cfg.serverProperties // {
DefaultPort = cfg.port;
UDPPort = cfg.udpPort;
WorkshopItems = lib.concatStringsSep ";" cfg.workshopItems;
Mods = lib.concatStringsSep ";" cfg.mods;
};
configLines = lib.mapAttrsToList (
name: value:
"${name}=${if builtins.isBool value then lib.boolToString value else toString value}"
) serverProperties;
sandboxValueType = lib.types.oneOf [
lib.types.bool
lib.types.int
lib.types.float
lib.types.str
(lib.types.attrsOf sandboxValueType)
];
luaValue = value:
if builtins.isBool value then
lib.boolToString value
else if builtins.isInt value || builtins.isFloat value then
toString value
else if builtins.isAttrs value then
"{ ${lib.concatStringsSep " " (lib.mapAttrsToList (name: child: "[${luaValue name}] = ${luaValue child},") value)} }"
else
"\"${lib.replaceStrings [ "\\" "\"" "\n" "\r" ] [ "\\\\" "\\\"" "\\n" "\\r" ] value}\"";
sandboxConfigLines = lib.mapAttrsToList (
name: value: "[${luaValue name}] = ${luaValue value},"
) cfg.sandboxProperties;
zomboidDir = "${cfg.dataDir}/Zomboid";
adminPasswordFile = "${cfg.dataDir}/admin-password";
rconPasswordFile = cfg.rcon.passwordFile;
backupCfg = cfg.backup;
s3CredentialsFile = if backupCfg.s3.credentialsFile == null then "" else backupCfg.s3.credentialsFile;
s3Bucket = if backupCfg.s3.bucket == null then "" else backupCfg.s3.bucket;
s3Endpoint = if backupCfg.s3.endpoint == null then "" else backupCfg.s3.endpoint;
s3Region = if backupCfg.s3.region == null then "" else backupCfg.s3.region;
timestampArchivePattern = "project-zomboid-${cfg.serverName}-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z.tar.zst";
saveDir = "${zomboidDir}/Saves/Multiplayer/${cfg.serverName}";
serverConfigDir = "${zomboidDir}/Server";
backupScript = pkgs.writeShellScript "project-zomboid-backup" ''
set -eu
staging_dir=${lib.escapeShellArg backupCfg.stagingDir}
archive_dir=${lib.escapeShellArg backupCfg.archiveDir}
lock_file="$archive_dir/.backup.lock"
${pkgs.coreutils}/bin/install -d -m 0700 \
"$staging_dir/Zomboid/Saves/Multiplayer/${cfg.serverName}" \
"$staging_dir/Zomboid/Server" \
"$archive_dir"
exec 9>"$lock_file"
if ! ${pkgs.util-linux}/bin/flock -n 9; then
${pkgs.coreutils}/bin/printf '%s\n' 'Project Zomboid backup already running; skipping.' >&2
exit 0
fi
${lib.optionalString backupCfg.s3.enable ''
if [ -z "''${AWS_ACCESS_KEY_ID:-}" ] || [ -z "''${AWS_SECRET_ACCESS_KEY:-}" ]; then
${pkgs.coreutils}/bin/printf '%s\n' \
'AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY missing from Project Zomboid S3 credentials file.' >&2
exit 1
fi
s3_bucket=${lib.escapeShellArg s3Bucket}
s3_prefix=${lib.escapeShellArg backupCfg.s3.prefix}
s3_upload() {
source=$1
key=$2
attempt=1
while [ "$attempt" -le 3 ]; do
if ${pkgs.awscli2}/bin/aws s3 cp "$source" "s3://$s3_bucket/$key" \
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
--region ${lib.escapeShellArg s3Region} \
--cli-connect-timeout 30 \
--cli-read-timeout 300 \
--only-show-errors; then
return 0
fi
if [ "$attempt" -eq 3 ]; then
return 1
fi
${pkgs.coreutils}/bin/sleep 5
attempt=$((attempt + 1))
done
}
''}
${lib.optionalString (backupCfg.s3.enable && backupCfg.retentionDays == 0) ''
pending_list="$staging_dir/.pending-archives"
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-printf '%T@ %p\n' | ${pkgs.coreutils}/bin/sort -n > "$pending_list"
while IFS= read -r pending_line; do
pending_archive="''${pending_line#* }"
pending_name="''${pending_archive##*/}"
s3_upload "$pending_archive" "''${s3_prefix:+$s3_prefix/}$pending_name"
${pkgs.coreutils}/bin/rm -f "$pending_archive"
done < "$pending_list"
${pkgs.coreutils}/bin/rm -f "$pending_list"
''}
${lib.optionalString cfg.rcon.enable ''
rcon_password="$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile})"
if [ -z "$rcon_password" ]; then
${pkgs.coreutils}/bin/printf '%s\n' 'Project Zomboid RCON password file is empty.' >&2
exit 1
fi
${pkgs.rcon}/bin/rcon \
--host 127.0.0.1 \
--port ${toString cfg.rcon.port} \
--password "$rcon_password" \
save
${pkgs.coreutils}/bin/sleep ${toString backupCfg.saveWaitSeconds}
''}
sync_staging() {
${pkgs.rsync}/bin/rsync -a --delete \
${lib.escapeShellArg "${saveDir}/"} \
"$staging_dir/Zomboid/Saves/Multiplayer/${cfg.serverName}/"
${pkgs.rsync}/bin/rsync -a --delete --delete-excluded \
--include=${lib.escapeShellArg "/${cfg.serverName}_SandboxVars.lua"} \
--include=${lib.escapeShellArg "/${cfg.serverName}_spawnpoints.lua"} \
--include=${lib.escapeShellArg "/${cfg.serverName}_spawnregions.lua"} \
--exclude='*' \
${lib.escapeShellArg "${serverConfigDir}/"} \
"$staging_dir/Zomboid/Server/"
}
# Second pass narrows, but cannot eliminate, live-save inconsistency.
sync_staging
${pkgs.coreutils}/bin/sleep 5
sync_staging
timestamp="$(${pkgs.coreutils}/bin/date -u +%Y%m%dT%H%M%SZ)"
archive_name="project-zomboid-${cfg.serverName}-$timestamp.tar.zst"
archive_tmp="$archive_dir/.$archive_name.tmp"
archive="$archive_dir/$archive_name"
trap '${pkgs.coreutils}/bin/rm -f "$archive_tmp"' EXIT
${pkgs.gnutar}/bin/tar \
--use-compress-program=${lib.escapeShellArg "${pkgs.zstd}/bin/zstd -T0"} \
-C "$staging_dir" -cf "$archive_tmp" Zomboid
${pkgs.coreutils}/bin/chmod 0600 "$archive_tmp"
${pkgs.coreutils}/bin/mv "$archive_tmp" "$archive"
trap - EXIT
${lib.optionalString backupCfg.s3.enable ''
s3_key="''${s3_prefix:+$s3_prefix/}$archive_name"
s3_upload "$archive" "$s3_key"
${lib.optionalString (backupCfg.retentionDays == 0) ''
${pkgs.coreutils}/bin/rm -f "$archive"
''}
${lib.optionalString (backupCfg.retentionDays != 0) ''
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-mmin +${toString (backupCfg.retentionDays * 1440)} -delete
''}
remote_prefix="$s3_prefix"
if [ -n "$remote_prefix" ]; then
remote_prefix="$remote_prefix/"
fi
archive_prefix=${lib.escapeShellArg "project-zomboid-${cfg.serverName}-"}
remote_list="$staging_dir/.remote-objects.json"
remote_delete_dir="$staging_dir/.remote-delete"
${pkgs.awscli2}/bin/aws s3api list-objects-v2 \
--bucket "$s3_bucket" \
--prefix "$remote_prefix" \
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
--region ${lib.escapeShellArg s3Region} \
--output json > "$remote_list"
${pkgs.python3}/bin/python3 - "$remote_list" "$remote_delete_dir" \
"$(( $(${pkgs.coreutils}/bin/date +%s) - ${toString (backupCfg.s3.remoteRetentionDays * 86400)} ))" \
"$remote_prefix$archive_prefix" <<'PY'
import datetime
import json
import os
import re
import sys
objects_path, delete_dir, cutoff, key_prefix = sys.argv[1:]
cutoff = int(cutoff)
archive_pattern = re.compile(
re.escape(key_prefix) + r"\d{8}T\d{6}Z\.tar\.zst\Z"
)
with open(objects_path, encoding="utf-8") as stream:
objects = json.load(stream).get("Contents", [])
old_keys = []
for item in objects:
key = item.get("Key", "")
if not archive_pattern.fullmatch(key):
continue
modified = datetime.datetime.fromisoformat(
item["LastModified"].replace("Z", "+00:00")
)
if int(modified.timestamp()) < cutoff:
old_keys.append(key)
os.makedirs(delete_dir, exist_ok=True)
for batch_number in range(0, len(old_keys), 1000):
batch = old_keys[batch_number:batch_number + 1000]
manifest_path = os.path.join(
delete_dir, f"batch-{batch_number // 1000:04d}.json"
)
with open(manifest_path, "w", encoding="utf-8") as stream:
json.dump(
{"Objects": [{"Key": key} for key in batch], "Quiet": True},
stream,
)
PY
for remote_manifest in "$remote_delete_dir"/*.json; do
[ -f "$remote_manifest" ] || continue
${pkgs.awscli2}/bin/aws s3api delete-objects \
--bucket "$s3_bucket" \
--delete "file://$remote_manifest" \
--endpoint-url ${lib.escapeShellArg s3Endpoint} \
--region ${lib.escapeShellArg s3Region} \
--only-show-errors
done
${pkgs.coreutils}/bin/rm -rf "$remote_list" "$remote_delete_dir"
''}
${lib.optionalString (!backupCfg.s3.enable) ''
if [ ${toString (if backupCfg.retentionDays == 0 then 0 else 1)} -eq 0 ]; then
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-delete
else
${pkgs.findutils}/bin/find "$archive_dir" -maxdepth 1 -type f \
-name ${lib.escapeShellArg timestampArchivePattern} \
-mmin +${toString (backupCfg.retentionDays * 1440)} -delete
fi
''}
'';
startScript = pkgs.writeShellScript "project-zomboid-start" ''
admin_password=$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg adminPasswordFile})
exec ${pkgs.steam-run}/bin/steam-run \
${lib.escapeShellArg "${cfg.installDir}/start-server.sh"} \
-servername ${lib.escapeShellArg cfg.serverName} \
-adminpassword "$admin_password"
'';
in {
options.hectic.services."project-zomboid" = {
enable = lib.mkEnableOption "Project Zomboid dedicated server";
serverName = lib.mkOption {
type = lib.types.strMatching "[A-Za-z0-9._-]+";
default = "servertest";
description = "Name used for Project Zomboid server and save files.";
};
dataDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/project-zomboid";
description = "Writable state directory for the server.";
};
installDir = lib.mkOption {
type = lib.types.path;
default = "/var/lib/project-zomboid/server";
description = "Directory where SteamCMD installs the dedicated server.";
};
port = lib.mkOption {
type = lib.types.port;
default = 16261;
description = "Project Zomboid UDP discovery port.";
};
udpPort = lib.mkOption {
type = lib.types.port;
default = 16262;
description = "Project Zomboid UDP game port.";
};
branch = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Steam beta branch, for example legacy41.";
};
memory = lib.mkOption {
type = lib.types.strMatching "[0-9]+[mMgG]";
default = "3g";
description = "Maximum Java heap for the server, for example 3g.";
};
workshopItems = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Steam Workshop item IDs, downloaded and enabled by the server.";
};
mods = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Project Zomboid mod loading IDs from mod.info.";
};
serverProperties = lib.mkOption {
type = lib.types.attrsOf (
lib.types.oneOf [
lib.types.bool
lib.types.int
lib.types.str
]
);
default = { };
description = "Additional or overriding values for the server INI file.";
};
serverPropertiesFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = "Runtime file with additional INI values, suitable for secrets.";
};
sandboxProperties = lib.mkOption {
type = lib.types.attrsOf sandboxValueType;
default = { };
description = "Values for the Project Zomboid SandboxVars.lua file.";
};
openFirewall = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Open the Project Zomboid UDP ports in the firewall.";
};
rcon = {
enable = lib.mkEnableOption "local RCON for Project Zomboid automation";
port = lib.mkOption {
type = lib.types.port;
default = 27015;
description = "RCON TCP port; not opened in the firewall by this module.";
};
passwordFile = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/rcon-password";
description = "Runtime file containing the generated RCON password.";
};
};
backup = {
enable = lib.mkEnableOption "no-stop Project Zomboid backups";
onCalendar = lib.mkOption {
type = lib.types.str;
default = "*:0/30";
description = "systemd calendar expression controlling backup frequency.";
};
stagingDir = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/backups/staging";
description = "Local directory containing the two-pass rsync staging tree.";
};
archiveDir = lib.mkOption {
type = lib.types.path;
default = "${cfg.dataDir}/backups/archive";
description = "Local directory containing timestamped tar.zst archives.";
};
retentionDays = lib.mkOption {
type = lib.types.ints.between 0 3650;
default = 14;
description = "Delete local archives older than this many days; zero keeps no local archives.";
};
saveWaitSeconds = lib.mkOption {
type = lib.types.ints.positive;
default = 10;
description = "Seconds to wait after the RCON save command before rsync.";
};
s3 = {
enable = lib.mkEnableOption "uploading Project Zomboid backups to S3-compatible storage";
credentialsFile = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
Runtime env file containing AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY. Required when S3 upload is enabled.
'';
};
bucket = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3 bucket receiving backup archives.";
};
endpoint = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3-compatible endpoint URL.";
};
region = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "S3 region passed to awscli2.";
};
prefix = lib.mkOption {
type = lib.types.str;
default = "project-zomboid";
description = "Optional object key prefix within the S3 bucket.";
};
remoteRetentionDays = lib.mkOption {
type = lib.types.ints.positive;
default = 14;
description = "Delete uploaded archives older than this many days.";
};
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = !cfg.rcon.enable || (
lib.hasPrefix "/" cfg.rcon.passwordFile
&& !lib.hasPrefix "/nix/store/" cfg.rcon.passwordFile
);
message = "hectic.services.project-zomboid.rcon.passwordFile must be a runtime path outside /nix/store.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.enable;
message = "hectic.services.project-zomboid.backup must be enabled before S3 upload.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.credentialsFile != null;
message = "hectic.services.project-zomboid.backup.s3.credentialsFile is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.bucket != null;
message = "hectic.services.project-zomboid.backup.s3.bucket is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.endpoint != null;
message = "hectic.services.project-zomboid.backup.s3.endpoint is required when S3 upload is enabled.";
}
{
assertion = !backupCfg.s3.enable || backupCfg.s3.region != null;
message = "hectic.services.project-zomboid.backup.s3.region is required when S3 upload is enabled.";
}
{
assertion =
!backupCfg.s3.enable
|| backupCfg.s3.credentialsFile == null
|| (
lib.hasPrefix "/" backupCfg.s3.credentialsFile
&& !lib.hasPrefix "/nix/store/" backupCfg.s3.credentialsFile
);
message = "hectic.services.project-zomboid.backup.s3.credentialsFile must be a runtime path outside /nix/store.";
}
{
assertion =
!backupCfg.s3.enable
|| backupCfg.s3.endpoint == null
|| lib.hasPrefix "https://" backupCfg.s3.endpoint;
message = "hectic.services.project-zomboid.backup.s3.endpoint must use HTTPS.";
}
];
users.groups.project-zomboid = { };
users.users.project-zomboid = {
isSystemUser = true;
group = "project-zomboid";
home = cfg.dataDir;
createHome = true;
};
systemd.tmpfiles.rules = [
"d ${cfg.dataDir} 0750 project-zomboid project-zomboid - -"
"d ${cfg.installDir} 0750 project-zomboid project-zomboid - -"
] ++ lib.optionals backupCfg.enable [
"d ${cfg.dataDir}/backups 0700 project-zomboid project-zomboid - -"
"Z ${cfg.dataDir}/backups 0700 project-zomboid project-zomboid - -"
"d ${backupCfg.stagingDir} 0700 project-zomboid project-zomboid - -"
"d ${backupCfg.archiveDir} 0700 project-zomboid project-zomboid - -"
];
systemd.services.project-zomboid = {
description = "Project Zomboid dedicated server";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
preStart = ''
${pkgs.coreutils}/bin/install -d -m 0750 \
${lib.escapeShellArg cfg.installDir}
if [ ! -s ${lib.escapeShellArg adminPasswordFile} ]; then
umask 077
${pkgs.openssl}/bin/openssl rand -base64 32 > ${lib.escapeShellArg adminPasswordFile}
fi
${lib.optionalString cfg.rcon.enable ''
if [ ! -s ${lib.escapeShellArg rconPasswordFile} ]; then
umask 077
${pkgs.openssl}/bin/openssl rand -hex 32 > ${lib.escapeShellArg rconPasswordFile}
else
rcon_password=$(${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile})
case "$rcon_password" in
*[!0123456789abcdefABCDEF]*)
umask 077
${pkgs.openssl}/bin/openssl rand -hex 32 > ${lib.escapeShellArg rconPasswordFile}
;;
esac
fi
${pkgs.coreutils}/bin/chown project-zomboid:project-zomboid ${lib.escapeShellArg rconPasswordFile}
${pkgs.coreutils}/bin/chmod 0600 ${lib.escapeShellArg rconPasswordFile}
''}
${pkgs.steamcmd}/bin/steamcmd \
+force_install_dir ${lib.escapeShellArg cfg.installDir} \
+login anonymous \
+app_update 380870 ${lib.optionalString (cfg.branch != null) "-beta ${lib.escapeShellArg cfg.branch}"} validate \
+quit
${pkgs.gnused}/bin/sed -i -E \
's/"-Xmx[0-9]+[mMgG]"/"-Xmx${cfg.memory}"/' \
${lib.escapeShellArg "${cfg.installDir}/ProjectZomboid64.json"}
${pkgs.coreutils}/bin/install -d -m 0750 \
${lib.escapeShellArg "${zomboidDir}/Server"}
{
${lib.concatMapStringsSep "\n " (line:
"${pkgs.coreutils}/bin/printf '%s\\n' ${lib.escapeShellArg line};"
) configLines}
${lib.optionalString (cfg.serverPropertiesFile != null)
"${pkgs.coreutils}/bin/cat ${lib.escapeShellArg cfg.serverPropertiesFile};"}
${lib.optionalString cfg.rcon.enable ''
${pkgs.coreutils}/bin/printf '%s\n' ${lib.escapeShellArg "RCONPort=${toString cfg.rcon.port}"};
${pkgs.coreutils}/bin/printf '%s' 'RCONPassword=';
${pkgs.coreutils}/bin/cat ${lib.escapeShellArg rconPasswordFile};
${pkgs.coreutils}/bin/printf '\n';
''}
} > ${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}.ini"}
${lib.optionalString (cfg.sandboxProperties != { }) ''
{
${pkgs.coreutils}/bin/printf '%s\n' 'SandboxVars = {';
${lib.concatMapStringsSep "\n " (line:
"${pkgs.coreutils}/bin/printf '%s\\n' ${lib.escapeShellArg line};"
) sandboxConfigLines}
${pkgs.coreutils}/bin/printf '%s\n' '};';
} > ${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}_SandboxVars.lua"}
''}
${lib.optionalString (cfg.sandboxProperties == { }) ''
${pkgs.coreutils}/bin/rm -f \
${lib.escapeShellArg "${zomboidDir}/Server/${cfg.serverName}_SandboxVars.lua"}
''}
'';
serviceConfig = {
User = "project-zomboid";
Group = "project-zomboid";
WorkingDirectory = cfg.dataDir;
Environment = [
"HOME=${cfg.dataDir}"
"SteamAppId=108600"
];
ExecStart = startScript;
Restart = "on-failure";
RestartSec = 5;
TimeoutStartSec = "15min";
TimeoutStopSec = 30;
UMask = "0077";
};
};
systemd.services.project-zomboid-backup = lib.mkIf backupCfg.enable {
description = "No-stop Project Zomboid backup";
after = [ "project-zomboid.service" ];
unitConfig.ConditionPathExists = [
saveDir
serverConfigDir
];
serviceConfig = {
Type = "oneshot";
User = "project-zomboid";
Group = "project-zomboid";
ExecStart = backupScript;
TimeoutStartSec = "30min";
UMask = "0077";
} // lib.optionalAttrs backupCfg.s3.enable {
EnvironmentFile = s3CredentialsFile;
};
};
systemd.timers.project-zomboid-backup = lib.mkIf backupCfg.enable {
description = "Run Project Zomboid backup";
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = backupCfg.onCalendar;
Persistent = true;
};
};
networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall [
cfg.port
cfg.udpPort
];
};
}
@@ -16,6 +16,7 @@
matrixClusterSopsFile = flake + "/sus/matrix-cluster.yaml";
in {
imports = [
./minecraft-wow.nix
self.nixosModules.xray-system
self.nixosModules.matrix-cluster
self.nixosModules.matrix-cluster-users
@@ -0,0 +1,35 @@
{ ... }:
{
imports = [ (import ../../module/generic/minecraft-public-relay.nix { }) ];
services.minecraft-public-relay = {
enable = true;
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNWWegOVTOF3EOmam32iP7sMybULMTxsXuC+cEGITQ8 minecraft-wow-relay";
};
systemd.tmpfiles.rules = [ "d /var/www/store/minecraft/world-of-sosal 0755 root root -" ];
services.nginx.virtualHosts."store.bfs.band" = {
enableACME = true;
forceSSL = true;
root = "/var/www/store";
locations."= /".return = "302 /minecraft/world-of-sosal/";
locations."= /minecraft".return = "302 /minecraft/world-of-sosal/";
locations."= /minecraft/".return = "302 /minecraft/world-of-sosal/";
locations."/".extraConfig = ''
autoindex off;
add_header Cache-Control "no-cache";
try_files $uri $uri/ =404;
'';
};
# Keep old pack URLs working for already imported Prism instances.
services.nginx.virtualHosts."bfs.band".locations = {
"= /minecraft".return = "302 /minecraft/world-of-sosal/";
"= /minecraft/".return = "302 /minecraft/world-of-sosal/";
"^~ /minecraft/" = {
root = "/var/www/store";
extraConfig = ''
autoindex off;
add_header Cache-Control "no-cache";
try_files $uri $uri/ =404;
'';
};
};
}
+7
View File
@@ -38,6 +38,13 @@
environment.systemPackages = (with pkgs; [ rsync git steamcmd hectic.AstroTuxLauncher ]);
hectic.services."project-zomboid" = {
enable = true;
serverName = "servertest";
workshopItems = [ ];
mods = [ ];
};
users.users.root.openssh.authorizedKeys.keys = [
''ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKAaObjLBslsdTlqEcYaS1TqX4x9aVJu75y27/8MFevO''
];
+128 -2
View File
@@ -3,8 +3,51 @@
...
}: {
config,
lib,
pkgs,
...
}: {
}: let
repackedActive = true;
migrationWriteFreeze = false;
uploadProxyConfig = ''
# Stream large NARs and tolerate S3 backpressure while Attic reads them.
proxy_http_version 1.1;
proxy_request_buffering off;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
'';
repackedSettings = config.services.atticd.settings // {
listen = "127.0.0.1:8082";
allowed-hosts = [ "cache.${domain}" ];
api-endpoint = if repackedActive then "https://cache.${domain}/" else "https://cache.${domain}/next/";
substituter-endpoint = if repackedActive then "https://cache.${domain}/" else "https://cache.${domain}/next/";
database.url = "sqlite:///var/lib/atticd-repacked/server.db?mode=rwc";
storage = {
type = "s3";
bucket = "nix-cache-hectic-lab";
endpoint = "https://hel1.your-objectstorage.com";
region = "hel1";
};
chunking = {
nar-size-threshold = 1048576;
min-size = 1048576;
avg-size = 2097152;
max-size = 4194304;
};
compression.type = "zstd";
};
repackedConfigFile = pkgs.runCommand "checked-atticd-repacked.toml" {
configFile = (pkgs.formats.toml { }).generate "server-repacked.toml" repackedSettings;
} ''
export ATTIC_SERVER_TOKEN_RS256_SECRET_BASE64="$(${lib.getExe pkgs.openssl} genrsa -traditional 4096 | ${pkgs.coreutils}/bin/base64 -w0)"
export ATTIC_SERVER_DATABASE_URL="sqlite://:memory:"
${lib.getExe config.services.atticd.package} --mode check-config -f $configFile
cat <$configFile >$out
'';
in {
hectic.services.attic = {
enable = true;
hostName = "cache.${domain}";
@@ -17,6 +60,54 @@
};
};
# Slow S3 chunk reads can exceed the SDK's default 20-second stall grace.
services.atticd.package = pkgs.attic-server.overrideAttrs (old: {
# Restrict the SDK TLS connector to HTTP/1.1 after S3 REFUSED_STREAM errors.
cargoDeps = pkgs.runCommand "attic-cargo-vendor-http1" { } ''
mkdir "$out"
shopt -s dotglob
for entry in ${old.cargoDeps}/*; do
ln -s "$entry" "$out/$(basename "$entry")"
done
crate=aws-smithy-http-client-1.0.6
rm "$out/$crate"
cp -rL ${old.cargoDeps}/"$crate" "$out/$crate"
chmod -R u+w "$out/$crate"
substituteInPlace "$out/$crate/src/client/tls.rs" \
--replace-fail '.enable_http2()' ""
'';
postPatch = (old.postPatch or "") + ''
substituteInPlace server/src/storage/s3.rs \
--replace-fail 'let mut builder = S3ConfigBuilder::from(&shared_config);' \
'let mut builder = S3ConfigBuilder::from(&shared_config)
.stalled_stream_protection(
aws_sdk_s3::config::StalledStreamProtectionConfig::enabled()
.grace_period(Duration::from_secs(120))
.build(),
);'
'';
});
services.atticd.settings = lib.mkIf repackedActive {
api-endpoint = lib.mkForce "https://cache.${domain}/previous/";
substituter-endpoint = "https://cache.${domain}/previous/";
};
services.atticd.mode = if migrationWriteFreeze || repackedActive then "api-server" else "monolithic";
systemd.services.atticd-repacked = {
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = config.systemd.services.atticd.serviceConfig // {
ExecStart = "${lib.getExe config.services.atticd.package} -f ${repackedConfigFile} --mode monolithic";
EnvironmentFile = config.sops.secrets."atticd/environment".path;
StateDirectory = "atticd-repacked";
User = "atticd-repacked";
Group = "atticd-repacked";
};
};
services.nginx.virtualHosts."cache.${domain}" = {
enableACME = true;
forceSSL = true;
@@ -24,7 +115,42 @@
client_max_body_size 0;
'';
locations."/" = {
proxyPass = "http://127.0.0.1:8081";
proxyPass = if repackedActive then "http://127.0.0.1:8082" else "http://127.0.0.1:8081";
extraConfig = ''
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'' + lib.optionalString (migrationWriteFreeze && !repackedActive) ''
# Quiesce the old writer during the final snapshot and verification.
limit_except GET {
deny all;
}
'';
};
locations."/next/" = {
proxyPass = "http://127.0.0.1:8082/";
extraConfig = ''
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'';
};
locations."= /_api/v1/upload-path" = lib.mkIf (repackedActive || !migrationWriteFreeze) {
proxyPass = if repackedActive then "http://127.0.0.1:8082" else "http://127.0.0.1:8081";
extraConfig = uploadProxyConfig;
};
locations."= /next/_api/v1/upload-path" = {
proxyPass = "http://127.0.0.1:8082/_api/v1/upload-path";
extraConfig = uploadProxyConfig;
};
locations."/previous/" = {
proxyPass = "http://127.0.0.1:8081/";
extraConfig = ''
# Legacy backend is exposed for read-only migration checks.
limit_except GET {
deny all;
}
# Allow quiet periods while Attic fetches NAR chunks from object storage.
proxy_read_timeout 300s;
'';
};
};
}
+2
View File
@@ -12,6 +12,8 @@ in self.lib.nixpkgs-lib.nixosSystem {
pkgs = import inputs.nixpkgs {
inherit system;
overlays = [ self.overlays.default ];
config.allowUnfreePredicate = pkg:
builtins.elem (inputs.nixpkgs.lib.getName pkg) [ "steamcmd" "steam-unwrapped" "p4d" "p4" ];
};
modules = [
{ networking.hostName = name; }
@@ -17,7 +17,7 @@ let
UsePAM yes
AuthenticationMethods publickey
AuthorizedKeysFile %h/.ssh/authorized_keys /etc/ssh/authorized_keys.d/%u
LogLevel DEBUG3
LogLevel INFO
VersionAddendum none
HostKeyAlgorithms rsa-sha2-512,rsa-sha2-256,ssh-ed25519
@@ -65,7 +65,8 @@ in
Type = "simple";
StateDirectory = "experimental-sshd";
RuntimeDirectory = "experimental-sshd";
ExecStart = "${pkgs.openssh}/bin/sshd -D -e -f /etc/ssh/experimental-sshd_config";
ExecStart = "${pkgs.openssh}/bin/sshd -D -f /etc/ssh/experimental-sshd_config";
StandardError = "journal";
};
preStart = ''
${pkgs.openssh}/bin/sshd -t -f /etc/ssh/experimental-sshd_config
+316 -7
View File
@@ -8,14 +8,13 @@
config,
pkgs,
lib,
modulesPath,
...
}:
with builtins;
with lib;
let
domain = "hectic-lab.com";
sshPort = 22;
giteaSshPort = 22223;
mailUserNames = [
"security"
"founders"
@@ -44,6 +43,12 @@ let
group = "ente";
};
};
giteaRunnerInstance = "hectic-lab-local";
giteaRunnerEscapedInstance = builtins.replaceStrings [ "-" ] [ "\\x2d" ] giteaRunnerInstance;
giteaRunnerService = "gitea-runner-${giteaRunnerEscapedInstance}";
giteaRunnerTokenEnvService = "${giteaRunnerService}-token-env";
giteaRunnerTokenEnv = "/run/gitea-runner-${giteaRunnerInstance}/token.env";
worldOfSosalRoot = "/var/www/store/world-of-sosal";
in {
imports = [
self.nixosModules.hectic
@@ -54,11 +59,14 @@ in {
self.nixosModules."shadowsocks" # NOTE(nrv): usage/instance
inputs.hectic-landing.nixosModules.hectic-landing
inputs.iana-angl.nixosModules.iana-angl
(import ./attic.nix { inherit flake self inputs domain; })
(import ./containers.nix { inherit flake self inputs; })
./experimental-sshd.nix
./minecraft-wow-proxy.nix
(import ./ente.nix { inherit domain; })
(import ./immich.nix { inherit domain; })
(import ./mechabellum.nix { inherit flake self inputs domain; })
(import (./. + "/sentinèlla.nix") { inherit flake self inputs domain; })
];
@@ -71,6 +79,12 @@ in {
host = "127.0.0.1";
};
services.iana-angl = {
enable = true;
package = inputs.iana-angl.packages.${pkgs.stdenv.hostPlatform.system}.iana-angl;
domain = "lessons.${domain}";
};
# NOTE(yukkop): both nixos-mailserver and hectic-landing module set
# security.acme.defaults.email. Force the mailserver-aligned address.
security.acme.defaults.email = lib.mkForce "security@${domain}";
@@ -87,6 +101,116 @@ in {
services.matrix = {
enable = false;
};
services."project-zomboid" = {
enable = true;
memory = "4g";
serverName = "servertest";
serverPropertiesFile = /var/lib/project-zomboid/server-password.ini;
rcon.enable = true;
backup = {
enable = true;
onCalendar = "*:0/30";
retentionDays = 0;
s3 = {
enable = true;
bucket = "backup-hectic-lab";
endpoint = "https://hel1.your-objectstorage.com";
region = "hel1";
credentialsFile = "/var/lib/project-zomboid/s3-credentials";
};
};
serverProperties = {
Map = "Muldraugh, KY";
SaveWorldEveryMinutes = 15;
DoLuaChecksum = false;
Public = true;
AntiCheatSafety = 4;
AntiCheatMovement = 4;
AntiCheatSpeed = 4;
AntiCheatHit = 4;
AntiCheatPacket = 4;
AntiCheatPacketException = 4;
AntiCheatPermission = 4;
AntiCheatXP = 4;
AntiCheatFire = 4;
AntiCheatSafeHouse = 4;
AntiCheatRecipe = 4;
AntiCheatPlayer = 4;
AntiCheatChecksum = 4;
AntiCheatItem = 4;
AntiCheatNoClip = 4;
AntiCheatServerCustomization = 4;
};
workshopItems = [
"3676456221" # Lua Digital Watch Framework
"3600401184" # Realistic Temperature Mod
];
mods = [
"\\LuaDigitalWatchUI"
"\\RC_RealisticColdMod"
];
sandboxProperties = {
StartMonth = 12;
StartDay = 1;
WaterShut = 3;
WaterShutModifier = 150;
ElecShut = 3;
ElecShutModifier = 150;
MinutesPerPage = 0.5;
Zombies = 4;
ZombieConfig = {
PopulationMultiplier = 1.3;
PopulationStartMultiplier = 1.0;
PopulationPeakMultiplier = 1.0;
RespawnHours = 0.0;
RespawnUnseenHours = 0.0;
RespawnMultiplier = 0.0;
RedistributeHours = 0.0;
};
ZombieLore = {
Transmission = 4;
Mortality = 7;
Speed = 2;
SprinterPercentage = 0;
Strength = 2;
Cognition = 2;
DoorOpeningPercentage = 10;
};
};
};
services.p4d = {
enable = true;
package = pkgs.p4d;
clientPackage = pkgs.p4;
openFirewall = true;
bootstrap.enable = false;
};
services.gitea-runner-controller = {
# NOTE(yukkop): ephemeral Hetzner VM runners (1 VM = 1 job).
# Runbook: infra/gitea-runners/runbook.md "Ephemeral VM runner cutover".
enable = true;
budgetEurMonthly = "30";
imageId = "429747473"; # MicroOS x86 + persistent controller SSH key and writable Nix mount
armImageId = "423979717"; # OpenSUSE MicroOS ARM K3S 2026-08-24 snapshot
nixImageId = "161547269"; # Ubuntu 24.04 x86; Nix needs writable root
armNixImageId = "161547270"; # Ubuntu 24.04 ARM; Nix needs writable root
allowedRepos = [
"hinterland/*"
"yukkop/*"
"hectic-lab/*"
];
# FIXME(yukkop): debug key for bootstrap debugging; remove once E2E stable.
debugSshPublicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSWIv80pyCMDQ6zH34P2qWizpOcO7X86BVhMGtbob9U gcr-controller@hectic-lab";
hcloudSshKeyId = 118512401;
};
};
zramSwap = {
enable = true;
priority = 100;
algorithm = lib.mkDefault "zstd";
swapDevices = 1;
memoryPercent = lib.mkDefault 100;
};
# NOTE(yukkop): disk was provisioned by Hetzner rescue image, disko was never
@@ -102,6 +226,12 @@ in {
options = [ "umask=0077" ];
};
fileSystems."/nix" = lib.mkForce {
device = "/dev/disk/by-id/scsi-0HC_Volume_106777875";
fsType = "ext4";
neededForBoot = true;
};
programs.zsh.enable = true;
programs.zsh.interactiveShellInit = ''
setopt vi
@@ -125,16 +255,62 @@ in {
key = "init-postgresql";
};
"atticd/environment" = {};
"wg-bfs/private-key" = {};
"immich/storage-box" = {};
"wg-bfs/private-key" = {};
"gitea-runner/org-registration-token" = {
sopsFile = flake + "/sus/gitea-runners.yaml";
key = "gitea/hectic-lab/org-runner-registration-token";
};
} // builtins.listToAttrs (map mkEnteSecret [
"key-encryption"
"key-hash"
"jwt-secret"
"s3-access-key"
"s3-secret-key"
]);
]) // {
"project-zomboid/s3-access-key" = {
key = "ente/s3-access-key";
owner = "project-zomboid";
group = "project-zomboid";
};
"project-zomboid/s3-secret-key" = {
key = "ente/s3-secret-key";
owner = "project-zomboid";
group = "project-zomboid";
};
};
};
systemd.services.project-zomboid.preStart = lib.mkBefore ''
password_file=${lib.escapeShellArg "/var/lib/project-zomboid/server-password"}
properties_file=${lib.escapeShellArg "/var/lib/project-zomboid/server-password.ini"}
s3_credentials_file=${lib.escapeShellArg "/var/lib/project-zomboid/s3-credentials"}
s3_credentials_tmp="$(${pkgs.coreutils}/bin/mktemp "''${s3_credentials_file}.XXXXXX")"
trap '${pkgs.coreutils}/bin/rm -f "$s3_credentials_tmp"' EXIT
{
${pkgs.coreutils}/bin/printf 'AWS_ACCESS_KEY_ID='
${pkgs.coreutils}/bin/cat ${lib.escapeShellArg config.sops.secrets."project-zomboid/s3-access-key".path}
${pkgs.coreutils}/bin/printf '\n'
${pkgs.coreutils}/bin/printf 'AWS_SECRET_ACCESS_KEY='
${pkgs.coreutils}/bin/cat ${lib.escapeShellArg config.sops.secrets."project-zomboid/s3-secret-key".path}
${pkgs.coreutils}/bin/printf '\n'
} > "$s3_credentials_tmp"
${pkgs.coreutils}/bin/chmod 0400 "$s3_credentials_tmp"
${pkgs.coreutils}/bin/mv -f "$s3_credentials_tmp" "$s3_credentials_file"
if [ ! -s "$password_file" ] || ! ${pkgs.gnugrep}/bin/grep -Eq '^[0-9a-f]{48}$' "$password_file"; then
umask 077
${pkgs.openssl}/bin/openssl rand -hex 24 > "$password_file"
fi
${pkgs.coreutils}/bin/chmod 0600 "$password_file"
properties_file_tmp="$(${pkgs.coreutils}/bin/mktemp "$(dirname "$properties_file")/.server-password.ini.XXXXXX")"
${pkgs.coreutils}/bin/printf 'Password=%s\n' "$(<"$password_file")" > "$properties_file_tmp"
${pkgs.coreutils}/bin/chmod 0600 "$properties_file_tmp"
${pkgs.coreutils}/bin/mv "$properties_file_tmp" "$properties_file"
'';
users.users.root.openssh.authorizedKeys.keys = [
# neuro machine
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDfqSROY+rp7amPPiArY3sZM7jTjYBS02csWxF/NeIr/ root@neuro"
@@ -148,6 +324,8 @@ in {
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE/EhBI6sJb2yHbTkqhZiCzUrsLE6t+CZe7RhS22z7w5 nrv@adamantia"
# github workflow
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKPEUArBxu7NUULT7Pi8ArtVxY1uVbIBSaeRKtqz1sz1"
# gitea workflow
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAogEr5boewtUrOeOqI96y/7FWR03vdbGW93Nj01tiIS gitea-actions-hectic-lab-deploy"
];
users.users.ds4d = { # NOTE(nrv): artishoque
@@ -164,7 +342,7 @@ in {
];
};
services.openssh.ports = [ sshPort ];
services.openssh.ports = [ giteaSshPort ];
services.mailserver = {
enable = true;
@@ -186,7 +364,7 @@ in {
networking.firewall = {
allowedTCPPorts = [
sshPort # ssh
giteaSshPort # gitea ssh
80
443
3306 # mysql
@@ -207,8 +385,40 @@ in {
systemd.tmpfiles.rules = [
"d /var/www/store 0755 nginx nginx -"
"d ${worldOfSosalRoot} 0750 root nginx -"
"d ${worldOfSosalRoot}/releases 0750 root nginx -"
];
systemd.services.${giteaRunnerTokenEnvService} = {
description = "Prepare local Gitea Actions runner token environment";
requiredBy = [ "${giteaRunnerService}.service" ];
before = [ "${giteaRunnerService}.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "gitea-runner-${giteaRunnerInstance}";
RuntimeDirectoryMode = "0700";
};
script = ''
set -eu
umask 077
token_file=${config.sops.secrets."gitea-runner/org-registration-token".path}
env_file=${giteaRunnerTokenEnv}
printf 'TOKEN=' > "$env_file"
tr -d '\n' < "$token_file" >> "$env_file"
printf '\n' >> "$env_file"
'';
};
systemd.services.${giteaRunnerService} = {
after = [
"gitea.service"
"${giteaRunnerTokenEnvService}.service"
];
requires = [ "${giteaRunnerTokenEnvService}.service" ];
};
services.nginx = {
enable = true;
# NOTE(yukkop): virtualHosts.${domain} is owned by the hectic-landing module
@@ -221,6 +431,69 @@ in {
autoindex on;
'';
};
locations."= /world-of-sosal/" = {
extraConfig = ''
return 302 /world-of-sosal/index.html;
'';
};
locations."= /world-of-sosal/index.html" = {
extraConfig = ''
alias ${./static/world-of-sosal/index.html};
default_type text/html;
add_header Cache-Control "no-cache" always;
limit_except GET {
deny all;
}
'';
};
locations."= /world-of-sosal/latest.mrpack" = {
extraConfig = ''
root /var/www/store;
default_type application/zip;
add_header Content-Disposition "attachment" always;
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
try_files $uri =404;
if ($request_method != GET) { return 405; }
'';
};
locations."= /world-of-sosal/SHA256SUMS" = {
extraConfig = ''
root /var/www/store;
default_type text/plain;
add_header Content-Disposition "attachment" always;
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
try_files $uri =404;
if ($request_method != GET) { return 405; }
'';
};
locations."= /world-of-sosal/releases/" = {
extraConfig = ''
return 404;
'';
};
locations."~ ^/world-of-sosal/releases/[A-Za-z0-9][A-Za-z0-9._-]*\\.mrpack$" = {
extraConfig = ''
root /var/www/store;
default_type application/zip;
add_header Content-Disposition "attachment" always;
add_header Cache-Control "public, max-age=31536000, immutable" always;
try_files $uri =404;
if ($request_method != GET) { return 405; }
'';
};
locations."/world-of-sosal/" = {
extraConfig = ''
autoindex off;
limit_except GET {
deny all;
}
return 404;
'';
};
};
virtualHosts."lessons.${domain}" = {
enableACME = true;
forceSSL = true;
};
virtualHosts."snuff.${domain}" = {
enableACME = true;
@@ -255,10 +528,15 @@ in {
virtualHosts."gitea.${domain}" = {
enableACME = true;
forceSSL = true;
# NOTE(yukkop): allow large git pushes over HTTPS.
extraConfig = "client_max_body_size 512m;";
locations."/" = {
extraConfig = ''
proxy_pass http://127.0.0.1:11011/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
'';
};
};
@@ -268,12 +546,21 @@ in {
gitea = {
enable = true;
package = pkgs.hectic.gitea-heatmap;
# Keep LFS storage limited to accounts provisioned by administrators.
settings.service.DISABLE_REGISTRATION = true;
settings.session.COOKIE_SECURE = true;
settings.actions.ENABLED = true;
# Long CUDA builds must not hit Gitea's default three-hour task watchdog.
settings.actions.ENDLESS_TASK_TIMEOUT = "8h";
settings.server = {
HTTP_ADDR = "127.0.0.1";
HTTP_PORT = 11011;
SSH_PORT = sshPort;
ROOT_URL = "https://gitea.${domain}/";
SSH_PORT = giteaSshPort;
SSH_DOMAIN = "hectic-lab.com";
};
lfs.enable = true;
settings.lfs.LFS_MAX_FILE_SIZE = 536870912;
database = {
createDatabase = true;
type = "postgres";
@@ -282,5 +569,27 @@ in {
name = "gitea";
};
};
gitea-actions-runner.instances.${giteaRunnerInstance} = {
enable = false;
name = giteaRunnerInstance;
url = "https://gitea.${domain}";
tokenFile = giteaRunnerTokenEnv;
labels = [
"nix:host"
"native:host"
];
hostPackages = with pkgs; [
bash
cacert
coreutils
curl
git
gnutar
gzip
nix
nodejs
xz
];
};
};
}
+16
View File
@@ -0,0 +1,16 @@
{ domain, ... }:
{
config,
...
}:
{
hectic.services.immich = {
enable = true;
domain = "immich.${domain}";
storageBox = {
enable = true;
credentialsFile = config.sops.secrets."immich/storage-box".path;
};
};
}
@@ -0,0 +1,8 @@
{ ... }:
{
imports = [ (import ../../module/generic/minecraft-public-relay.nix { }) ];
services.minecraft-public-relay = {
enable = true;
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNWWegOVTOF3EOmam32iP7sMybULMTxsXuC+cEGITQ8 minecraft-wow-relay";
};
}
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WorldOfSosal</title>
</head>
<body>
<main>
<h1>WorldOfSosal</h1>
<p><a href="https://store.hectic-lab.com/minecraft/world-of-sosal/">Install in Prism with automatic mod updates</a></p>
<p><a href="https://store.hectic-lab.com/world-of-sosal/latest.mrpack">Download latest pack</a></p>
<p><a href="prismlauncher://import?url=https%3A%2F%2Fstore.hectic-lab.com%2Fworld-of-sosal%2Flatest.mrpack">Import latest pack in Prism Launcher</a></p>
<p><a href="https://store.hectic-lab.com/world-of-sosal/SHA256SUMS">SHA-256 checksums</a></p>
<p>Updates are manual. Packs imported from arbitrary URLs do not update automatically.</p>
</main>
</body>
</html>
+52
View File
@@ -0,0 +1,52 @@
# WorldOfSosal pack publishing
The public endpoint is `https://store.hectic-lab.com/world-of-sosal/`. Nix
deploys only its landing page and nginx configuration. Pack files, the checksum
manifest, and `latest.mrpack` stay under `/var/www/store/world-of-sosal` on the
host and never enter Git or the Nix store.
## Publish an uploaded pack
Run these commands on `hectic-lab` as root after the Storage Box pack has
already been uploaded to a local staging path. Pick a stable version name; do
not replace an existing versioned release.
```sh
set -eu
source_pack=/path/to/already-uploaded/WorldOfSosal.mrpack
version=2026-09-16
root=/var/www/store/world-of-sosal
release_name="WorldOfSosal-${version}.mrpack"
release_path="$root/releases/$release_name"
printf '%s %s\n' \
f8c18acb9208e4592725632ae50dab4f9c308483b34fd43a6507c74fdbf8169f \
"$source_pack" | sha256sum --check --status
test ! -e "$release_path"
install -o root -g nginx -m 0640 "$source_pack" "$release_path.new"
mv -T "$release_path.new" "$release_path"
manifest="$root/.SHA256SUMS.$$"
(cd "$root/releases" && sha256sum -- *.mrpack) > "$manifest"
chown root:nginx "$manifest"
chmod 0640 "$manifest"
mv -Tf "$manifest" "$root/SHA256SUMS"
latest="$root/.latest.mrpack.$$"
ln -s "releases/$release_name" "$latest"
mv -Tf "$latest" "$root/latest.mrpack"
```
Versioned releases use a one-year immutable cache policy. `latest.mrpack` and
`SHA256SUMS` disable caching so an atomic replacement becomes visible quickly.
The manifest is available at
`https://store.hectic-lab.com/world-of-sosal/SHA256SUMS`.
Import the current pack in Prism Launcher with:
```text
prismlauncher://import?url=https%3A%2F%2Fstore.hectic-lab.com%2Fworld-of-sosal%2Flatest.mrpack
```
Direct URL imports do not auto-update. Repeat the publication and import steps
for each new pack version.
+16
View File
@@ -1,3 +1,17 @@
# Current Minecraft access (2026-09-18)
WorldOfSosal on the WoW map uses `store.hectic-lab.com:25568` publicly.
The game server is `neuro:25567`; a restricted persistent reverse SSH tunnel
connects it to the public relay. See `docs/minecraft-prism.md` and the Nix modules
`minecraft/public-tunnel.nix` / `hectic-lab/minecraft-wow-proxy.nix`.
Verified LAN: neuro is `192.168.88.10`, gateway `192.168.88.1`.
SSH access is `95.31.254.84:34457`. Direct external Minecraft TCP probes timed out,
and no UPnP IGD was discovered. The old TP-Link network and manual port-forward
instructions below describe the previous network, not the active configuration.
---
# Router Access (TP-Link)
The server `neuro` is behind a NAT router at `192.168.0.1`.
@@ -50,6 +64,8 @@ Ports that need to be forwarded from router to `192.168.0.10`:
| 5269 | 5269 | TCP | XMPP (s2s) |
| 10000 | 10000 | UDP | Jitsi Videobridge |
| 25565 | 25565 | TCP | Minecraft |
| 25567 | 25567 | TCP | Minecraft WoW Mine map |
| 25568 | 25568 | TCP | Minecraft World of Sosal |
## Troubleshooting
+5 -3
View File
@@ -17,10 +17,12 @@ in self.lib.nixpkgs-lib.nixosSystem {
];
config.allowUnfreePredicate = pkg:
self.lib.cudaUnfreePredicate pkg || builtins.elem (self.lib.nixpkgs-lib.getName pkg) [
"minecraft-server"
"neoforge"
"minecraft-server"
"neoforge"
"steamcmd"
"steam-unwrapped"
"nvidia-x11"
"nvidia-x11"
];
# jitsi-meet depends on libolm which is marked insecure (CVE-2024-4519x)
config.permittedInsecurePackages = [
-61
View File
@@ -1,61 +0,0 @@
{
pkgs,
...
}:
{
services.minecraft-servers = {
enable = true;
eula = true;
openFirewall = true;
servers = {
vanilla = {
enable = true;
jvmOpts = "-Xmx6G -Xms2G";
package = pkgs.minecraftServers.vanilla-1_21_11;
serverProperties = {
server-port = 25565;
difficulty = "hard";
online-mode = true;
view-distance = 32;
level-seed = "8306359138650378643";
pause-when-empty-seconds = 0;
};
};
createAeronautics = {
enable = true;
jvmOpts = "-Xmx8G -Xms2G";
package = pkgs.minecraftServers.neoforge-1_21_1;
symlinks = {
mods = pkgs.linkFarmFromDrvs "mods" (
builtins.attrValues {
Sable = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/T9PomCSv/versions/g8CObHcP/sable-neoforge-1.21.1-1.1.3.jar";
sha512 = "8180e214681c171c9e3b7fa307f7a92bd7de0b8125d671291425f04a4ba26b408758d8ea80a6386d8e73bb1e6b02caf3f20afb9b91ecedd48c37ed44363ac961";
};
Create = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/LNytGWDc/versions/UjX6dr61/create-1.21.1-6.0.10.jar";
sha512 = "11cc8fc049d2f67f6548c7abfada6b82a3adb5c7ca410a742de04bbca76e03862c518721b88d806f6e6d768a4d68531fdb903a85859b25d1484d550cc7bafd4b";
};
CreateAeronautics = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/oWaK0Q19/versions/1sv6OtSz/create-aeronautics-bundled-1.21.1-1.1.3.jar";
sha512 = "94831bc4702b3864524258fa0a73a50ab3cd37e9c157b5c6688a6845b866ec5838452804050b55e490549d91dad909fc37f0d619f354c5676e2e2651b9c15ec6";
};
}
);
};
serverProperties = {
server-port = 25566;
difficulty = "hard";
online-mode = true;
view-distance = 20;
pause-when-empty-seconds = 0;
};
};
};
};
}
@@ -0,0 +1,21 @@
{ pkgs, ... }:
{
services.minecraft-servers.servers.createAeronautics = {
enable = true;
jvmOpts = "-Xmx8G -Xms2G";
package = pkgs.minecraftServers.neoforge-1_21_1;
symlinks = {
mods = import ./mods.nix { inherit pkgs; };
};
serverProperties = {
server-port = 25566;
difficulty = "hard";
online-mode = true;
view-distance = 20;
pause-when-empty-seconds = 0;
};
};
}
+17
View File
@@ -0,0 +1,17 @@
{
imports = [
./vanilla.nix
./create-aeronautics.nix
./wow-mine-map.nix
./world-of-sosal.nix
./public-tunnel.nix
./world-import.nix
./modpack-import.nix
];
services.minecraft-servers = {
enable = true;
eula = true;
openFirewall = true;
};
}
@@ -0,0 +1,460 @@
{
config,
lib,
pkgs,
...
}: let
inherit (lib) mkOption types;
cfg = config.services.minecraft-modpack-imports;
enabledImports = lib.filterAttrs (_: import: import.enable) cfg;
dataDir = config.services.minecraft-servers.dataDir;
minecraftServers = config.services.minecraft-servers.servers;
targetServers = lib.mapAttrsToList (_: import: import.serverName) enabledImports;
importerUser = name: let
descriptiveName = "mc-pack-${name}";
in
if builtins.stringLength descriptiveName <= 31
then descriptiveName
else "mc-pack-${builtins.substring 0 16 (builtins.hashString "sha256" name)}";
stateDirectory = cacheDir:
if lib.hasPrefix "/var/lib/" cacheDir
then lib.removePrefix "/var/lib/" cacheDir
else null;
stateDirectoryCompatible = cacheDir: let
relative = stateDirectory cacheDir;
components = lib.splitString "/" (if relative == null then "" else relative);
in
relative != null
&& relative != ""
&& lib.all (component: component != "" && component != "." && component != "..") components;
escapeSftp = value:
"\"${lib.replaceStrings ["\\" "\""] ["\\\\" "\\\""] value}\"";
escapeTmpfiles = value:
lib.replaceStrings ["%" " " "\t"] ["%%" "\\x20" "\\x09"] value;
importerServices = lib.mkMerge (lib.mapAttrsToList (name: import: let
user = importerUser name;
unitName = "minecraft-modpack-import-${name}";
serverUnit = "minecraft-server-${import.serverName}.service";
cacheStateDirectory = stateDirectory import.cacheDir;
serverDir = "${dataDir}/${import.serverName}";
in {
${unitName} = {
description = "Import Minecraft Modrinth pack ${name}";
before = [ serverUnit ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
path = [
pkgs.coreutils
pkgs.curl
pkgs.findutils
pkgs.jq
pkgs.openssh
pkgs.unar
];
serviceConfig = {
Type = "oneshot";
User = user;
Group = user;
RemainAfterExit = true;
TimeoutStartSec = import.timeout;
ProtectSystem = "strict";
ProtectHome = true;
PrivateDevices = true;
PrivateTmp = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectKernelLogs = true;
ProtectControlGroups = true;
NoNewPrivileges = true;
RestrictSUIDSGID = true;
LockPersonality = true;
CapabilityBoundingSet = [ "" ];
ReadWritePaths = [ import.cacheDir serverDir ];
UMask = "0007";
} // lib.optionalAttrs (stateDirectoryCompatible import.cacheDir) {
StateDirectory = cacheStateDirectory;
};
script = ''
set -eu
umask 007
cache_dir=${lib.escapeShellArg import.cacheDir}
server_dir=${lib.escapeShellArg serverDir}
archive_name=${lib.escapeShellArg import.archiveName}
archive="$cache_dir/$archive_name"
temporary_archive="$cache_dir/.$archive_name.$$"
extraction_dir="$cache_dir/.extract-${name}.$$"
staging_dir="$cache_dir/.stage-${name}.$$"
managed_paths="$cache_dir/managed-paths"
new_managed_paths="$cache_dir/.managed-paths.$$"
key=${lib.escapeShellArg import.sshKeyFile}
cleanup() {
rm -f "$temporary_archive" "$new_managed_paths"
rm -rf "$extraction_dir" "$staging_dir"
}
trap cleanup EXIT
safe_relative_path() {
case "$1" in
""|/*|*\\*|.|..|./*|../*|*/./*|*/../*|*/.|*/..)
return 1
;;
esac
return 0
}
archive_valid() {
[ -f "$archive" ] && printf '%s %s\n' \
${lib.escapeShellArg import.archiveSha256} \
"$archive" | sha256sum -c --status
}
archive_entries_valid() {
lsar -json "$archive" | jq -e '
(.lsarContents // .entries) as $entries
| ($entries | type == "array")
and ($entries | all(.[];
(.XADFileName // .XADPath) as $path
| ($path | type == "string")
and ($path | startswith("/") | not)
and ($path | contains("\\") | not)
and ($path | test("[[:cntrl:]]") | not)
and ([$path | split("/")[] | select(. == "" or . == "." or . == "..")] | length == 0)
and ((.XADIsSymbolicLink // false) | not)
and ((.XADIsHardLink // false) | not)
and ((.XADIsDevice // false) | not)
and ((.XADIsFIFO // false) | not)
and ((.XADIsSocket // false) | not)
)
)
' >/dev/null
}
mkdir -p "$cache_dir" "$server_dir"
chmod 0700 "$cache_dir"
if ! archive_valid; then
rm -f "$archive"
downloaded=false
attempt=1
while [ "$attempt" -le ${toString import.retries} ]; do
rm -f "$temporary_archive"
if sftp \
-o BatchMode=yes \
-o StrictHostKeyChecking=yes \
-o UserKnownHostsFile=/etc/ssh/ssh_known_hosts \
-i "$key" \
-b - \
${lib.escapeShellArg "${import.remoteUser}@${import.remoteHost}"} <<EOF
get ${escapeSftp import.remotePath} "$temporary_archive"
EOF
then
if printf '%s %s\n' \
${lib.escapeShellArg import.archiveSha256} \
"$temporary_archive" | sha256sum -c --status; then
mv "$temporary_archive" "$archive"
downloaded=true
break
fi
fi
rm -f "$temporary_archive"
attempt=$((attempt + 1))
done
if [ "$downloaded" != true ]; then
echo "Unable to download verified Minecraft modpack ${name}" >&2
exit 1
fi
fi
if ! archive_entries_valid; then
echo "Modpack archive contains unsafe entries" >&2
exit 1
fi
mkdir -p "$extraction_dir" "$staging_dir"
unar -quiet -output-directory "$extraction_dir" "$archive"
find "$extraction_dir" \
\( -type l -o -type b -o -type c -o -type p -o -type s \) \
-delete
manifest=$(find "$extraction_dir" -type f -name modrinth.index.json -print)
if [ -z "$manifest" ] || [ "$(printf '%s\n' "$manifest" | wc -l)" -ne 1 ]; then
echo "Modpack must contain exactly one modrinth.index.json" >&2
exit 1
fi
pack_root=$(dirname "$manifest")
if ! jq -e \
--argjson expectedDependencies ${lib.escapeShellArg (builtins.toJSON import.expectedDependencies)} \
'
. as $manifest
| .formatVersion == 1
and ($expectedDependencies | to_entries | all(.[];
$manifest.dependencies[.key] == .value
))
and (.files | type == "array")
and all(.files[];
((.env.server // "required") == "unsupported")
or (
(.path | type == "string")
and (.path | length > 0)
and (.path | startswith("mods/"))
and (.path | startswith("/") | not)
and (.path | contains("\\") | not)
and (.path | test("[[:cntrl:]]") | not)
and ([.path | split("/")[] | select(. == "" or . == "." or . == "..")] | length == 0)
and (.hashes.sha512 | type == "string")
and (.hashes.sha512 | test("^[0-9a-fA-F]{128}$"))
and (.downloads | type == "array")
and (.downloads | length > 0)
and (.downloads[0] | type == "string")
and (.downloads[0] | startswith("https://"))
and (.downloads[0] | test("[[:cntrl:]]") | not)
)
)
' "$manifest" >/dev/null; then
echo "Modpack manifest contains unsafe or invalid server files" >&2
exit 1
fi
: > "$new_managed_paths"
jq -r '
.files[]
| select((.env.server // "required") != "unsupported")
| [.path, .hashes.sha512, .downloads[0]]
| @tsv
' "$manifest" |
while IFS="$(printf '\t')" read -r relative expected_hash url; do
safe_relative_path "$relative" || exit 1
destination="$staging_dir/$relative"
mkdir -p "$(dirname "$destination")"
curl --fail --location --silent --show-error \
--retry ${toString import.retries} \
--output "$destination" \
"$url"
if ! printf '%s %s\n' "$expected_hash" "$destination" |
sha512sum -c --status; then
echo "SHA-512 mismatch for $relative" >&2
exit 1
fi
printf '%s\n' "$relative" >> "$new_managed_paths"
done
overrides_dir="$pack_root/overrides"
if [ -d "$overrides_dir" ]; then
find "$overrides_dir" \
\( -type l -o -type b -o -type c -o -type p -o -type s \) \
-delete
cp -R "$overrides_dir/." "$staging_dir/"
find "$overrides_dir" -type f -printf '%P\n' |
while IFS= read -r relative; do
safe_relative_path "$relative" || exit 1
printf '%s\n' "$relative"
done >> "$new_managed_paths"
fi
# Nix Minecraft manages eula.txt via a symlink. Only reject symlinks
# in destinations we actually touch, including their parent directories.
safe_target_path() {
safe_relative_path "$1" || return 1
target="$server_dir/$1"
while [ "$target" != "$server_dir" ]; do
if [ -L "$target" ]; then
echo "Modpack destination contains symlink: $target" >&2
return 1
fi
target=$(dirname "$target")
done
}
while IFS= read -r relative; do
safe_target_path "$relative" || exit 1
done < "$new_managed_paths"
if [ -f "$managed_paths" ]; then
while IFS= read -r relative; do
safe_target_path "$relative" || exit 1
done < "$managed_paths"
fi
while IFS= read -r relative; do
safe_relative_path "$relative" || exit 1
source_file="$staging_dir/$relative"
target_file="$server_dir/$relative"
install -d -m 0770 -g minecraft "$(dirname "$target_file")"
install -m 0660 -g minecraft "$source_file" "$target_file"
done < "$new_managed_paths"
if [ -f "$managed_paths" ]; then
while IFS= read -r old_relative; do
safe_relative_path "$old_relative" || {
echo "Unsafe path in previous managed-paths file" >&2
exit 1
}
keep=false
while IFS= read -r relative; do
if [ "$old_relative" = "$relative" ]; then
keep=true
break
fi
done < "$new_managed_paths"
if [ "$keep" != true ]; then
rm -f "$server_dir/$old_relative"
fi
done < "$managed_paths"
fi
mv "$new_managed_paths" "$managed_paths"
'';
};
"minecraft-server-${import.serverName}" = {
requires = [ "${unitName}.service" ];
after = [ "${unitName}.service" ];
};
}) enabledImports);
in {
options.services.minecraft-modpack-imports = mkOption {
default = { };
type = types.attrsOf (types.submodule ({ name, ... }: {
options = {
enable = lib.mkEnableOption "Minecraft Modrinth pack import ${name}";
serverName = mkOption {
type = types.str;
description = "minecraft-servers server receiving imported pack";
};
remoteHost = mkOption {
type = types.str;
description = "SSH host serving Modrinth pack archive";
};
remoteUser = mkOption {
type = types.str;
description = "SSH user used to download Modrinth pack archive";
};
remotePath = mkOption {
type = types.str;
description = "Remote path to Modrinth pack archive";
};
archiveName = mkOption {
type = types.str;
description = "Archive file name inside cache directory";
};
cacheDir = mkOption {
type = types.str;
default = "/var/lib/minecraft-modpacks/${name}";
description = "Persistent Modrinth archive and importer state directory";
};
archiveSha256 = mkOption {
type = types.strMatching "[0-9a-fA-F]{64}";
description = "Expected SHA-256 digest of Modrinth pack archive";
};
expectedDependencies = mkOption {
type = types.attrsOf types.str;
default = { };
description = "Required dependency versions in modrinth.index.json";
};
sshKeyFile = mkOption {
type = types.str;
description = "Runtime path to private SSH key";
};
hostPublicKey = mkOption {
type = types.str;
description = "Pinned SSH host public key";
};
retries = mkOption {
type = types.ints.positive;
default = 3;
description = "Maximum SFTP attempts and curl retry count";
};
timeout = mkOption {
type = types.str;
default = "30min";
description = "Importer service start timeout";
};
};
}));
description = "Modrinth packs imported before selected Minecraft servers start";
};
config = lib.mkIf (enabledImports != { }) {
assertions = lib.flatten (lib.mapAttrsToList (name: import: [
{
assertion = builtins.match "[A-Za-z0-9_-]+" name != null;
message = "services.minecraft-modpack-imports.${name}: name must contain only letters, digits, underscores, or hyphens";
}
{
assertion = builtins.match "/.*" import.cacheDir != null;
message = "services.minecraft-modpack-imports.${name}.cacheDir must be absolute";
}
{
assertion = builtins.match "/var/lib(/[A-Za-z0-9][A-Za-z0-9._-]*)+" import.cacheDir != null;
message = "services.minecraft-modpack-imports.${name}.cacheDir must be beneath /var/lib with safe path components";
}
{
assertion = builtins.match "[A-Za-z0-9_-]+" import.serverName != null;
message = "services.minecraft-modpack-imports.${name}.serverName must contain only letters, digits, underscores, or hyphens";
}
{
assertion = !lib.hasInfix "\n" import.remotePath && !lib.hasInfix "\r" import.remotePath;
message = "services.minecraft-modpack-imports.${name}.remotePath must not contain newlines";
}
{
assertion = builtins.hasAttr import.serverName minecraftServers
&& (builtins.getAttr import.serverName minecraftServers).enable;
message = "services.minecraft-modpack-imports.${name}.serverName must name an enabled Minecraft server";
}
{
assertion = builtins.match "[A-Za-z0-9._-]+" import.archiveName != null
&& import.archiveName != "."
&& import.archiveName != ".."
&& import.archiveName != "managed-paths";
message = "services.minecraft-modpack-imports.${name}.archiveName must be a file name";
}
{
assertion = lib.length (lib.unique targetServers) == lib.length targetServers;
message = "services.minecraft-modpack-imports: each server target must be unique";
}
]) enabledImports);
users.groups = lib.mapAttrs' (name: _: lib.nameValuePair (importerUser name) { }) enabledImports;
users.users = lib.mapAttrs' (name: _: let
user = importerUser name;
in lib.nameValuePair user {
description = "Minecraft modpack importer ${name}";
isSystemUser = true;
group = user;
extraGroups = [ "minecraft" ];
}) enabledImports;
programs.ssh.knownHosts = lib.mapAttrs' (name: import:
lib.nameValuePair "minecraft-modpack-import-${name}" {
hostNames = [ import.remoteHost ];
publicKey = import.hostPublicKey;
}) enabledImports;
systemd.tmpfiles.rules = lib.flatten (lib.mapAttrsToList (name: import:
lib.optional (!stateDirectoryCompatible import.cacheDir)
"d ${escapeTmpfiles import.cacheDir} 0700 ${importerUser name} ${importerUser name} -") enabledImports);
systemd.services = importerServices;
};
}
+18
View File
@@ -0,0 +1,18 @@
{ pkgs }:
pkgs.linkFarmFromDrvs "create-aeronautics-mods" (
builtins.attrValues {
Sable = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/T9PomCSv/versions/g8CObHcP/sable-neoforge-1.21.1-1.1.3.jar";
sha512 = "8180e214681c171c9e3b7fa307f7a92bd7de0b8125d671291425f04a4ba26b408758d8ea80a6386d8e73bb1e6b02caf3f20afb9b91ecedd48c37ed44363ac961";
};
Create = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/LNytGWDc/versions/UjX6dr61/create-1.21.1-6.0.10.jar";
sha512 = "11cc8fc049d2f67f6548c7abfada6b82a3adb5c7ca410a742de04bbca76e03862c518721b88d806f6e6d768a4d68531fdb903a85859b25d1484d550cc7bafd4b";
};
CreateAeronautics = pkgs.fetchurl {
url = "https://cdn.modrinth.com/data/oWaK0Q19/versions/1sv6OtSz/create-aeronautics-bundled-1.21.1-1.1.3.jar";
sha512 = "94831bc4702b3864524258fa0a73a50ab3cd37e9c157b5c6688a6845b866ec5838452804050b55e490549d91dad909fc37f0d619f354c5676e2e2651b9c15ec6";
};
}
)
@@ -0,0 +1,363 @@
{
"build": {
"version": "21.1.250",
"src": {
"url": "https://maven.neoforged.net/releases/net/neoforged/neoforge/21.1.250/neoforge-21.1.250-installer.jar",
"hash": "sha256-DkepG6ITmo20v3Ynrwgfe1eJtQi7A57o3qEnK3lpPWA="
},
"libraries": [
"net.neoforged.fancymodloader:earlydisplay:4.0.44",
"net.neoforged.fancymodloader:loader:4.0.44",
"net.neoforged.accesstransformers:at-modlauncher:10.0.1",
"net.neoforged:accesstransformers:10.0.1",
"net.neoforged:bus:8.0.5",
"net.neoforged:coremods:7.0.3",
"cpw.mods:modlauncher:11.0.5",
"net.neoforged:mergetool:2.0.0:api",
"com.electronwill.night-config:toml:3.8.3",
"com.electronwill.night-config:core:3.8.3",
"net.neoforged:JarJarSelector:0.4.1",
"net.neoforged:JarJarMetadata:0.4.1",
"org.apache.maven:maven-artifact:3.8.5",
"net.jodah:typetools:0.6.3",
"net.minecrell:terminalconsoleappender:1.3.0",
"net.fabricmc:sponge-mixin:0.15.2+mixin.0.8.7",
"org.openjdk.nashorn:nashorn-core:15.4",
"org.apache.commons:commons-lang3:3.14.0",
"cpw.mods:bootstraplauncher:2.0.2",
"cpw.mods:securejarhandler:3.0.8",
"org.ow2.asm:asm-commons:9.10.1",
"org.ow2.asm:asm-util:9.10.1",
"org.ow2.asm:asm-analysis:9.10.1",
"org.ow2.asm:asm-tree:9.10.1",
"org.ow2.asm:asm:9.10.1",
"net.neoforged:JarJarFileSystems:0.4.1",
"net.sf.jopt-simple:jopt-simple:5.0.4",
"org.slf4j:slf4j-api:2.0.9",
"org.antlr:antlr4-runtime:4.13.1",
"com.mojang:logging:1.2.7",
"org.apache.logging.log4j:log4j-slf4j2-impl:2.22.1",
"org.apache.logging.log4j:log4j-core:2.22.1",
"org.apache.logging.log4j:log4j-api:2.22.1",
"org.jline:jline-reader:3.20.0",
"org.jline:jline-terminal:3.20.0",
"commons-io:commons-io:2.15.1",
"net.minecraftforge:srgutils:0.4.15",
"com.google.guava:guava:32.1.2-jre",
"com.google.guava:failureaccess:1.0.1",
"com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava",
"com.google.code.findbugs:jsr305:3.0.2",
"org.checkerframework:checker-qual:3.33.0",
"com.google.errorprone:error_prone_annotations:2.18.0",
"com.google.j2objc:j2objc-annotations:2.8",
"com.google.code.gson:gson:2.10.1",
"org.codehaus.plexus:plexus-utils:3.3.0",
"com.machinezoo.noexception:noexception:1.7.1",
"net.neoforged:neoform:1.21.1-20240808.144430@zip",
"net.neoforged.installertools:binarypatcher:2.1.2:fatjar",
"net.neoforged:AutoRenamingTool:2.0.3:all",
"net.neoforged.installertools:installertools:2.1.2",
"net.neoforged:srgutils:1.0.0",
"net.md-5:SpecialSource:1.11.0",
"com.google.code.gson:gson:2.8.9",
"de.siegmar:fastcsv:2.0.0",
"org.ow2.asm:asm-commons:9.3",
"net.neoforged.installertools:cli-utils:2.1.2",
"com.google.guava:guava:20.0",
"com.opencsv:opencsv:4.4",
"org.ow2.asm:asm-analysis:9.3",
"org.ow2.asm:asm-tree:9.3",
"org.ow2.asm:asm:9.3",
"org.apache.commons:commons-text:1.3",
"org.apache.commons:commons-lang3:3.8.1",
"commons-beanutils:commons-beanutils:1.9.3",
"org.apache.commons:commons-collections4:4.2",
"commons-logging:commons-logging:1.2",
"commons-collections:commons-collections:3.2.2",
"net.neoforged.installertools:jarsplitter:2.1.2",
"net.neoforged:neoforge:21.1.250:universal"
]
},
"libraryLocks": {
"net.neoforged.fancymodloader:earlydisplay:4.0.44": {
"url": "https://maven.neoforged.net/releases/net/neoforged/fancymodloader/earlydisplay/4.0.44/earlydisplay-4.0.44.jar",
"hash": "sha1-yyr88VZyGA7KHEmxybEgiVHvMi4="
},
"net.neoforged.fancymodloader:loader:4.0.44": {
"url": "https://maven.neoforged.net/releases/net/neoforged/fancymodloader/loader/4.0.44/loader-4.0.44.jar",
"hash": "sha1-Y0M2CLaDAqRC49uoeIDlT0LqBYM="
},
"net.neoforged.accesstransformers:at-modlauncher:10.0.1": {
"url": "https://maven.neoforged.net/releases/net/neoforged/accesstransformers/at-modlauncher/10.0.1/at-modlauncher-10.0.1.jar",
"hash": "sha1-WrpQICrO6tCGvAn7wnUcnwXLSJA="
},
"net.neoforged:accesstransformers:10.0.1": {
"url": "https://maven.neoforged.net/releases/net/neoforged/accesstransformers/10.0.1/accesstransformers-10.0.1.jar",
"hash": "sha1-/YO1cl926ukRXpNV+hxFampEFAA="
},
"net.neoforged:bus:8.0.5": {
"url": "https://maven.neoforged.net/releases/net/neoforged/bus/8.0.5/bus-8.0.5.jar",
"hash": "sha1-Wy0zKFq10VVOl5itmMQNbqOGi9U="
},
"net.neoforged:coremods:7.0.3": {
"url": "https://maven.neoforged.net/releases/net/neoforged/coremods/7.0.3/coremods-7.0.3.jar",
"hash": "sha1-CRR+b2OLQnKzvV/I+SrTeAJRLGw="
},
"cpw.mods:modlauncher:11.0.5": {
"url": "https://maven.neoforged.net/releases/cpw/mods/modlauncher/11.0.5/modlauncher-11.0.5.jar",
"hash": "sha1-uPDUkpT3M/22FzkxsmNVPpQ9yVA="
},
"net.neoforged:mergetool:2.0.0:api": {
"url": "https://maven.neoforged.net/releases/net/neoforged/mergetool/2.0.0/mergetool-2.0.0-api.jar",
"hash": "sha1-Uv4ZSb5k4zA6q6qiHjFfVR25yfQ="
},
"com.electronwill.night-config:toml:3.8.3": {
"url": "https://maven.neoforged.net/releases/com/electronwill/night-config/toml/3.8.3/toml-3.8.3.jar",
"hash": "sha1-kLL9bvy0p9W5gQz3j52CSZTXF/I="
},
"com.electronwill.night-config:core:3.8.3": {
"url": "https://maven.neoforged.net/releases/com/electronwill/night-config/core/3.8.3/core-3.8.3.jar",
"hash": "sha1-tEKpXwnjSZJ/WpRey1lEVYcPz08="
},
"net.neoforged:JarJarSelector:0.4.1": {
"url": "https://maven.neoforged.net/releases/net/neoforged/JarJarSelector/0.4.1/JarJarSelector-0.4.1.jar",
"hash": "sha1-+zzHpYryKtKICtuYr21RgSjEfa4="
},
"net.neoforged:JarJarMetadata:0.4.1": {
"url": "https://maven.neoforged.net/releases/net/neoforged/JarJarMetadata/0.4.1/JarJarMetadata-0.4.1.jar",
"hash": "sha1-+NoDaD3IFpRVbcPhd8Xju3eub8s="
},
"org.apache.maven:maven-artifact:3.8.5": {
"url": "https://maven.neoforged.net/releases/org/apache/maven/maven-artifact/3.8.5/maven-artifact-3.8.5.jar",
"hash": "sha1-RDP1DAfevvrtBVO9AGj09I1EkxM="
},
"net.jodah:typetools:0.6.3": {
"url": "https://maven.neoforged.net/releases/net/jodah/typetools/0.6.3/typetools-0.6.3.jar",
"hash": "sha1-oBqqbdrqnsB+xPIJSHt6RqUmKDo="
},
"net.minecrell:terminalconsoleappender:1.3.0": {
"url": "https://maven.neoforged.net/releases/net/minecrell/terminalconsoleappender/1.3.0/terminalconsoleappender-1.3.0.jar",
"hash": "sha1-tWLpu2EjXJUg4mKCze5x+PgC0fw="
},
"net.fabricmc:sponge-mixin:0.15.2+mixin.0.8.7": {
"url": "https://maven.neoforged.net/releases/net/fabricmc/sponge-mixin/0.15.2+mixin.0.8.7/sponge-mixin-0.15.2+mixin.0.8.7.jar",
"hash": "sha1-KvLwIdjgKgIg3CenpytGZtZtRMo="
},
"org.openjdk.nashorn:nashorn-core:15.4": {
"url": "https://maven.neoforged.net/releases/org/openjdk/nashorn/nashorn-core/15.4/nashorn-core-15.4.jar",
"hash": "sha1-9n9f+qX1Ewz2+5sTPaAMffO1MqU="
},
"org.apache.commons:commons-lang3:3.14.0": {
"url": "https://libraries.minecraft.net/org/apache/commons/commons-lang3/3.14.0/commons-lang3-3.14.0.jar",
"hash": "sha1-HtRxGUsC8sbLc0oM1vbxB8Zzr64="
},
"cpw.mods:bootstraplauncher:2.0.2": {
"url": "https://maven.neoforged.net/releases/cpw/mods/bootstraplauncher/2.0.2/bootstraplauncher-2.0.2.jar",
"hash": "sha1-Gi0HbLwzsFIMus1ZEiRCeyogBH0="
},
"cpw.mods:securejarhandler:3.0.8": {
"url": "https://maven.neoforged.net/releases/cpw/mods/securejarhandler/3.0.8/securejarhandler-3.0.8.jar",
"hash": "sha1-wO+Vzs2GmaBEkFOsfZwWB0jZAs0="
},
"org.ow2.asm:asm-commons:9.10.1": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-commons/9.10.1/asm-commons-9.10.1.jar",
"hash": "sha1-QinkxV/Y4Bwj+f6YhAdcxiiqzFA="
},
"org.ow2.asm:asm-util:9.10.1": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-util/9.10.1/asm-util-9.10.1.jar",
"hash": "sha1-e7nUUOjUy/n54ECWxEu/5/uoCxU="
},
"org.ow2.asm:asm-analysis:9.10.1": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-analysis/9.10.1/asm-analysis-9.10.1.jar",
"hash": "sha1-jUnxTVH2Mssdh8iNHOr1DbDYrxs="
},
"org.ow2.asm:asm-tree:9.10.1": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-tree/9.10.1/asm-tree-9.10.1.jar",
"hash": "sha1-4kQzKhdWTB0VckSTmahC3jWIG+I="
},
"org.ow2.asm:asm:9.10.1": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm/9.10.1/asm-9.10.1.jar",
"hash": "sha1-raIUHAzFLuj1xIzV+kzg55TyIjY="
},
"net.neoforged:JarJarFileSystems:0.4.1": {
"url": "https://maven.neoforged.net/releases/net/neoforged/JarJarFileSystems/0.4.1/JarJarFileSystems-0.4.1.jar",
"hash": "sha1-ePWfid780DLteIsVHKag1ArOeWo="
},
"net.sf.jopt-simple:jopt-simple:5.0.4": {
"url": "https://libraries.minecraft.net/net/sf/jopt-simple/jopt-simple/5.0.4/jopt-simple-5.0.4.jar",
"hash": "sha1-T9rC++kt+thqpukwFzb2tDQqP1w="
},
"org.slf4j:slf4j-api:2.0.9": {
"url": "https://libraries.minecraft.net/org/slf4j/slf4j-api/2.0.9/slf4j-api-2.0.9.jar",
"hash": "sha1-fPJyb9z7yGEPmnH7PtY5hx8xU0A="
},
"org.antlr:antlr4-runtime:4.13.1": {
"url": "https://maven.neoforged.net/releases/org/antlr/antlr4-runtime/4.13.1/antlr4-runtime-4.13.1.jar",
"hash": "sha1-FxJbrh2WViTiZe9JVS9kZaK/owc="
},
"com.mojang:logging:1.2.7": {
"url": "https://libraries.minecraft.net/com/mojang/logging/1.2.7/logging-1.2.7.jar",
"hash": "sha1-JMuV/7DjQz/W6ETATmgAnlBMocA="
},
"org.apache.logging.log4j:log4j-slf4j2-impl:2.22.1": {
"url": "https://libraries.minecraft.net/org/apache/logging/log4j/log4j-slf4j2-impl/2.22.1/log4j-slf4j2-impl-2.22.1.jar",
"hash": "sha1-1+ZpPCYGy35zNQR9e7lt7FLbVmU="
},
"org.apache.logging.log4j:log4j-core:2.22.1": {
"url": "https://libraries.minecraft.net/org/apache/logging/log4j/log4j-core/2.22.1/log4j-core-2.22.1.jar",
"hash": "sha1-cYOiVRCgKtAMxqldOz0qfTxajcQ="
},
"org.apache.logging.log4j:log4j-api:2.22.1": {
"url": "https://libraries.minecraft.net/org/apache/logging/log4j/log4j-api/2.22.1/log4j-api-2.22.1.jar",
"hash": "sha1-vqb+3mMo+rr9fmg2MWGn6mYFq9E="
},
"org.jline:jline-reader:3.20.0": {
"url": "https://maven.neoforged.net/releases/org/jline/jline-reader/3.20.0/jline-reader-3.20.0.jar",
"hash": "sha1-jxVBWwIqJbRz6OFsKK6RMYb/ucQ="
},
"org.jline:jline-terminal:3.20.0": {
"url": "https://maven.neoforged.net/releases/org/jline/jline-terminal/3.20.0/jline-terminal-3.20.0.jar",
"hash": "sha1-0N3McI3fUno0VMlBt7kiXMg6Ff8="
},
"commons-io:commons-io:2.15.1": {
"url": "https://libraries.minecraft.net/commons-io/commons-io/2.15.1/commons-io-2.15.1.jar",
"hash": "sha1-8RVg2hiatWOlyONRlBQVQw6TBOo="
},
"net.minecraftforge:srgutils:0.4.15": {
"url": "https://maven.neoforged.net/releases/net/minecraftforge/srgutils/0.4.15/srgutils-0.4.15.jar",
"hash": "sha1-ykCLExdZR48WTgEPrg1zmX4SX7U="
},
"com.google.guava:guava:32.1.2-jre": {
"url": "https://libraries.minecraft.net/com/google/guava/guava/32.1.2-jre/guava-32.1.2-jre.jar",
"hash": "sha1-XmTsfgVkVr7zpLxMb9rvceirYxg="
},
"com.google.guava:failureaccess:1.0.1": {
"url": "https://libraries.minecraft.net/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar",
"hash": "sha1-Hc8d44Kgv5Wj2LCElUbIi6wSksk="
},
"com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava": {
"url": "https://libraries.minecraft.net/com/google/guava/listenablefuture/9999.0-empty-to-avoid-conflict-with-guava/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar",
"hash": "sha1-tCFSbF8pcpWt7xyIblJGw51Kxik="
},
"com.google.code.findbugs:jsr305:3.0.2": {
"url": "https://libraries.minecraft.net/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar",
"hash": "sha1-JeouiwwziodzE71GctP+BW6njw0="
},
"org.checkerframework:checker-qual:3.33.0": {
"url": "https://libraries.minecraft.net/org/checkerframework/checker-qual/3.33.0/checker-qual-3.33.0.jar",
"hash": "sha1-3itgti2kh2RPwR9zTnPIsLQxI48="
},
"com.google.errorprone:error_prone_annotations:2.18.0": {
"url": "https://libraries.minecraft.net/com/google/errorprone/error_prone_annotations/2.18.0/error_prone_annotations-2.18.0.jar",
"hash": "sha1-ibaEJXCW9Uj6Oaffn9qkCdTU35E="
},
"com.google.j2objc:j2objc-annotations:2.8": {
"url": "https://libraries.minecraft.net/com/google/j2objc/j2objc-annotations/2.8/j2objc-annotations-2.8.jar",
"hash": "sha1-yFJw4wfnuCLxCGuTaJEkuJdo4nM="
},
"com.google.code.gson:gson:2.10.1": {
"url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.10.1/gson-2.10.1.jar",
"hash": "sha1-s63UeNQ4K3jqILFnE5CoWAAv62w="
},
"org.codehaus.plexus:plexus-utils:3.3.0": {
"url": "https://maven.neoforged.net/releases/org/codehaus/plexus/plexus-utils/3.3.0/plexus-utils-3.3.0.jar",
"hash": "sha1-z0O1OR3mI7Nv4GaiESe674LGQCI="
},
"com.machinezoo.noexception:noexception:1.7.1": {
"url": "https://maven.neoforged.net/releases/com/machinezoo/noexception/noexception/1.7.1/noexception-1.7.1.jar",
"hash": "sha1-tlMwyY44ofkV+lSm5eykllBePwo="
},
"net.neoforged:neoform:1.21.1-20240808.144430@zip": {
"url": "https://maven.neoforged.net/releases/net/neoforged/neoform/1.21.1-20240808.144430/neoform-1.21.1-20240808.144430.zip",
"hash": "sha1-gR4r2G+izaKBLl6OUdcY6ovW0/Q="
},
"net.neoforged.installertools:binarypatcher:2.1.2:fatjar": {
"url": "https://maven.neoforged.net/releases/net/neoforged/installertools/binarypatcher/2.1.2/binarypatcher-2.1.2-fatjar.jar",
"hash": "sha1-dZtj7zk+2AQY7B6k0jPNYVLQJjc="
},
"net.neoforged:AutoRenamingTool:2.0.3:all": {
"url": "https://maven.neoforged.net/releases/net/neoforged/AutoRenamingTool/2.0.3/AutoRenamingTool-2.0.3-all.jar",
"hash": "sha1-2YkMcbQ2b4hsKxAGeCBDpqaBbrY="
},
"net.neoforged.installertools:installertools:2.1.2": {
"url": "https://maven.neoforged.net/releases/net/neoforged/installertools/installertools/2.1.2/installertools-2.1.2.jar",
"hash": "sha1-clJMA2L4EtiqTNtMA+m0Xitxrjs="
},
"net.neoforged:srgutils:1.0.0": {
"url": "https://maven.neoforged.net/releases/net/neoforged/srgutils/1.0.0/srgutils-1.0.0.jar",
"hash": "sha1-uf5s2rSUmDIXy8FMxvksjmxhZSY="
},
"net.md-5:SpecialSource:1.11.0": {
"url": "https://maven.neoforged.net/releases/net/md-5/SpecialSource/1.11.0/SpecialSource-1.11.0.jar",
"hash": "sha1-Q7hMS7jQHPkKKd/uwclYpLZLr0Y="
},
"com.google.code.gson:gson:2.8.9": {
"url": "https://libraries.minecraft.net/com/google/code/gson/gson/2.8.9/gson-2.8.9.jar",
"hash": "sha1-ikMsHWgleB4hoC2y4sM8X94oM7k="
},
"de.siegmar:fastcsv:2.0.0": {
"url": "https://maven.neoforged.net/releases/de/siegmar/fastcsv/2.0.0/fastcsv-2.0.0.jar",
"hash": "sha1-thXybAPt6slmYYuTue5PTu1QquE="
},
"org.ow2.asm:asm-commons:9.3": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-commons/9.3/asm-commons-9.3.jar",
"hash": "sha1-HypDLRIS9cNSrmB9e2HcriDCCvU="
},
"net.neoforged.installertools:cli-utils:2.1.2": {
"url": "https://maven.neoforged.net/releases/net/neoforged/installertools/cli-utils/2.1.2/cli-utils-2.1.2.jar",
"hash": "sha1-5aMRXrnimRF0cmdZRr6KcuSZCtY="
},
"com.google.guava:guava:20.0": {
"url": "https://maven.neoforged.net/releases/com/google/guava/guava/20.0/guava-20.0.jar",
"hash": "sha1-iVB3ASSTiOHtXdz4xB9M4b54Me8="
},
"com.opencsv:opencsv:4.4": {
"url": "https://maven.neoforged.net/releases/com/opencsv/opencsv/4.4/opencsv-4.4.jar",
"hash": "sha1-Ulkyoe30bJynWqnIPTHcGAwYaGU="
},
"org.ow2.asm:asm-analysis:9.3": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-analysis/9.3/asm-analysis-9.3.jar",
"hash": "sha1-SwcfIRs3w44On1mYVQGXyFk/atg="
},
"org.ow2.asm:asm-tree:9.3": {
"url": "https://maven.neoforged.net/releases/org/ow2/asm/asm-tree/9.3/asm-tree-9.3.jar",
"hash": "sha1-eNLs1hMYtaWM0E+yN2NsDoa3fZc="
},
"org.ow2.asm:asm:9.3": {
"url": "https://libraries.minecraft.net/org/ow2/asm/asm/9.3/asm-9.3.jar",
"hash": "sha1-jmMA71HB2AGn7WLQfNIhrKOpBkA="
},
"org.apache.commons:commons-text:1.3": {
"url": "https://maven.neoforged.net/releases/org/apache/commons/commons-text/1.3/commons-text-1.3.jar",
"hash": "sha1-mr9hcIpmq15V9haaIA2/xYS1Rtk="
},
"org.apache.commons:commons-lang3:3.8.1": {
"url": "https://maven.neoforged.net/releases/org/apache/commons/commons-lang3/3.8.1/commons-lang3-3.8.1.jar",
"hash": "sha1-ZQWnKgl9knD3qee/QsQjgoMkd1U="
},
"commons-beanutils:commons-beanutils:1.9.3": {
"url": "https://maven.neoforged.net/releases/commons-beanutils/commons-beanutils/1.9.3/commons-beanutils-1.9.3.jar",
"hash": "sha1-yEVwPeM03ca0s80mg1RYyxy6Hz0="
},
"org.apache.commons:commons-collections4:4.2": {
"url": "https://maven.neoforged.net/releases/org/apache/commons/commons-collections4/4.2/commons-collections4-4.2.jar",
"hash": "sha1-VOvqCltlPTxoATHnP+gHu494xO0="
},
"commons-logging:commons-logging:1.2": {
"url": "https://libraries.minecraft.net/commons-logging/commons-logging/1.2/commons-logging-1.2.jar",
"hash": "sha1-S/wSrf5IQr8HtlfwNpxMtSKVVoY="
},
"commons-collections:commons-collections:3.2.2": {
"url": "https://maven.neoforged.net/releases/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar",
"hash": "sha1-itcv45+oyR6q8Sqtsh4MNmH+JtU="
},
"net.neoforged.installertools:jarsplitter:2.1.2": {
"url": "https://maven.neoforged.net/releases/net/neoforged/installertools/jarsplitter/2.1.2/jarsplitter-2.1.2.jar",
"hash": "sha1-inkWvgoOWJiXvqt8g5ByYxBn5I4="
},
"net.neoforged:neoforge:21.1.250:universal": {
"url": "https://maven.neoforged.net/releases/net/neoforged/neoforge/21.1.250/neoforge-21.1.250-universal.jar",
"hash": "sha1-IUxSk8hZmwqq39v6kkU7ojkYohk="
}
}
}
@@ -0,0 +1,49 @@
{ config, pkgs, ... }:
let
mkTunnel = relay: {
description = "WorldOfSosal WoW reverse tunnel to ${relay.name}";
startLimitIntervalSec = 0;
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
serviceConfig = {
User = "mc-wow-tunnel";
Group = "mc-wow-tunnel";
ExecStart = "${pkgs.openssh}/bin/ssh -NT -i ${config.sops.secrets."minecraft/wow-tunnel-key".path} -o IPQoS=none -o Ciphers=aes256-ctr -o MACs=hmac-sha2-256-etm@openssh.com -o KexAlgorithms=curve25519-sha256 -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=/etc/ssh/ssh_known_hosts -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ConnectTimeout=10 -R 127.0.0.1:25577:127.0.0.1:25567 mc-wow-relay@${relay.address}";
Restart = "always";
RestartSec = 10;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
};
};
in {
users.groups.mc-wow-tunnel = { };
users.users.mc-wow-tunnel = {
isSystemUser = true;
group = "mc-wow-tunnel";
};
sops.secrets."minecraft/wow-tunnel-key" = {
sopsFile = ../../../../sus/neuro-minecraft.yaml;
owner = "mc-wow-tunnel";
group = "mc-wow-tunnel";
mode = "0400";
};
programs.ssh.knownHosts.minecraft-wow-relay = {
hostNames = [ "128.140.75.58" ];
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAFpr4DPSaJt0xeuGIfcZBJD3LsJHTdIRIs2Tt9HF+CT";
};
programs.ssh.knownHosts.minecraft-wow-relay-bfs = {
hostNames = [ "91.198.166.181" ];
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICcCn57nlWY5QyEz17kxuAbIX9PkjPwtlGzdJyhy+SQQ";
};
systemd.services.minecraft-wow-tunnel = mkTunnel {
name = "hectic-lab";
address = "128.140.75.58";
};
systemd.services.minecraft-wow-tunnel-bfs = mkTunnel {
name = "bfs.band";
address = "91.198.166.181";
};
}
+18
View File
@@ -0,0 +1,18 @@
{ pkgs, ... }:
{
services.minecraft-servers.servers.vanilla = {
enable = true;
jvmOpts = "-Xmx6G -Xms2G";
package = pkgs.minecraftServers.vanilla-1_21_11;
serverProperties = {
server-port = 25565;
difficulty = "hard";
online-mode = true;
view-distance = 32;
level-seed = "8306359138650378643";
pause-when-empty-seconds = 0;
};
};
}
@@ -0,0 +1,312 @@
{
config,
lib,
pkgs,
...
}: let
inherit (lib) mkOption types;
cfg = config.services.minecraft-world-imports;
enabledImports = lib.filterAttrs (_: import: import.enable) cfg;
dataDir = config.services.minecraft-servers.dataDir;
minecraftServers = config.services.minecraft-servers.servers;
targetPairs = lib.mapAttrsToList (_: import:
"${import.serverName}:${import.worldName}") enabledImports;
importerUser = name: let
descriptiveName = "minecraft-map-import-${name}";
in
if builtins.stringLength descriptiveName <= 31
then descriptiveName
else "mc-import-${builtins.substring 0 12 (builtins.hashString "sha256" name)}";
stateDirectory = cacheDir:
if lib.hasPrefix "/var/lib/" cacheDir
then lib.removePrefix "/var/lib/" cacheDir
else null;
stateDirectoryCompatible = cacheDir: let
relative = stateDirectory cacheDir;
components = lib.splitString "/" (if relative == null then "" else relative);
in
relative != null
&& relative != ""
&& lib.all (component: component != "" && component != "." && component != "..") components;
escapeSftp = value:
"\"${lib.replaceStrings ["\\" "\""] ["\\\\" "\\\""] value}\"";
escapeTmpfiles = value:
lib.replaceStrings ["%" " " "\t"] ["%%" "\\x20" "\\x09"] value;
importerServices = lib.mkMerge (lib.mapAttrsToList (name: import: let
user = importerUser name;
unitName = "minecraft-world-import-${name}";
serverUnit = "minecraft-server-${import.serverName}.service";
cacheStateDirectory = stateDirectory import.cacheDir;
serverDir = "${dataDir}/${import.serverName}";
worldDir = "${serverDir}/${import.worldName}";
in {
${unitName} = {
description = "Import Minecraft world ${name}";
before = [ serverUnit ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
path = [ pkgs.coreutils pkgs.findutils pkgs.openssh pkgs.unar ];
serviceConfig = {
Type = "oneshot";
User = user;
Group = user;
RemainAfterExit = true;
TimeoutStartSec = import.timeoutStartSec;
ProtectSystem = "strict";
ProtectHome = true;
PrivateDevices = true;
PrivateTmp = true;
NoNewPrivileges = true;
CapabilityBoundingSet = [ "" ];
ReadWritePaths = [ import.cacheDir dataDir ];
UMask = "0077";
} // lib.optionalAttrs (stateDirectoryCompatible import.cacheDir) {
StateDirectory = cacheStateDirectory;
};
script = ''
set -eu
umask 077
cache_dir=${lib.escapeShellArg import.cacheDir}
server_dir=${lib.escapeShellArg serverDir}
world_dir=${lib.escapeShellArg worldDir}
archive_name=${lib.escapeShellArg import.archiveName}
world_name=${lib.escapeShellArg import.worldName}
archive="$cache_dir/$archive_name"
temporary_archive="$cache_dir/.$archive_name.$$"
extraction_dir="$cache_dir/.minecraft-world-import-${name}.$$"
staged_world="$server_dir/.$world_name.import.$$"
key=${lib.escapeShellArg import.sshKeyFile}
cleanup() {
rm -f "$temporary_archive"
rm -rf "$extraction_dir" "$staged_world"
}
trap cleanup EXIT
mkdir -p "$cache_dir" "$server_dir"
chmod 0700 "$cache_dir"
# The Minecraft module creates server_dir as minecraft:minecraft
# with group write access; this importer must not chmod another user's directory.
if [ -d "$world_dir" ]; then
if [ -f "$world_dir/level.dat" ]; then
exit 0
fi
echo "Minecraft world directory exists but has no level.dat" >&2
exit 1
fi
if [ ! -f "$archive" ]; then
downloaded=false
attempt=1
while [ "$attempt" -le ${toString import.downloadRetries} ]; do
if sftp \
-o BatchMode=yes \
-o StrictHostKeyChecking=yes \
-o UserKnownHostsFile=/etc/ssh/ssh_known_hosts \
-i "$key" \
-b - \
${lib.escapeShellArg "${import.remoteUser}@${import.remoteHost}"} <<EOF
get ${escapeSftp import.remotePath} "$temporary_archive"
EOF
then
downloaded=true
break
fi
rm -f "$temporary_archive"
sleep ${toString import.retryDelaySeconds}
attempt=$((attempt + 1))
done
if [ "$downloaded" != true ]; then
echo "Unable to download Minecraft world ${name}" >&2
exit 1
fi
mv "$temporary_archive" "$archive"
fi
if ! printf '%s %s\n' \
${lib.escapeShellArg import.archiveSha256} \
"$archive" | sha256sum -c -; then
rm -f "$archive"
echo "Cached Minecraft world ${name} checksum mismatch" >&2
exit 1
fi
mkdir -p "$extraction_dir"
unar -quiet -output-directory "$extraction_dir" "$archive"
find "$extraction_dir" \
\( -type l -o -type b -o -type c -o -type p -o -type s \) \
-delete
world_level_dat=$(find "$extraction_dir" -type f -name level.dat -print -quit)
if [ -z "$world_level_dat" ]; then
echo "Minecraft world archive contains no level.dat" >&2
exit 1
fi
mv "$(dirname "$world_level_dat")" "$staged_world"
chgrp -R minecraft "$staged_world"
chmod -R u+rwX,g+rwX,o-rwx "$staged_world"
mv "$staged_world" "$world_dir"
'';
};
"minecraft-server-${import.serverName}" = {
requires = [ "${unitName}.service" ];
after = [ "${unitName}.service" ];
};
}) enabledImports);
in {
options.services.minecraft-world-imports = mkOption {
default = { };
type = types.attrsOf (types.submodule ({ name, ... }: {
options = {
enable = lib.mkEnableOption "Minecraft world import ${name}";
serverName = mkOption {
type = types.str;
description = "minecraft-servers server receiving imported world";
};
remoteHost = mkOption {
type = types.str;
description = "SSH host serving world archive";
};
remoteUser = mkOption {
type = types.str;
description = "SSH user used to download world archive";
};
remotePath = mkOption {
type = types.str;
description = "Remote path to world archive";
};
archiveName = mkOption {
type = types.str;
description = "Archive file name inside cache directory";
};
cacheDir = mkOption {
type = types.str;
default = "/var/lib/minecraft-world-imports/${name}";
description = "Persistent archive cache directory";
};
archiveSha256 = mkOption {
type = types.strMatching "[0-9a-fA-F]{64}";
description = "Expected SHA-256 digest of world archive";
};
sshKeyFile = mkOption {
type = types.str;
description = "Runtime path to private SSH key";
};
worldName = mkOption {
type = types.str;
default = "world";
description = "World directory name beneath server directory";
};
hostPublicKey = mkOption {
type = types.str;
description = "Pinned SSH host public key";
};
downloadRetries = mkOption {
type = types.ints.positive;
default = 3;
description = "Maximum SFTP download attempts";
};
retryDelaySeconds = mkOption {
type = types.ints.unsigned;
default = 10;
description = "Delay between SFTP download attempts";
};
timeoutStartSec = mkOption {
type = types.str;
default = "30min";
description = "Importer service start timeout";
};
};
}));
description = "Minecraft worlds imported before selected servers start";
};
config = lib.mkIf (enabledImports != { }) {
assertions = lib.flatten (lib.mapAttrsToList (name: import: [
{
assertion = builtins.match "[A-Za-z0-9_-]+" name != null;
message = "services.minecraft-world-imports.${name}: name must contain only letters, digits, underscores, or hyphens";
}
{
assertion = builtins.stringLength name <= 24;
message = "services.minecraft-world-imports.${name}: name must be at most 24 characters";
}
{
assertion = builtins.match "/.*" import.cacheDir != null;
message = "services.minecraft-world-imports.${name}.cacheDir must be absolute";
}
{
assertion = builtins.match "[A-Za-z0-9_-]+" import.serverName != null;
message = "services.minecraft-world-imports.${name}.serverName must contain only letters, digits, underscores, or hyphens";
}
{
assertion = !lib.hasInfix "\n" import.remotePath && !lib.hasInfix "\r" import.remotePath;
message = "services.minecraft-world-imports.${name}.remotePath must not contain newlines";
}
{
assertion = builtins.hasAttr import.serverName minecraftServers
&& (builtins.getAttr import.serverName minecraftServers).enable;
message = "services.minecraft-world-imports.${name}.serverName must name an enabled Minecraft server";
}
{
assertion = lib.length (lib.unique targetPairs) == lib.length targetPairs;
message = "services.minecraft-world-imports: each server/world target must be unique";
}
{
assertion = builtins.match "[^/]+" import.archiveName != null;
message = "services.minecraft-world-imports.${name}.archiveName must be a file name";
}
{
assertion = builtins.match "[^/]+" import.worldName != null;
message = "services.minecraft-world-imports.${name}.worldName must be a directory name";
}
]) enabledImports);
users.groups = lib.mapAttrs' (name: _: lib.nameValuePair (importerUser name) { }) enabledImports;
users.users = lib.mapAttrs' (name: _: let
user = importerUser name;
in lib.nameValuePair user {
description = "Minecraft world importer ${name}";
isSystemUser = true;
group = user;
extraGroups = [ "minecraft" ];
}) enabledImports;
programs.ssh.knownHosts = lib.mapAttrs' (name: import:
lib.nameValuePair "minecraft-world-import-${name}" {
hostNames = [ import.remoteHost ];
publicKey = import.hostPublicKey;
}) enabledImports;
systemd.tmpfiles.rules = lib.flatten (lib.mapAttrsToList (name: import:
lib.optional (!stateDirectoryCompatible import.cacheDir)
"d ${escapeTmpfiles import.cacheDir} 0700 ${importerUser name} ${importerUser name} -") enabledImports);
systemd.services = importerServices;
};
}
@@ -0,0 +1,33 @@
{ config, ... }:
{
sops.secrets."minecraft/storage-box-pack-key" = {
sopsFile = ../../../../sus/neuro-minecraft.yaml;
owner = "mc-pack-worldOfSosal";
group = "mc-pack-worldOfSosal";
mode = "0400";
};
services.minecraft-modpack-imports.worldOfSosal = {
enable = true;
serverName = "wowMineMap";
remoteHost = "u664722.your-storagebox.de";
remoteUser = "u664722";
remotePath = "minecraft/pack/WorldOfSosal-v3.mrpack";
archiveName = "WorldOfSosal.mrpack";
cacheDir = "/var/lib/minecraft-modpacks/worldOfSosal";
archiveSha256 = "f97cf251b14f40590e97e7b39e8a8ec43dacfce6da1b02357d15e0eee10d3ade";
expectedDependencies = {
minecraft = "1.21.1";
neoforge = "21.1.250";
};
sshKeyFile = config.sops.secrets."minecraft/storage-box-pack-key".path;
hostPublicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5EB5p/5Hp3hGW1oHok+PIOH9Pbn7cnUiGmUEBrCVjnAw+HrKyN8bYVV0dIGllswYXwkG/+bgiBlE6IVIBAq+JwVWu1Sss3KarHY3OvFJUXZoZyRRg/Gc/+LRCE7lyKpwWQ70dbelGRyyJFH36eNv6ySXoUYtGkwlU5IVaHPApOxe4LHPZa/qhSRbPo2hwoh0orCtgejRebNtW5nlx00DNFgsvn8Svz2cIYLxsPVzKgUxs8Zxsxgn+Q/UvR7uq4AbAhyBMLxv7DjJ1pc7PJocuTno2Rw9uMZi1gkjbnmiOh6TTXIEWbnroyIhwc8555uto9melEUmWNQ+C+PwAK+MPw==";
};
# Import the map before writing modpack configuration into the same server.
systemd.services.minecraft-modpack-import-worldOfSosal = {
after = [ "minecraft-world-import-wowMineMap.service" ];
requires = [ "minecraft-world-import-wowMineMap.service" ];
};
}
@@ -0,0 +1,65 @@
{ config, pkgs, ... }:
{
sops.secrets."minecraft/storage-box-key" = {
sopsFile = ../../../../sus/neuro-minecraft.yaml;
owner = "minecraft-map-import-wowMineMap";
group = "minecraft-map-import-wowMineMap";
mode = "0400";
};
services.minecraft-world-imports.wowMineMap = {
enable = true;
serverName = "wowMineMap";
remoteHost = "u664722.your-storagebox.de";
remoteUser = "u664722";
remotePath = "minecraft/map/wow mine map.rar";
archiveName = "wow mine map.rar";
cacheDir = "/var/lib/minecraft-maps";
archiveSha256 = "bc80084de10a06b0fc2cb1651c61936b9e2fd2288f3f0fe44c964d83a393aa30";
sshKeyFile = config.sops.secrets."minecraft/storage-box-key".path;
worldName = "world";
hostPublicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5EB5p/5Hp3hGW1oHok+PIOH9Pbn7cnUiGmUEBrCVjnAw+HrKyN8bYVV0dIGllswYXwkG/+bgiBlE6IVIBAq+JwVWu1Sss3KarHY3OvFJUXZoZyRRg/Gc/+LRCE7lyKpwWQ70dbelGRyyJFH36eNv6ySXoUYtGkwlU5IVaHPApOxe4LHPZa/qhSRbPo2hwoh0orCtgejRebNtW5nlx00DNFgsvn8Svz2cIYLxsPVzKgUxs8Zxsxgn+Q/UvR7uq4AbAhyBMLxv7DjJ1pc7PJocuTno2Rw9uMZi1gkjbnmiOh6TTXIEWbnroyIhwc8555uto9melEUmWNQ+C+PwAK+MPw==";
};
sops.secrets."minecraft/rcon-password" = {
sopsFile = ../../../../sus/neuro-minecraft.yaml;
owner = "minecraft";
group = "minecraft";
mode = "0400";
restartUnits = [ "minecraft-server-wowMineMap.service" ];
};
# The module's automatic firewall would also expose RCON.
networking.firewall.allowedTCPPorts = [ 25567 ];
services.minecraft-servers.servers.wowMineMap = {
openFirewall = false;
extraStartPre = ''
chmod 600 server.properties
{
printf '\nrcon.password='
cat ${config.sops.secrets."minecraft/rcon-password".path}
printf '\n'
} >> server.properties
'';
enable = true;
jvmOpts = "-Xmx24G -Xms2G";
# WorldOfSosal client and server use the same pinned NeoForge.
package = pkgs.minecraftServers.neoforge-1_21_1.override (
builtins.fromJSON (builtins.readFile ./neoforge-21.1.250.json)
);
serverProperties = {
server-port = 25567;
difficulty = "hard";
online-mode = false;
enable-rcon = true;
"rcon.port" = 25575;
view-distance = 12;
simulation-distance = 8;
motd = "WorldOfSosal — World of Warcraft";
level-name = "world";
pause-when-empty-seconds = 0;
};
};
}
+78 -5
View File
@@ -24,11 +24,11 @@
ollamaPrebuilt = pkgs.stdenvNoCC.mkDerivation {
pname = "ollama";
version = "0.22.1";
version = "0.24.0";
src = pkgs.fetchurl {
url = "https://github.com/ollama/ollama/releases/download/v0.22.1/ollama-linux-amd64.tar.zst";
hash = "sha256-4nwP6PYKgkFi+Bzge0v9p2fc5PNX12LhSbPQ3gq62fs=";
url = "https://github.com/ollama/ollama/releases/download/v0.24.0/ollama-linux-amd64.tar.zst";
hash = "sha256-FcX41mugbg07RxnfiGhhLb1m4U6CdgkpuzVS4WV83Ns=";
};
nativeBuildInputs = [
@@ -70,7 +70,7 @@ in {
imports = [
self.nixosModules.hectic
inputs.sops-nix.nixosModules.sops
./minecraft.nix
./minecraft
./hardware.nix
];
@@ -139,7 +139,7 @@ in {
};
services.nginx = {
enable = true;
enable = false;
virtualHosts."bfs.band" = let
site = pkgs.runCommand "bfs-band-site" {} ''
mkdir -p $out
@@ -194,6 +194,13 @@ in {
openFirewall = false;
};
hectic.services.dify = {
enable = true;
environmentFile = config.sops.secrets."dify/environment".path;
port = 8080;
pluginPort = 5003;
};
networking = {
networkmanager.enable = true;
useDHCP = lib.mkDefault true;
@@ -217,6 +224,70 @@ in {
archetype.dev.enable = true;
};
hectic.services."project-zomboid" = {
enable = true;
memory = "8g";
serverName = "servertest";
serverPropertiesFile = /var/lib/project-zomboid/server-password.ini;
serverProperties = {
Map = "Muldraugh, KY";
DoLuaChecksum = false;
Public = true;
AntiCheatSafety = 4;
AntiCheatMovement = 4;
AntiCheatSpeed = 4;
AntiCheatHit = 4;
AntiCheatPacket = 4;
AntiCheatPacketException = 4;
AntiCheatPermission = 4;
AntiCheatXP = 4;
AntiCheatFire = 4;
AntiCheatSafeHouse = 4;
AntiCheatRecipe = 4;
AntiCheatPlayer = 4;
AntiCheatChecksum = 4;
AntiCheatItem = 4;
AntiCheatNoClip = 4;
AntiCheatServerCustomization = 4;
};
workshopItems = [
"3676456221" # Lua Digital Watch Framework
"3600401184" # Realistic Temperature Mod
];
mods = [
"\\LuaDigitalWatchUI"
"\\RC_RealisticColdMod"
];
sandboxProperties = {
Zombies = 6;
ZombieConfig = {
PopulationMultiplier = 0.0;
PopulationStartMultiplier = 0.0;
PopulationPeakMultiplier = 0.0;
RespawnHours = 0.0;
RespawnUnseenHours = 0.0;
RespawnMultiplier = 0.0;
RedistributeHours = 0.0;
};
};
};
systemd.services.project-zomboid.preStart = lib.mkBefore ''
password_file=${lib.escapeShellArg "/var/lib/project-zomboid/server-password"}
properties_file=${lib.escapeShellArg "/var/lib/project-zomboid/server-password.ini"}
if [ ! -s "$password_file" ] || ! ${pkgs.gnugrep}/bin/grep -Eq '^[0-9a-f]{48}$' "$password_file"; then
umask 077
${pkgs.openssl}/bin/openssl rand -hex 24 > "$password_file"
fi
${pkgs.coreutils}/bin/chmod 0600 "$password_file"
properties_file_tmp="$( ${pkgs.coreutils}/bin/mktemp "$(dirname "$properties_file")/.server-password.ini.XXXXXX")"
${pkgs.coreutils}/bin/printf 'Password=%s\n' "$(<"$password_file")" > "$properties_file_tmp"
${pkgs.coreutils}/bin/chmod 0600 "$properties_file_tmp"
${pkgs.coreutils}/bin/mv "$properties_file_tmp" "$properties_file"
'';
sops = {
gnupg.sshKeyPaths = [ ];
age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];
@@ -229,6 +300,7 @@ in {
# group = "turnserver";
# mode = "0400";
#};
secrets."dify/environment" = {};
};
boot.loader.systemd-boot.enable = true;
@@ -281,6 +353,7 @@ in {
in [
#python-ai
git
hectic.git-lfs-transfer
hectic.hiddify-core
neovim
wget
+14
View File
@@ -6,6 +6,20 @@ in final: prev: (
legacyPackages = self.legacyPackages.${prev.stdenv.hostPlatform.system};
in {
hectic = packages // legacyPackages;
p4d = if final.stdenv.hostPlatform.system == "x86_64-linux" then prev.p4d.overrideAttrs (_: {
version = "2023.1/2797325";
src = final.fetchurl {
url = "https://ftp.perforce.com/pub/perforce/r23.1/bin.linux26x86_64/helix-core-server.tgz";
hash = "sha256-O8znAlq2XjrixG0FA4cfkgcI9t/w9QMHV0spUjYKl48=";
};
}) else prev.p4d;
p4 = prev.p4.overrideAttrs (_: {
version = "2024.1/3006289";
src = final.fetchurl {
url = "https://ftp.perforce.com/pub/perforce/r24.1/bin.tools/p4source.tgz";
hash = "sha256-z3I3cikbbSrmS7dUMMKi6edPnZk2BYAmdO+pfYRJUVQ=";
};
});
postgresql_17 = prev.postgresql_17 // {pkgs = prev.postgresql_17.pkgs // {
http = packages.pg-17-ext-http;
pg_smtp_client = packages.pg-17-ext-smtp-client;
+3 -2
View File
@@ -919,7 +919,7 @@ subcommand_normalize_backup() {
NORMALIZE_DATABASE="${PG_DATABASE:-testdb}"
NORMALIZE_ADMIN_ROLE="postgres"
NORMALIZE_PORT="${PG_PORT:-5432}"
NORMALIZE_PRELOAD_LIBRARIES="${PG_SHARED_PRELOAD_LIBRARIES:-pg_cron}"
NORMALIZE_PRELOAD_LIBRARIES="${PG_SHARED_PRELOAD_LIBRARIES-pg_cron}"
NORMALIZE_DATABASE_EXPLICIT=0
while [ $# -gt 0 ]; do
@@ -1060,7 +1060,8 @@ EOF
log notice "starting temporary local cluster"
with_closed_fds pg_ctl -D "$NORMALIZE_PGDATA" -o "-F" -w start > "$NORMALIZE_LOG" 2>&1 || {
log error "normalize-backup: failed to start temporary cluster; see $NORMALIZE_LOG"
cat "$NORMALIZE_LOG" >&2
log error "normalize-backup: failed to start temporary cluster"
exit 1
}
+11 -10
View File
@@ -16,16 +16,16 @@ let
"errexit"
"nounset"
];
excludeShellChecks = [ "SC2209" ];
excludeShellChecks = [ "SC1091" "SC2209" ];
name = "database";
runtimeInputs = [ hectic.migrator hectic.parse-uri postgresql neovim openssh coreutils gawk ];
text = ''
${builtins.readFile hectic.helpers.posix-shell.log}
${builtins.readFile hectic.helpers.posix-shell.change_namespace}
${builtins.readFile hectic.helpers.posix-shell.quote}
${builtins.readFile hectic.helpers.posix-shell.pager_or_cat}
${builtins.readFile hectic.helpers.posix-shell.with_closed_fds}
. ${hectic.helpers.posix-shell.log}
. ${hectic.helpers.posix-shell.change_namespace}
. ${hectic.helpers.posix-shell.quote}
. ${hectic.helpers.posix-shell.pager_or_cat}
. ${hectic.helpers.posix-shell.with_closed_fds}
${applyBundle}
${builtins.readFile ./db-dev.sh}
'';
@@ -44,13 +44,13 @@ let
"errexit"
"nounset"
];
excludeShellChecks = [ "SC2209" ];
excludeShellChecks = [ "SC1091" "SC2209" ];
name = "db-ops";
runtimeInputs = [ postgresql coreutils ];
text = ''
${builtins.readFile hectic.helpers.posix-shell.log}
${builtins.readFile hectic.helpers.posix-shell.change_namespace}
. ${hectic.helpers.posix-shell.log}
. ${hectic.helpers.posix-shell.change_namespace}
${applyBundle}
${builtins.readFile ./db-ops.sh}
'';
@@ -66,11 +66,12 @@ let
hectic.writeShellApplication {
inherit shell;
bashOptions = [ ];
excludeShellChecks = [ "SC1091" ];
name = "postgres-init";
runtimeInputs = [ postgresql coreutils ];
text = ''
${builtins.readFile hectic.helpers.posix-shell.with_closed_fds}
. ${hectic.helpers.posix-shell.with_closed_fds}
${builtins.readFile ./postgres-init.sh}
'';
+17 -13
View File
@@ -1,4 +1,8 @@
{ self, pkgs, inputs, ... }: let
{ self, pkgs, inputs, system, ... }: let
giteaPkgs = import inputs.nixpkgs-gitea {
inherit system;
config = pkgs.config;
};
rust = {
nativeBuildInputs = [
pkgs.pkgsBuildHost.rust-bin.stable."1.81.0".default
@@ -10,15 +14,9 @@
};
};
buildPostgresqlExtension =
pkgs: pkgs.callPackage (import (builtins.path {
name = "extension-builder";
path = ./buildPostgresqlExtension.nix;
}));
pkgs: pkgs.callPackage ./buildPostgresqlExtension.nix;
buildPgrxExtension = pkgs:
pkgs.callPackage (import (builtins.path {
name = "extension-builder";
path = ./buildPgrxExtension.nix;
})) {
pkgs.callPackage ./buildPgrxExtension.nix {
cargo-pgrx = pkgs.cargo-pgrx_0_12_6;
inherit (pkgs.darwin.apple_sdk.frameworks) Security;
};
@@ -31,11 +29,10 @@
rev = "6ff3b71e3705e0d4081a51c21ca0379e869ba5fb";
hash = "sha256-wC/2rAsSDO83UITaFhtaf3do3aaOAko4gnKUOzwURc8=";
};
cargo = self.lib.cargoToml src;
in
buildPgrxExtension pkgs {
pname = cargo.package.name;
version = cargo.package.version;
pname = "pg_smtp_client";
version = "0.2.0";
inherit src postgresql;
@@ -142,13 +139,18 @@ in {
c-hectic = pkgs.callPackage ./c/hectic/default.nix {};
watch = pkgs.callPackage ./c/watch/default.nix {};
support-bot = pkgs.callPackage ./support-bot {};
gitea-heatmap = pkgs.callPackage ./gitea {};
gitea-heatmap = giteaPkgs.callPackage ./gitea {
nixosTests = pkgs.nixosTests;
};
gitea-runner-nix-image = pkgs.callPackage ./gitea-runner-nix-image {};
gitea-runner-controller = pkgs.callPackage ./gitea-runner-controller {};
git-lfs-transfer = pkgs.callPackage ./git-lfs-transfer {};
nix-derivation-hash = pkgs.callPackage ./nix-derivation-hash {};
"sentinèlla" = pkgs.callPackage (./. + "/sentinèlla") {};
deploy = pkgs.callPackage ./deploy { inherit inputs; };
element-web = pkgs.callPackage ./element-web {};
shellplot = pkgs.callPackage ./shellplot {};
gitea-kanban-tui = pkgs.callPackage ./gitea-kanban-tui rust.commonArgs;
which-country-rs = pkgs.callPackage ./which-country-rs {};
onlinepubs2man = pkgs.callPackage ./onlinepubs2man {};
migrator = pkgs.callPackage ./migrator { inherit self; };
@@ -178,4 +180,6 @@ in {
pg-15-ext-plsh = buildPlShExt pkgs "15";
stable-video-diffusion-api = pkgs.callPackage ./stable-video-diffusion-api {};
media-browser = pkgs.callPackage ./media-browser {};
} // pkgs.lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux {
with-attic-cache = pkgs.callPackage ./with-attic-cache {};
}
+4 -2
View File
@@ -1,4 +1,4 @@
{ inputs, symlinkJoin, dash, hectic, ssh-to-age, stdenv }:
{ inputs, symlinkJoin, dash, hectic, ssh-to-age, nixos-rebuild, stdenv }:
let
shell = "${dash}/bin/dash";
bashOptions = [
@@ -8,14 +8,16 @@ let
deploy = hectic.writeShellApplication {
inherit shell bashOptions;
excludeShellChecks = [ "SC1091" "SC2034" ];
name = "deploy";
runtimeInputs = [
ssh-to-age
nixos-rebuild
inputs.nixos-anywhere.packages.${stdenv.hostPlatform.system}.nixos-anywhere
];
text = ''
${builtins.readFile hectic.helpers.posix-shell.log}
. ${hectic.helpers.posix-shell.log}
${builtins.readFile ./deploy.sh}
'';
};
+9 -2
View File
@@ -7,8 +7,15 @@ HECTIC_NAMESPACE="deploy"
# ssh that not saves the host in ~/.ssh/know_hosts
puressh() {
# shellcheck disable=SC2068
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null $@
local known_hosts="${HECTIC_DEPLOY_KNOWN_HOSTS:-$HOME/.ssh/known_hosts}"
local identity_file="${HECTIC_DEPLOY_IDENTITY_FILE:-$HOME/.ssh/id_ed25519}"
local ssh_config="${HECTIC_DEPLOY_SSH_CONFIG:-}"
if [ -n "$ssh_config" ]; then
set -- -F "$ssh_config" "$@"
fi
ssh -o BatchMode=yes -o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$known_hosts" -o IdentitiesOnly=yes \
-i "$identity_file" "$@"
}
# echo <gens_list> | find_older_gen(gen)
+25
View File
@@ -0,0 +1,25 @@
{
buildGoModule,
fetchFromGitHub,
lib,
}:
buildGoModule {
pname = "git-lfs-transfer";
version = "0.1.0";
src = fetchFromGitHub {
owner = "charmbracelet";
repo = "git-lfs-transfer";
rev = "063daea1437ee33d549da76f9405fac344038e36";
hash = "sha256-4AwWxcWKetPE9VUsfnQggLZKRDBzxPx0kYyTlej+VOg=";
};
vendorHash = "sha256-dgT/AUQn6IxdxmolCKhmNyCX2DstvKMw4168UU4zlnI=";
meta = {
description = "SSH server for Git LFS transfers";
homepage = "https://github.com/charmbracelet/git-lfs-transfer";
license = lib.licenses.mit;
mainProgram = "git-lfs-transfer";
};
}
+1453
View File
File diff suppressed because it is too large Load Diff
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "gitea-kanban-tui"
version = "0.1.0"
edition = "2021"
description = "Native-project Gitea Kanban terminal interface"
license = "MIT"
[dependencies]
clap = { version = "=4.5.20", features = ["derive"] }
crossterm = "=0.28.1"
encoding_rs = "=0.8.35"
indexmap = "=2.6.0"
instability = "=0.3.2"
ratatui = "=0.29.0"
reqwest = { version = "=0.11.27", default-features = false, features = ["blocking", "json", "rustls-tls"] }
serde = { version = "=1.0.210", features = ["derive"] }
serde_json = "=1.0.128"
unicode-segmentation = "=1.12.0"
url = "=2.5.2"
+89
View File
@@ -0,0 +1,89 @@
# gitea-kanban
Native Projects Kanban tools for custom Gitea fork. `gitea-kanban-tui` provides
the keyboard interface; `gitea-kanban` provides the command-line interface.
## Configuration
Required configuration can come from flags or environment variables:
| Flag | Environment | Meaning |
| --- | --- | --- |
| `--url` | `GITEA_URL` | Gitea base URL |
| `--token-file` | `GITEA_TOKEN_FILE` | File containing API token |
| — | `GITEA_TOKEN` | API token fallback when no token file is configured |
| `--project` | `GITEA_PROJECT` | Exact native project name |
| `--project-id` | `GITEA_PROJECT_ID` | Native project ID instead of name |
| positional `OWNER` | `GITEA_OWNER` | Repository owner |
| positional `REPO` | `GITEA_REPO` | Repository name |
Native mode requires an enabled repository Projects unit, project read/write
repository permission, and a token with `read:issue`/`write:issue` scope. Issue
creation/editing follows Gitea issue permissions; deletion requires repository
admin permission in this fork. Token values are sent
only through Gitea's `Authorization` header and are never printed. Token-file
input takes precedence over environment variables. Remote URLs must use HTTPS; plain HTTP is
accepted only for loopback development.
```sh
export GITEA_URL=https://gitea.hectic-lab.com
export GITEA_TOKEN_FILE="$HOME/.config/gitea/token"
cargo run --manifest-path package/gitea-kanban-tui/Cargo.toml --bin gitea-kanban-tui -- \
--project Kanban yukkop util.nix
```
Alternatively:
```sh
nix develop .#ratatui
cargo run --manifest-path package/gitea-kanban-tui/Cargo.toml --bin gitea-kanban-tui -- \
--project-id 1 owner repo
```
## Keys
- Arrow keys or `h`/`j`/`k`/`l`: focus column/card
- `H`/`L`: move focused card left/right
- `r`: refresh project columns and issues
- `?`: toggle help
- `q`: quit
## CLI
Both binaries use same configuration and API client. CLI commands:
```sh
gitea-kanban --project Kanban owner repo board
gitea-kanban --project Kanban owner repo create --title "Fix issue" --body "Details"
gitea-kanban --project Kanban owner repo edit 42 --title "Updated" --body "Changed"
gitea-kanban --project Kanban owner repo move 123 --column-id 7
gitea-kanban --project Kanban owner repo delete 42 --yes
gitea-kanban --project Kanban owner repo comment list 42
gitea-kanban --project Kanban owner repo comment add 42 --body "Investigating"
gitea-kanban --project Kanban owner repo comment edit 42 9001 --body "Resolved"
gitea-kanban --project Kanban owner repo comment delete 42 9001 --yes
```
`delete` requires repository admin permission. `move` takes global issue and
project-column IDs.
Native mode reads `/projects`, project columns, and each column's issues. Moves
use the issue's global API `id` and destination column `id`; optional sorting is
supported by the server API. Project names are exact, case-sensitive matches;
use `--project-id` when duplicate names exist. Empty native boards render
normally. `n` creates an issue assigned to the selected project, `e` edits the
focused issue title/body, and `d` deletes it after confirmation. In the editor,
`Enter` switches from title to body, `Tab` switches fields, `Ctrl-S` saves, and
`Esc` cancels. Closed projects, archived repositories, disabled Projects units,
unassigned issues, and cross-repository IDs are rejected by the server.
## Development
```sh
nix develop .#ratatui
cargo fmt --manifest-path package/gitea-kanban-tui/Cargo.toml -- --check
cargo clippy --manifest-path package/gitea-kanban-tui/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path package/gitea-kanban-tui/Cargo.toml
nix build .#gitea-kanban-tui
```
+32
View File
@@ -0,0 +1,32 @@
{
cargoToml,
lib,
nativeBuildInputs,
pkgs,
...
}: let
cargo = cargoToml ./Cargo.toml;
in
pkgs.rustPlatform.buildRustPackage {
pname = cargo.package.name;
version = cargo.package.version;
src = ./.;
inherit nativeBuildInputs;
cargoLock.lockFile = ./Cargo.lock;
doCheck = true;
postBuild = ''
cargo build --release --offline --bin gitea-kanban
'';
postInstall = ''
install -Dm755 target/*/release/gitea-kanban $out/bin/gitea-kanban
'';
meta = {
description = cargo.package.description;
license = lib.licenses.mit;
mainProgram = "gitea-kanban-tui";
};
}
+623
View File
@@ -0,0 +1,623 @@
use std::fmt;
use std::net::IpAddr;
use std::time::Duration;
use reqwest::blocking::{Client, Response};
use reqwest::redirect::Policy;
use reqwest::{StatusCode, Url};
use serde::de::DeserializeOwned;
use crate::config::Config;
use crate::model::{
Comment, CommentPayload, CreateIssuePayload, EditIssuePayload, Issue, MoveProjectIssuePayload,
Project, ProjectBoard, ProjectColumn,
};
pub trait GiteaApi {
fn list_projects(&self) -> Result<Vec<Project>, ApiError>;
fn list_project_columns(&self, project_id: u64) -> Result<Vec<ProjectColumn>, ApiError>;
fn list_project_column_issues(
&self,
project_id: u64,
column_id: u64,
) -> Result<Vec<Issue>, ApiError>;
fn move_project_issue(
&self,
project_id: u64,
issue_id: u64,
payload: &MoveProjectIssuePayload,
) -> Result<(), ApiError>;
fn create_issue(&self, payload: &CreateIssuePayload) -> Result<Issue, ApiError>;
fn edit_issue(&self, issue_number: u64, payload: &EditIssuePayload) -> Result<Issue, ApiError>;
fn delete_issue(&self, issue_number: u64) -> Result<(), ApiError>;
fn list_issue_comments(&self, issue_number: u64) -> Result<Vec<Comment>, ApiError>;
fn create_issue_comment(&self, issue_number: u64, body: String) -> Result<Comment, ApiError>;
fn edit_issue_comment(&self, comment_id: u64, body: String) -> Result<Comment, ApiError>;
fn delete_issue_comment(&self, comment_id: u64) -> Result<(), ApiError>;
}
pub struct GiteaClient {
client: Client,
api_base: Url,
token: String,
}
#[derive(Debug)]
pub struct ApiError(String);
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ApiError {}
pub fn resolve_project(
projects: &[Project],
project_name: Option<&str>,
project_id: Option<u64>,
) -> Result<Project, ApiError> {
if let Some(id) = project_id {
return projects
.iter()
.find(|project| project.id == id)
.cloned()
.ok_or_else(|| ApiError(format!("project ID {id} was not found in this repository")));
}
let name = project_name.ok_or_else(|| ApiError("project selector is missing".to_owned()))?;
let matches = projects
.iter()
.filter(|project| project.title == name)
.cloned()
.collect::<Vec<_>>();
match matches.as_slice() {
[project] => Ok(project.clone()),
[] => Err(ApiError(format!(
"project named '{name}' was not found; names are matched exactly"
))),
_ => Err(ApiError(format!(
"multiple projects are named '{name}'; use --project-id"
))),
}
}
pub fn load_project_board(
client: &impl GiteaApi,
config: &Config,
) -> Result<ProjectBoard, ApiError> {
let projects = client.list_projects()?;
let project = resolve_project(&projects, config.project.as_deref(), config.project_id)?;
let columns = client.list_project_columns(project.id)?;
let issues_by_column = columns
.iter()
.map(|column| client.list_project_column_issues(project.id, column.id))
.collect::<Result<Vec<_>, _>>()?;
Ok(ProjectBoard {
project,
columns,
issues_by_column,
})
}
impl GiteaClient {
pub fn new(config: &Config) -> Result<Self, ApiError> {
let mut api_base = Url::parse(&config.base_url)
.map_err(|error| ApiError(format!("invalid Gitea URL: {error}")))?;
if !api_base.username().is_empty() || api_base.password().is_some() {
return Err(ApiError(
"Gitea URL must not contain embedded username or password".to_owned(),
));
}
require_secure_transport(&api_base)?;
api_base.set_query(None);
api_base.set_fragment(None);
api_base
.path_segments_mut()
.map_err(|_| ApiError("Gitea URL cannot be used as an API base".to_owned()))?
.pop_if_empty()
.extend(["api", "v1", "repos", &config.owner, &config.repo]);
let client = Client::builder()
.timeout(Duration::from_secs(20))
.redirect(Policy::none())
.user_agent(concat!("gitea-kanban-tui/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|error| ApiError(format!("cannot create HTTP client: {error}")))?;
Ok(Self {
client,
api_base,
token: config.token.clone(),
})
}
fn endpoint(&self, path: &str) -> Result<Url, ApiError> {
let mut url = self.api_base.clone();
url.path_segments_mut()
.map_err(|_| ApiError("Gitea URL cannot contain API paths".to_owned()))?
.extend(path.split('/').filter(|part| !part.is_empty()));
Ok(url)
}
fn decode<T: DeserializeOwned>(
&self,
response: Response,
operation: &str,
) -> Result<T, ApiError> {
let response = check_response(response, operation)?;
response.json().map_err(|error| {
ApiError(format!(
"Gitea returned invalid JSON while {operation}: {error}"
))
})
}
fn get_all<T: DeserializeOwned>(
&self,
path: &str,
operation: &str,
query: &[(&str, &str)],
) -> Result<Vec<T>, ApiError> {
let mut items = Vec::new();
for page in 1..=10_000_u32 {
let page_value = page.to_string();
let mut page_query = query.to_vec();
page_query.extend([("limit", "100"), ("page", page_value.as_str())]);
let response = self
.client
.get(self.endpoint(path)?)
.query(&page_query)
.header("Authorization", format!("token {}", self.token))
.send()
.map_err(|error| {
ApiError(format!("cannot reach Gitea while {operation}: {error}"))
})?;
let total_count = response
.headers()
.get("x-total-count")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok());
let page_items: Vec<T> = self.decode(response, operation)?;
if page_items.is_empty() {
return Ok(items);
}
items.extend(page_items);
if total_count.is_some_and(|total| items.len() >= total) {
return Ok(items);
}
}
Err(ApiError(format!(
"Gitea returned too many pages while {operation}; narrow repository data or check server pagination"
)))
}
}
impl GiteaApi for GiteaClient {
fn list_projects(&self) -> Result<Vec<Project>, ApiError> {
self.get_all(
"projects",
"listing repository projects",
&[("state", "all")],
)
}
fn list_project_columns(&self, project_id: u64) -> Result<Vec<ProjectColumn>, ApiError> {
let response = self
.client
.get(self.endpoint(&format!("projects/{project_id}/columns"))?)
.header("Authorization", format!("token {}", self.token))
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while listing project columns: {error}"
))
})?;
self.decode(response, "listing project columns")
}
fn list_project_column_issues(
&self,
project_id: u64,
column_id: u64,
) -> Result<Vec<Issue>, ApiError> {
self.get_all(
&format!("projects/{project_id}/columns/{column_id}/issues"),
"listing project issues",
&[],
)
}
fn move_project_issue(
&self,
project_id: u64,
issue_id: u64,
payload: &MoveProjectIssuePayload,
) -> Result<(), ApiError> {
let response = self
.client
.post(self.endpoint(&format!("projects/{project_id}/issues/{issue_id}/move"))?)
.header("Authorization", format!("token {}", self.token))
.json(payload)
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while moving project issue: {error}"
))
})?;
check_response(response, "moving project issue")?;
Ok(())
}
fn create_issue(&self, payload: &CreateIssuePayload) -> Result<Issue, ApiError> {
let response = self
.client
.post(self.endpoint("issues")?)
.header("Authorization", format!("token {}", self.token))
.json(payload)
.send()
.map_err(|error| {
ApiError(format!("cannot reach Gitea while creating issue: {error}"))
})?;
self.decode(response, "creating issue")
}
fn edit_issue(&self, issue_number: u64, payload: &EditIssuePayload) -> Result<Issue, ApiError> {
let response = self
.client
.patch(self.endpoint(&format!("issues/{issue_number}"))?)
.header("Authorization", format!("token {}", self.token))
.json(payload)
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while editing issue #{issue_number}: {error}"
))
})?;
self.decode(response, &format!("editing issue #{issue_number}"))
}
fn delete_issue(&self, issue_number: u64) -> Result<(), ApiError> {
let response = self
.client
.delete(self.endpoint(&format!("issues/{issue_number}"))?)
.header("Authorization", format!("token {}", self.token))
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while deleting issue #{issue_number}: {error}"
))
})?;
check_response(response, &format!("deleting issue #{issue_number}"))?;
Ok(())
}
fn list_issue_comments(&self, issue_number: u64) -> Result<Vec<Comment>, ApiError> {
self.get_all(
&format!("issues/{issue_number}/comments"),
&format!("listing comments for issue #{issue_number}"),
&[],
)
}
fn create_issue_comment(&self, issue_number: u64, body: String) -> Result<Comment, ApiError> {
let response = self
.client
.post(self.endpoint(&format!("issues/{issue_number}/comments"))?)
.header("Authorization", format!("token {}", self.token))
.json(&CommentPayload { body })
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while creating comment on issue #{issue_number}: {error}"
))
})?;
self.decode(
response,
&format!("creating comment on issue #{issue_number}"),
)
}
fn edit_issue_comment(&self, comment_id: u64, body: String) -> Result<Comment, ApiError> {
let response = self
.client
.patch(self.endpoint(&format!("issues/comments/{comment_id}"))?)
.header("Authorization", format!("token {}", self.token))
.json(&CommentPayload { body })
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while editing comment #{comment_id}: {error}"
))
})?;
self.decode(response, &format!("editing comment #{comment_id}"))
}
fn delete_issue_comment(&self, comment_id: u64) -> Result<(), ApiError> {
let response = self
.client
.delete(self.endpoint(&format!("issues/comments/{comment_id}"))?)
.header("Authorization", format!("token {}", self.token))
.send()
.map_err(|error| {
ApiError(format!(
"cannot reach Gitea while deleting comment #{comment_id}: {error}"
))
})?;
check_response(response, &format!("deleting comment #{comment_id}"))?;
Ok(())
}
}
fn check_response(response: Response, operation: &str) -> Result<Response, ApiError> {
let status = response.status();
if status.is_success() {
return Ok(response);
}
let guidance = match status {
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
" Check token validity and repository issue permissions."
}
StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED => {
" Check repository owner/name and whether this Gitea version supports native project APIs."
}
_ => "",
};
Err(ApiError(format!(
"Gitea API failed while {operation} ({status}).{guidance}"
)))
}
fn require_secure_transport(url: &Url) -> Result<(), ApiError> {
if url.scheme() == "https" {
return Ok(());
}
let loopback = url
.host_str()
.and_then(|host| {
host.trim_start_matches('[')
.trim_end_matches(']')
.parse::<IpAddr>()
.ok()
})
.is_some_and(|address| address.is_loopback());
if url.scheme() == "http" && loopback {
return Ok(());
}
Err(ApiError(
"Gitea URL must use HTTPS to protect the API token; plain HTTP is allowed only for loopback development"
.to_owned(),
))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::mpsc::{self, Receiver};
use std::thread;
fn config(base_url: &str) -> Config {
Config {
base_url: base_url.to_owned(),
token: "secret".to_owned(),
owner: "owner name".to_owned(),
repo: "repo/name".to_owned(),
project: Some("Kanban".to_owned()),
project_id: None,
}
}
fn mock_server(responses: Vec<&'static str>) -> (String, Receiver<String>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock server");
let address = listener.local_addr().expect("mock address");
let (sender, receiver) = mpsc::channel();
thread::spawn(move || {
for response in responses {
let (mut stream, _) = listener.accept().expect("accept request");
let mut request = Vec::new();
let mut buffer = [0_u8; 4096];
loop {
let read = stream.read(&mut buffer).expect("read request");
if read == 0 {
break;
}
request.extend_from_slice(&buffer[..read]);
let header_end = request
.windows(4)
.position(|window| window == b"\r\n\r\n")
.map(|position| position + 4);
if let Some(header_end) = header_end {
let headers = String::from_utf8_lossy(&request[..header_end]);
let content_length = headers
.lines()
.find_map(|line| {
line.to_ascii_lowercase()
.strip_prefix("content-length: ")?
.parse::<usize>()
.ok()
})
.unwrap_or(0);
if request.len() >= header_end + content_length {
break;
}
}
}
let _ = sender.send(String::from_utf8(request).expect("UTF-8 request"));
stream
.write_all(response.as_bytes())
.expect("write response");
}
});
(format!("http://{address}"), receiver)
}
#[test]
fn preserves_base_path_and_encodes_repository_segments() {
let client = GiteaClient::new(&config("https://gitea.example/subpath"))
.expect("client should build");
assert_eq!(
client.endpoint("projects").expect("endpoint").as_str(),
"https://gitea.example/subpath/api/v1/repos/owner%20name/repo%2Fname/projects"
);
}
#[test]
fn rejects_remote_plain_http_but_allows_loopback() {
assert!(GiteaClient::new(&config("http://gitea.example")).is_err());
assert!(GiteaClient::new(&config("http://localhost:3000")).is_err());
assert!(GiteaClient::new(&config("http://127.0.0.1:3000")).is_ok());
assert!(GiteaClient::new(&config("http://[::1]:3000")).is_ok());
}
#[test]
fn resolves_exact_project_name_and_rejects_ambiguity() {
let projects = vec![
Project {
id: 1,
title: "Kanban".to_owned(),
is_closed: false,
},
Project {
id: 2,
title: "kanban".to_owned(),
is_closed: false,
},
];
assert_eq!(
resolve_project(&projects, Some("Kanban"), None)
.expect("match")
.id,
1
);
assert!(resolve_project(&projects, Some("Missing"), None).is_err());
assert_eq!(
resolve_project(&projects, None, Some(2)).expect("id").title,
"kanban"
);
}
#[test]
fn lists_projects_with_pagination_and_reports_unsupported_api() {
let (base_url, requests) = mock_server(vec![
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n[{\"id\":4,\"title\":\"Kanban\",\"is_closed\":false}]",
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n[]",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
let projects = client.list_projects().expect("projects");
assert_eq!(projects[0].title, "Kanban");
let first = requests.recv().expect("first request");
let second = requests.recv().expect("second request");
assert!(first.starts_with("GET /api/v1/repos/owner%20name/repo%2Fname/projects?"));
assert!(first.contains("state=all"));
assert!(first.contains("page=1"));
assert!(second.contains("page=2"));
assert!(first.contains("authorization: token secret"));
let (base_url, _) = mock_server(vec![
"HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"message\":\"projects unavailable secret\"}",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
let error = client
.list_project_columns(4)
.expect_err("unsupported API must fail");
assert!(error.to_string().contains("404 Not Found"));
assert!(!error.to_string().contains("secret"));
}
#[test]
fn stops_pagination_at_reported_total_count() {
let (base_url, requests) = mock_server(vec![
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nX-Total-Count: 1\r\nConnection: close\r\n\r\n[{\"id\":4,\"title\":\"Kanban\",\"is_closed\":false}]",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
let projects = client.list_projects().expect("projects");
assert_eq!(projects.len(), 1);
assert!(requests.recv().expect("page one").contains("page=1"));
assert!(requests.try_recv().is_err());
}
#[test]
fn sends_global_issue_move_payload() {
let (base_url, requests) = mock_server(vec![
"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
client
.move_project_issue(
4,
99,
&MoveProjectIssuePayload {
column_id: 12,
sorting: Some(3),
},
)
.expect("move");
let request = requests.recv().expect("request");
assert!(request.starts_with(
"POST /api/v1/repos/owner%20name/repo%2Fname/projects/4/issues/99/move HTTP/1.1"
));
assert!(request.ends_with("{\"column_id\":12,\"sorting\":3}"));
}
#[test]
fn paginates_native_column_issues() {
let (base_url, requests) = mock_server(vec![
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n[{\"id\":99,\"number\":7,\"title\":\"Fix\"}]",
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n[]",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
let issues = client
.list_project_column_issues(4, 12)
.expect("column issues");
assert_eq!(issues[0].id, 99);
assert!(requests.recv().expect("page one").contains("page=1"));
assert!(requests.recv().expect("page two").contains("page=2"));
}
#[test]
fn creates_edits_and_deletes_issues() {
let (base_url, requests) = mock_server(vec![
"HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"id\":99,\"number\":7,\"title\":\"New\"}",
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"id\":99,\"number\":7,\"title\":\"Updated\"}",
"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
]);
let client = GiteaClient::new(&config(&base_url)).expect("client");
let created = client
.create_issue(&CreateIssuePayload {
title: "New".to_owned(),
body: "Details".to_owned(),
projects: vec![4],
})
.expect("create");
assert_eq!(created.number, 7);
let edited = client
.edit_issue(
7,
&EditIssuePayload {
title: "Updated".to_owned(),
body: "Changed".to_owned(),
},
)
.expect("edit");
assert_eq!(edited.title, "Updated");
client.delete_issue(7).expect("delete");
assert!(requests
.recv()
.expect("create request")
.ends_with("{\"title\":\"New\",\"body\":\"Details\",\"projects\":[4]}"));
assert!(requests
.recv()
.expect("edit request")
.starts_with("PATCH /api/v1/repos/owner%20name/repo%2Fname/issues/7 HTTP/1.1"));
assert!(requests
.recv()
.expect("delete request")
.starts_with("DELETE /api/v1/repos/owner%20name/repo%2Fname/issues/7 HTTP/1.1"));
}
}
+502
View File
@@ -0,0 +1,502 @@
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::model::{
ColumnSpec, EditIssuePayload, Issue, MoveProjectIssuePayload, Project, ProjectColumn,
};
#[derive(Clone, Debug)]
pub struct Column {
pub spec: ColumnSpec,
pub cards: Vec<Issue>,
}
pub struct App {
pub board_title: String,
pub columns: Vec<Column>,
pub focused_column: usize,
pub focused_cards: Vec<usize>,
pub status: String,
pub show_help: bool,
pub editor: Option<EditorState>,
project_id: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EditorMode {
Create { project_id: u64 },
Edit { issue_number: u64 },
Delete { issue_number: u64, title: String },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditorField {
Title,
Body,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EditorState {
pub mode: EditorMode,
pub field: EditorField,
pub title: String,
pub body: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IssueAction {
Create {
project_id: u64,
title: String,
body: String,
},
Edit {
issue_number: u64,
payload: EditIssuePayload,
},
Delete {
issue_number: u64,
},
}
#[derive(Debug, PartialEq, Eq)]
pub enum MoveAction {
Project {
issue_id: u64,
project_id: u64,
payload: MoveProjectIssuePayload,
},
}
#[derive(Debug, PartialEq, Eq)]
pub struct MoveRequest {
pub source: usize,
pub target: usize,
pub action: MoveAction,
}
impl App {
pub fn new_project(
project: Project,
project_columns: Vec<ProjectColumn>,
issues_by_column: Vec<Vec<Issue>>,
) -> Result<Self, String> {
if project_columns.is_empty() {
return Err(format!("project '{}' has no columns", project.title));
}
if project_columns.len() != issues_by_column.len() {
return Err("project columns and issue lists do not match".to_owned());
}
let columns = project_columns
.into_iter()
.zip(issues_by_column)
.map(|(column, cards)| Column {
spec: ColumnSpec {
id: column.id,
title: column.title,
},
cards,
})
.collect::<Vec<_>>();
let focused_column = columns
.iter()
.position(|column| !column.cards.is_empty())
.unwrap_or(0);
let focused_cards = vec![0; columns.len()];
Ok(Self {
board_title: format!("{} (project {})", project.title, project.id),
columns,
focused_column,
focused_cards,
status: "Ready".to_owned(),
show_help: false,
editor: None,
project_id: project.id,
})
}
pub fn focus_left(&mut self) {
self.focused_column = self.focused_column.saturating_sub(1);
}
pub fn focus_right(&mut self) {
self.focused_column = (self.focused_column + 1).min(self.columns.len() - 1);
}
pub fn focus_up(&mut self) {
let selected = &mut self.focused_cards[self.focused_column];
*selected = selected.saturating_sub(1);
}
pub fn focus_down(&mut self) {
let column = &self.columns[self.focused_column];
if !column.cards.is_empty() {
let selected = &mut self.focused_cards[self.focused_column];
*selected = (*selected + 1).min(column.cards.len() - 1);
}
}
pub fn focused_card(&self) -> Option<&Issue> {
self.columns[self.focused_column]
.cards
.get(self.focused_cards[self.focused_column])
}
pub fn prepare_move(&self, offset: isize) -> Option<MoveRequest> {
let target = self.focused_column.checked_add_signed(offset)?;
if target >= self.columns.len() {
return None;
}
let issue = self.focused_card()?;
let action = MoveAction::Project {
issue_id: issue.id,
project_id: self.project_id,
payload: MoveProjectIssuePayload {
column_id: self.columns[target].spec.id,
sorting: None,
},
};
Some(MoveRequest {
source: self.focused_column,
target,
action,
})
}
pub fn apply_move(&mut self, request: MoveRequest) {
let selected = self.focused_cards[request.source];
let issue = self.columns[request.source].cards.remove(selected);
let issue_number = issue.number;
self.columns[request.target].cards.push(issue);
self.focused_cards[request.source] =
selected.min(self.columns[request.source].cards.len().saturating_sub(1));
self.focused_cards[request.target] = self.columns[request.target].cards.len() - 1;
self.focused_column = request.target;
self.status = format!("Moved issue #{issue_number}");
}
pub fn begin_create(&mut self) {
self.editor = Some(EditorState {
mode: EditorMode::Create {
project_id: self.project_id,
},
field: EditorField::Title,
title: String::new(),
body: String::new(),
});
}
pub fn begin_edit(&mut self) {
let Some(issue) = self.focused_card().cloned() else {
self.status = "No issue selected".to_owned();
return;
};
self.editor = Some(EditorState {
mode: EditorMode::Edit {
issue_number: issue.number,
},
field: EditorField::Title,
title: issue.title,
body: issue.body.unwrap_or_default(),
});
}
pub fn begin_delete(&mut self) {
let Some(issue) = self.focused_card() else {
self.status = "No issue selected".to_owned();
return;
};
self.editor = Some(EditorState {
mode: EditorMode::Delete {
issue_number: issue.number,
title: issue.title.clone(),
},
field: EditorField::Title,
title: String::new(),
body: String::new(),
});
}
pub fn handle_editor_key(&mut self, key: KeyEvent) -> Option<IssueAction> {
let mut editor = self.editor.take()?;
if matches!(editor.mode, EditorMode::Delete { .. }) {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
if let EditorMode::Delete { issue_number, .. } = editor.mode {
return Some(IssueAction::Delete { issue_number });
}
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.status = "Delete cancelled".to_owned();
}
_ => {
self.editor = Some(editor);
}
}
return None;
}
if key.code == KeyCode::Esc {
self.status = "Edit cancelled".to_owned();
return None;
}
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('s') {
return self.submit_editor(editor);
}
match key.code {
KeyCode::Tab => {
editor.field = match editor.field {
EditorField::Title => EditorField::Body,
EditorField::Body => EditorField::Title,
};
}
KeyCode::Enter if editor.field == EditorField::Title => {
editor.field = EditorField::Body;
}
KeyCode::Enter => editor.body.push('\n'),
KeyCode::Backspace => match editor.field {
EditorField::Title => {
editor.title.pop();
}
EditorField::Body => {
editor.body.pop();
}
},
KeyCode::Char(character) if !character.is_control() => match editor.field {
EditorField::Title => editor.title.push(character),
EditorField::Body => editor.body.push(character),
},
_ => {}
}
self.editor = Some(editor);
None
}
pub fn restore_issue_action(&mut self, action: IssueAction) {
self.editor = Some(match action {
IssueAction::Create {
project_id,
title,
body,
} => EditorState {
mode: EditorMode::Create { project_id },
field: EditorField::Body,
title,
body,
},
IssueAction::Edit {
issue_number,
payload,
} => EditorState {
mode: EditorMode::Edit { issue_number },
field: EditorField::Body,
title: payload.title,
body: payload.body,
},
IssueAction::Delete { issue_number } => EditorState {
mode: EditorMode::Delete {
issue_number,
title: self
.focused_card()
.map(|issue| issue.title.clone())
.unwrap_or_default(),
},
field: EditorField::Title,
title: String::new(),
body: String::new(),
},
});
}
fn submit_editor(&mut self, editor: EditorState) -> Option<IssueAction> {
if editor.title.trim().is_empty() {
self.status = "Title cannot be empty".to_owned();
self.editor = Some(editor);
return None;
}
match editor.mode {
EditorMode::Create { project_id } => Some(IssueAction::Create {
project_id,
title: editor.title,
body: editor.body,
}),
EditorMode::Edit { issue_number } => Some(IssueAction::Edit {
issue_number,
payload: EditIssuePayload {
title: editor.title,
body: editor.body,
},
}),
EditorMode::Delete { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::*;
fn app() -> App {
App::new_project(
Project {
id: 8,
title: "Kanban".to_owned(),
is_closed: false,
},
vec![
ProjectColumn {
id: 10,
title: "Todo".to_owned(),
color: String::new(),
sorting: 0,
},
ProjectColumn {
id: 20,
title: "Done".to_owned(),
color: String::new(),
sorting: 1,
},
],
vec![
vec![
Issue {
id: 1,
number: 1,
title: "First".to_owned(),
body: None,
},
Issue {
id: 2,
number: 2,
title: "Second".to_owned(),
body: None,
},
],
Vec::new(),
],
)
.expect("board builds")
}
#[test]
fn navigation_stays_within_board() {
let mut app = app();
app.focus_left();
app.focus_up();
assert_eq!(app.focused_column, 0);
assert_eq!(app.focused_cards[0], 0);
app.focus_down();
app.focus_down();
app.focus_right();
app.focus_right();
assert_eq!(app.focused_cards[0], 1);
assert_eq!(app.focused_column, 1);
}
#[test]
fn cannot_move_past_board_edge() {
let app = app();
assert!(app.prepare_move(-1).is_none());
}
#[test]
fn empty_board_returns_actionable_error() {
let result = App::new_project(
Project {
id: 1,
title: "Kanban".to_owned(),
is_closed: false,
},
vec![ProjectColumn {
id: 1,
title: "Todo".to_owned(),
color: String::new(),
sorting: 0,
}],
vec![Vec::new()],
);
assert!(result.is_ok());
}
#[test]
fn native_move_uses_global_issue_and_column_ids() {
let mut app = App::new_project(
Project {
id: 8,
title: "Kanban".to_owned(),
is_closed: false,
},
vec![
ProjectColumn {
id: 10,
title: "Todo".to_owned(),
color: String::new(),
sorting: 0,
},
ProjectColumn {
id: 20,
title: "Done".to_owned(),
color: String::new(),
sorting: 1,
},
],
vec![
vec![Issue {
id: 99,
number: 7,
title: "Fix".to_owned(),
body: None,
}],
Vec::new(),
],
)
.expect("board");
let request = app.prepare_move(1).expect("move");
assert!(matches!(
request.action,
MoveAction::Project { issue_id: 99, ref payload, .. } if payload.column_id == 20
));
app.apply_move(request);
assert_eq!(app.columns[1].cards[0].id, 99);
}
#[test]
fn native_editor_creates_project_issue_action() {
let mut app = App::new_project(
Project {
id: 8,
title: "Kanban".to_owned(),
is_closed: false,
},
vec![ProjectColumn {
id: 10,
title: "Todo".to_owned(),
color: String::new(),
sorting: 0,
}],
vec![Vec::new()],
)
.expect("board");
app.begin_create();
for character in "New issue".chars() {
app.handle_editor_key(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE));
}
app.handle_editor_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
for character in "Details".chars() {
app.handle_editor_key(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE));
}
let action =
app.handle_editor_key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));
assert!(matches!(
action,
Some(IssueAction::Create {
project_id: 8,
title,
body,
}) if title == "New issue" && body == "Details"
));
assert!(app.editor.is_none());
}
}
@@ -0,0 +1,251 @@
use std::error::Error;
use clap::{Parser, Subcommand};
use gitea_kanban_tui::api::{load_project_board, GiteaClient};
use gitea_kanban_tui::config::{Config, SharedArgs};
use gitea_kanban_tui::model::EditIssuePayload;
use gitea_kanban_tui::operations;
use gitea_kanban_tui::text::sanitize_terminal_text;
#[derive(Debug, Parser)]
#[command(
version,
about = "Control native Gitea project boards from the command line"
)]
struct Cli {
#[command(flatten)]
shared: SharedArgs,
#[command(subcommand)]
command: Command,
}
#[derive(Debug, Subcommand)]
enum Command {
/// Print project columns and their issues.
Board,
/// Create an issue assigned to selected project.
Create {
#[arg(long)]
title: String,
#[arg(long, default_value = "")]
body: String,
},
/// Replace issue title and body.
Edit {
issue: u64,
#[arg(long)]
title: String,
#[arg(long)]
body: String,
},
/// Delete an issue. Requires repository admin permission.
Delete {
issue: u64,
/// Confirm irreversible deletion.
#[arg(long)]
yes: bool,
},
/// Move an issue to a project column.
Move {
issue_id: u64,
#[arg(long)]
column_id: u64,
#[arg(long)]
sorting: Option<u64>,
},
/// Manage comments on an issue in selected project.
Comment {
#[command(subcommand)]
command: CommentCommand,
},
}
#[derive(Debug, Subcommand)]
enum CommentCommand {
/// List comments for an issue.
List { issue: u64 },
/// Add a comment to an issue.
Add {
issue: u64,
#[arg(long)]
body: String,
},
/// Replace a comment body.
Edit {
issue: u64,
comment_id: u64,
#[arg(long)]
body: String,
},
/// Delete a comment.
Delete {
issue: u64,
comment_id: u64,
#[arg(long)]
yes: bool,
},
}
fn main() {
if let Err(error) = run() {
eprintln!("error: {}", sanitize_terminal_text(&error.to_string()));
std::process::exit(1);
}
}
fn run() -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
let config = Config::from_shared_args_with(cli.shared, |name| std::env::var(name).ok())?;
let client = GiteaClient::new(&config)?;
match cli.command {
Command::Board => {
let board = load_project_board(&client, &config)?;
println!(
"{} (project {})",
sanitize_terminal_text(&board.project.title),
board.project.id
);
for (column, issues) in board.columns.iter().zip(board.issues_by_column) {
println!(
"\n{} ({})",
sanitize_terminal_text(&column.title),
column.id
);
for issue in issues {
println!(
" #{} {}",
issue.number,
sanitize_terminal_text(&issue.title)
);
}
}
}
Command::Create { title, body } => {
let board = load_project_board(&client, &config)?;
let issue = operations::create_project_issue(&client, board.project.id, title, body)?;
println!("created issue #{}", issue.number);
}
Command::Edit { issue, title, body } => {
let board = load_project_board(&client, &config)?;
if !board
.issues_by_column
.iter()
.flatten()
.any(|candidate| candidate.number == issue)
{
return Err(format!("issue #{issue} is not assigned to selected project").into());
}
operations::edit_issue(&client, issue, &EditIssuePayload { title, body })?;
println!("updated issue #{issue}");
}
Command::Delete { issue, yes } => {
if !yes {
return Err("deletion requires --yes".into());
}
let board = load_project_board(&client, &config)?;
if !board
.issues_by_column
.iter()
.flatten()
.any(|candidate| candidate.number == issue)
{
return Err(format!("issue #{issue} is not assigned to selected project").into());
}
operations::delete_issue(&client, issue)?;
println!("deleted issue #{issue}");
}
Command::Move {
issue_id,
column_id,
sorting,
} => {
let board = load_project_board(&client, &config)?;
operations::move_project_issue(
&client,
board.project.id,
issue_id,
&gitea_kanban_tui::model::MoveProjectIssuePayload { column_id, sorting },
)?;
println!("moved issue {issue_id} to column {column_id}");
}
Command::Comment { command } => match command {
CommentCommand::List { issue } => {
for comment in project_issue_comments(&client, &config, issue)? {
let author = comment
.user
.as_ref()
.map(|user| user.login.as_str())
.unwrap_or("unknown");
println!(
"#{} {}\n{}",
comment.id,
sanitize_terminal_text(author),
sanitize_terminal_text(&comment.body)
);
}
}
CommentCommand::Add { issue, body } => {
project_issue_comments(&client, &config, issue)?;
let comment = operations::create_issue_comment(&client, issue, body)?;
println!("created comment #{} on issue #{}", comment.id, issue);
}
CommentCommand::Edit {
issue,
comment_id,
body,
} => {
ensure_comment(&client, &config, issue, comment_id)?;
operations::edit_issue_comment(&client, comment_id, body)?;
println!("updated comment #{comment_id}");
}
CommentCommand::Delete {
issue,
comment_id,
yes,
} => {
if !yes {
return Err("comment deletion requires --yes".into());
}
ensure_comment(&client, &config, issue, comment_id)?;
operations::delete_issue_comment(&client, comment_id)?;
println!("deleted comment #{comment_id}");
}
},
}
Ok(())
}
fn project_issue_comments(
client: &GiteaClient,
config: &Config,
issue: u64,
) -> Result<Vec<gitea_kanban_tui::model::Comment>, Box<dyn Error>> {
let board = load_project_board(client, config)?;
if !board
.issues_by_column
.iter()
.flatten()
.any(|candidate| candidate.number == issue)
{
return Err(format!("issue #{issue} is not assigned to selected project").into());
}
Ok(operations::list_issue_comments(client, issue)?)
}
fn ensure_comment(
client: &GiteaClient,
config: &Config,
issue: u64,
comment_id: u64,
) -> Result<(), Box<dyn Error>> {
if !project_issue_comments(client, config, issue)?
.iter()
.any(|comment| comment.id == comment_id)
{
return Err(format!("comment #{comment_id} is not attached to issue #{issue}").into());
}
Ok(())
}
+303
View File
@@ -0,0 +1,303 @@
use std::env;
use std::fmt;
use std::fs;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use clap::{Args as ClapArgs, Parser};
#[derive(Clone, Debug, ClapArgs)]
pub struct SharedArgs {
/// Gitea base URL; falls back to GITEA_URL
#[arg(long)]
pub url: Option<String>,
/// File containing API token; falls back to GITEA_TOKEN_FILE
#[arg(long, value_name = "PATH")]
pub token_file: Option<PathBuf>,
/// Exact native project name
#[arg(long)]
pub project: Option<String>,
/// Native project ID
#[arg(long)]
pub project_id: Option<u64>,
/// Repository owner; falls back to GITEA_OWNER
pub owner: Option<String>,
/// Repository name; falls back to GITEA_REPO
pub repo: Option<String>,
}
#[derive(Debug, Parser)]
#[command(
name = "gitea-kanban-tui",
version,
about = "Browse and move Gitea issues using native projects"
)]
pub struct Args {
#[command(flatten)]
pub shared: SharedArgs,
}
#[derive(Debug)]
pub struct Config {
pub base_url: String,
pub token: String,
pub owner: String,
pub repo: String,
pub project: Option<String>,
pub project_id: Option<u64>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ConfigError(String);
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ConfigError {}
impl Config {
pub fn load() -> Result<Self, ConfigError> {
Self::from_args_with(Args::parse(), |name| env::var(name).ok())
}
pub fn from_args_with<F>(args: Args, env_var: F) -> Result<Self, ConfigError>
where
F: Fn(&str) -> Option<String>,
{
Self::from_shared_args_with(args.shared, env_var)
}
pub fn from_shared_args_with<F>(args: SharedArgs, env_var: F) -> Result<Self, ConfigError>
where
F: Fn(&str) -> Option<String>,
{
let base_url = required(
args.url.or_else(|| env_var("GITEA_URL")),
"Gitea URL",
"--url or GITEA_URL",
)?;
let owner = required(
args.owner.or_else(|| env_var("GITEA_OWNER")),
"repository owner",
"OWNER argument or GITEA_OWNER",
)?;
let repo = required(
args.repo.or_else(|| env_var("GITEA_REPO")),
"repository name",
"REPO argument or GITEA_REPO",
)?;
let project = args
.project
.or_else(|| env_var("GITEA_PROJECT"))
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty());
let project_id = args
.project_id
.or_else(|| env_var("GITEA_PROJECT_ID").and_then(|value| value.parse::<u64>().ok()));
if project.is_some() == project_id.is_some() {
return Err(ConfigError(
"projects mode requires exactly one of --project/GITEA_PROJECT or --project-id/GITEA_PROJECT_ID"
.to_owned(),
));
}
let token = if let Some(path) = args.token_file {
read_token_file(path)?
} else if let Some(path) = env_var("GITEA_TOKEN_FILE") {
read_token_file(PathBuf::from(path))?
} else if let Some(token) = env_var("GITEA_TOKEN") {
clean_token(token, "GITEA_TOKEN")?
} else {
return Err(ConfigError(
"missing Gitea token; use --token-file, GITEA_TOKEN, or GITEA_TOKEN_FILE"
.to_owned(),
));
};
Ok(Self {
base_url: base_url.trim_end_matches('/').to_owned(),
token,
owner,
repo,
project,
project_id,
})
}
}
fn required(value: Option<String>, name: &str, source: &str) -> Result<String, ConfigError> {
match value.map(|value| value.trim().to_owned()) {
Some(value) if !value.is_empty() => Ok(value),
_ => Err(ConfigError(format!("missing {name}; use {source}"))),
}
}
fn clean_token(token: String, source: &str) -> Result<String, ConfigError> {
let token = token.trim().to_owned();
if token.is_empty() {
Err(ConfigError(format!("{source} contains an empty token")))
} else {
Ok(token)
}
}
fn read_token_file(path: PathBuf) -> Result<String, ConfigError> {
let metadata = fs::symlink_metadata(&path).map_err(|error| {
ConfigError(format!(
"cannot inspect token file {}: {error}",
path.display()
))
})?;
if !metadata.is_file() {
return Err(ConfigError(format!(
"token path {} is not a regular file",
path.display()
)));
}
#[cfg(unix)]
if metadata.permissions().mode() & 0o077 != 0 {
return Err(ConfigError(format!(
"token file {} must not be group- or world-readable",
path.display()
)));
}
let token = fs::read_to_string(&path).map_err(|error| {
ConfigError(format!(
"cannot read token file {}: {error}",
path.display()
))
})?;
clean_token(token, &format!("token file {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
fn empty_env(_: &str) -> Option<String> {
None
}
fn token_env(name: &str) -> Option<String> {
(name == "GITEA_TOKEN").then(|| "secret".to_owned())
}
#[test]
fn parses_explicit_configuration() {
let args = Args::try_parse_from([
"gitea-kanban-tui",
"--url",
"https://gitea.example/",
"--project",
"Kanban",
"owner",
"repo",
])
.expect("arguments parse");
let config = Config::from_args_with(args, token_env).expect("config is valid");
assert_eq!(config.base_url, "https://gitea.example");
assert_eq!(config.owner, "owner");
assert_eq!(config.repo, "repo");
assert_eq!(config.project.as_deref(), Some("Kanban"));
assert_eq!(config.token, "secret");
}
#[test]
fn parses_native_project_by_name() {
let args = Args::try_parse_from([
"gitea-kanban-tui",
"--url",
"https://gitea.example",
"--project",
"Kanban",
"owner",
"repo",
])
.expect("arguments parse");
let config = Config::from_args_with(args, token_env).expect("config is valid");
assert_eq!(config.project.as_deref(), Some("Kanban"));
assert_eq!(config.project_id, None);
}
#[test]
fn requires_project_selector() {
let args = Args::try_parse_from([
"gitea-kanban-tui",
"--url",
"https://gitea.example",
"owner",
"repo",
])
.expect("arguments parse");
let error =
Config::from_args_with(args, token_env).expect_err("project selector is required");
assert!(error.to_string().contains("--project"));
}
#[test]
fn native_project_selector_is_unambiguous() {
let args = Args::try_parse_from([
"gitea-kanban-tui",
"--url",
"https://gitea.example",
"owner",
"repo",
])
.expect("arguments parse");
let error = Config::from_args_with(args, token_env).expect_err("selector is required");
assert!(error.to_string().contains("exactly one"));
}
#[test]
fn falls_back_to_environment() {
let args = Args::try_parse_from(["gitea-kanban-tui"]).expect("arguments parse");
let config = Config::from_args_with(args, |name| {
match name {
"GITEA_URL" => Some("https://gitea.example"),
"GITEA_TOKEN" => Some("secret"),
"GITEA_PROJECT" => Some("Kanban"),
"GITEA_OWNER" => Some("owner"),
"GITEA_REPO" => Some("repo"),
_ => None,
}
.map(str::to_owned)
})
.expect("config is valid");
assert_eq!(config.project.as_deref(), Some("Kanban"));
assert_eq!(config.owner, "owner");
}
#[test]
fn reports_missing_token_without_exposing_values() {
let args = Args::try_parse_from([
"gitea-kanban-tui",
"--url",
"https://gitea.example",
"--project",
"Kanban",
"owner",
"repo",
])
.expect("arguments parse");
let error = match Config::from_args_with(args, empty_env) {
Ok(_) => panic!("token should be required"),
Err(error) => error,
};
assert!(error.to_string().contains("GITEA_TOKEN_FILE"));
}
}
+8
View File
@@ -0,0 +1,8 @@
pub mod api;
pub mod app;
pub mod config;
pub mod model;
pub mod operations;
pub mod terminal;
pub mod text;
pub mod ui;
+125
View File
@@ -0,0 +1,125 @@
use std::error::Error;
use std::time::Duration;
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use gitea_kanban_tui::api::{load_project_board, GiteaApi, GiteaClient};
use gitea_kanban_tui::app::{App, IssueAction, MoveAction};
use gitea_kanban_tui::config::Config;
use gitea_kanban_tui::operations;
use gitea_kanban_tui::terminal::TerminalGuard;
use gitea_kanban_tui::text::sanitize_terminal_text;
use gitea_kanban_tui::ui;
fn main() {
if let Err(error) = run() {
eprintln!("error: {}", sanitize_terminal_text(&error.to_string()));
std::process::exit(1);
}
}
fn run() -> Result<(), Box<dyn Error>> {
let config = Config::load()?;
let client = GiteaClient::new(&config)?;
let mut app = load_board(&client, &config)?;
let repository = format!("{}/{}", config.owner, config.repo);
let mut terminal = TerminalGuard::enter()?;
loop {
terminal
.terminal()
.draw(|frame| ui::draw(frame, &app, &repository))?;
if !event::poll(Duration::from_millis(250))? {
continue;
}
let Event::Key(key) = event::read()? else {
continue;
};
if key.kind != KeyEventKind::Press {
continue;
}
if app.editor.is_some() {
if let Some(action) = app.handle_editor_key(key) {
issue_action(&client, &config, &mut app, action);
}
continue;
}
match key.code {
KeyCode::Char('q') => break,
KeyCode::Left | KeyCode::Char('h') => app.focus_left(),
KeyCode::Right | KeyCode::Char('l') => app.focus_right(),
KeyCode::Up | KeyCode::Char('k') => app.focus_up(),
KeyCode::Down | KeyCode::Char('j') => app.focus_down(),
KeyCode::Char('H') => move_card(&client, &mut app, -1),
KeyCode::Char('L') => move_card(&client, &mut app, 1),
KeyCode::Char('n') => app.begin_create(),
KeyCode::Char('e') => app.begin_edit(),
KeyCode::Char('d') => app.begin_delete(),
KeyCode::Char('r') => match load_board(&client, &config) {
Ok(board) => app = board,
Err(error) => app.status = format!("Refresh failed: {error}"),
},
KeyCode::Char('?') => app.show_help = !app.show_help,
_ => {}
}
}
Ok(())
}
fn issue_action(client: &impl GiteaApi, config: &Config, app: &mut App, action: IssueAction) {
let retry_action = action.clone();
let message = match action {
IssueAction::Create {
project_id,
title,
body,
} => operations::create_project_issue(client, project_id, title, body)
.map(|issue| format!("Created issue #{}", issue.number)),
IssueAction::Edit {
issue_number,
payload,
} => operations::edit_issue(client, issue_number, &payload)
.map(|_| format!("Updated issue #{issue_number}")),
IssueAction::Delete { issue_number } => operations::delete_issue(client, issue_number)
.map(|_| format!("Deleted issue #{issue_number}")),
};
match message {
Ok(message) => match load_board(client, config) {
Ok(mut board) => {
board.status = message;
*app = board;
}
Err(error) => app.status = format!("Saved, refresh failed: {error}"),
},
Err(error) => {
app.restore_issue_action(retry_action);
app.status = format!("Issue operation failed: {error}");
}
}
}
fn load_board(client: &impl GiteaApi, config: &Config) -> Result<App, Box<dyn Error>> {
let board = load_project_board(client, config)?;
App::new_project(board.project, board.columns, board.issues_by_column)
.map_err(|error| error.into())
}
fn move_card(client: &impl GiteaApi, app: &mut App, offset: isize) {
let Some(request) = app.prepare_move(offset) else {
app.status = "Cannot move card beyond board edge".to_owned();
return;
};
let result = match &request.action {
MoveAction::Project {
issue_id,
project_id,
payload,
} => operations::move_project_issue(client, *project_id, *issue_id, payload),
};
match result {
Ok(()) => app.apply_move(request),
Err(error) => app.status = format!("Move failed: {error}"),
}
}
+158
View File
@@ -0,0 +1,158 @@
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Issue {
pub id: u64,
pub number: u64,
pub title: String,
#[serde(default)]
pub body: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Comment {
pub id: u64,
pub body: String,
#[serde(default)]
pub user: Option<CommentUser>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct CommentUser {
pub login: String,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct CommentPayload {
pub body: String,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct CreateIssuePayload {
pub title: String,
pub body: String,
pub projects: Vec<u64>,
}
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct EditIssuePayload {
pub title: String,
pub body: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColumnSpec {
pub id: u64,
pub title: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Project {
pub id: u64,
pub title: String,
#[serde(default)]
pub is_closed: bool,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct ProjectColumn {
pub id: u64,
pub title: String,
#[serde(default)]
pub color: String,
#[serde(default)]
pub sorting: i8,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectBoard {
pub project: Project,
pub columns: Vec<ProjectColumn>,
pub issues_by_column: Vec<Vec<Issue>>,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct MoveProjectIssuePayload {
pub column_id: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub sorting: Option<u64>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_native_project_data_and_move_payload() {
let project: Project = serde_json::from_value(serde_json::json!({
"id": 4,
"title": "Kanban",
"is_closed": false
}))
.expect("project JSON");
let column: ProjectColumn = serde_json::from_value(serde_json::json!({
"id": 9,
"title": "Doing",
"sorting": 1
}))
.expect("column JSON");
let issue: Issue = serde_json::from_value(serde_json::json!({
"id": 70,
"number": 7,
"title": "Fix it"
}))
.expect("issue JSON");
let payload = MoveProjectIssuePayload {
column_id: column.id,
sorting: Some(3),
};
assert_eq!(project.title, "Kanban");
assert_eq!(issue.id, 70);
assert_eq!(
serde_json::to_value(payload).expect("move payload"),
serde_json::json!({"column_id": 9, "sorting": 3})
);
}
#[test]
fn serializes_issue_create_and_edit_payloads() {
let create = CreateIssuePayload {
title: "New issue".to_owned(),
body: "Details".to_owned(),
projects: vec![4],
};
let edit = EditIssuePayload {
title: "Updated".to_owned(),
body: "Changed".to_owned(),
};
assert_eq!(
serde_json::to_value(create).expect("create payload"),
serde_json::json!({"title": "New issue", "body": "Details", "projects": [4]})
);
assert_eq!(
serde_json::to_value(edit).expect("edit payload"),
serde_json::json!({"title": "Updated", "body": "Changed"})
);
}
#[test]
fn serializes_and_deserializes_comment_data() {
let comment: Comment = serde_json::from_value(serde_json::json!({
"id": 9001,
"body": "Investigating",
"user": {"login": "alice"}
}))
.expect("comment JSON");
let payload = CommentPayload {
body: "Resolved".to_owned(),
};
assert_eq!(comment.id, 9001);
assert_eq!(comment.user.expect("comment user").login, "alice");
assert_eq!(
serde_json::to_value(payload).expect("comment payload"),
serde_json::json!({"body": "Resolved"})
);
}
}
@@ -0,0 +1,63 @@
use crate::api::{ApiError, GiteaApi};
use crate::model::{Comment, CreateIssuePayload, EditIssuePayload, Issue, MoveProjectIssuePayload};
pub fn create_project_issue(
client: &impl GiteaApi,
project_id: u64,
title: String,
body: String,
) -> Result<Issue, ApiError> {
client.create_issue(&CreateIssuePayload {
title,
body,
projects: vec![project_id],
})
}
pub fn edit_issue(
client: &impl GiteaApi,
issue_number: u64,
payload: &EditIssuePayload,
) -> Result<Issue, ApiError> {
client.edit_issue(issue_number, payload)
}
pub fn delete_issue(client: &impl GiteaApi, issue_number: u64) -> Result<(), ApiError> {
client.delete_issue(issue_number)
}
pub fn move_project_issue(
client: &impl GiteaApi,
project_id: u64,
issue_id: u64,
payload: &MoveProjectIssuePayload,
) -> Result<(), ApiError> {
client.move_project_issue(project_id, issue_id, payload)
}
pub fn list_issue_comments(
client: &impl GiteaApi,
issue_number: u64,
) -> Result<Vec<Comment>, ApiError> {
client.list_issue_comments(issue_number)
}
pub fn create_issue_comment(
client: &impl GiteaApi,
issue_number: u64,
body: String,
) -> Result<Comment, ApiError> {
client.create_issue_comment(issue_number, body)
}
pub fn edit_issue_comment(
client: &impl GiteaApi,
comment_id: u64,
body: String,
) -> Result<Comment, ApiError> {
client.edit_issue_comment(comment_id, body)
}
pub fn delete_issue_comment(client: &impl GiteaApi, comment_id: u64) -> Result<(), ApiError> {
client.delete_issue_comment(comment_id)
}
+45
View File
@@ -0,0 +1,45 @@
use std::io::{self, Stdout};
use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
pub struct TerminalGuard {
terminal: Terminal<CrosstermBackend<Stdout>>,
}
impl TerminalGuard {
pub fn enter() -> io::Result<Self> {
enable_raw_mode()?;
let mut stdout = io::stdout();
if let Err(error) = execute!(stdout, EnterAlternateScreen) {
let _ = disable_raw_mode();
return Err(error);
}
let backend = CrosstermBackend::new(stdout);
match Terminal::new(backend) {
Ok(terminal) => Ok(Self { terminal }),
Err(error) => {
let mut stdout = io::stdout();
let _ = execute!(stdout, LeaveAlternateScreen);
let _ = disable_raw_mode();
Err(error)
}
}
}
pub fn terminal(&mut self) -> &mut Terminal<CrosstermBackend<Stdout>> {
&mut self.terminal
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = disable_raw_mode();
let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
let _ = self.terminal.show_cursor();
}
}
+46
View File
@@ -0,0 +1,46 @@
pub fn sanitize_terminal_text(value: &str) -> String {
value
.chars()
.map(|character| {
if character.is_control() {
' '
} else {
character
}
})
.collect()
}
pub fn sanitize_editor_text(value: &str) -> String {
value
.chars()
.map(|character| {
if character == '\n' || !character.is_control() {
character
} else {
' '
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_terminal_control_characters() {
assert_eq!(
sanitize_terminal_text("safe\u{1b}[31m\ntext"),
"safe [31m text"
);
}
#[test]
fn editor_sanitizer_preserves_newlines() {
assert_eq!(
sanitize_editor_text("first\nsecond\u{1b}[31m"),
"first\nsecond [31m"
);
}
}
+208
View File
@@ -0,0 +1,208 @@
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Frame;
use crate::app::{App, Column, EditorField, EditorMode, EditorState};
use crate::text::{sanitize_editor_text, sanitize_terminal_text};
pub fn draw(frame: &mut Frame<'_>, app: &App, repository: &str) {
let areas = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Min(6),
Constraint::Length(4),
Constraint::Length(if app.show_help { 3 } else { 1 }),
])
.split(frame.area());
frame.render_widget(
Paragraph::new(format!(
"Gitea Kanban — {} — {}",
sanitize_terminal_text(repository),
sanitize_terminal_text(&app.board_title)
))
.style(
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
),
areas[0],
);
draw_columns(frame, app, areas[1]);
draw_detail(frame, app, areas[2]);
let help = if app.show_help {
format!(
"{}\n←/h →/l: column ↑/k ↓/j: card H/L: move n: new e: edit d: delete r: refresh ?: help q: quit",
sanitize_terminal_text(&app.status)
)
} else {
format!(
"{} | ?: help q: quit",
sanitize_terminal_text(&app.status)
)
};
frame.render_widget(Paragraph::new(help).wrap(Wrap { trim: true }), areas[3]);
if let Some(editor) = &app.editor {
draw_editor(frame, editor);
}
}
fn draw_editor(frame: &mut Frame<'_>, editor: &EditorState) {
let area = centered_rect(frame.area(), 80, 45);
frame.render_widget(Clear, area);
let (title, content) = match &editor.mode {
EditorMode::Delete {
issue_number,
title,
} => (
"Delete issue".to_owned(),
format!(
"Delete issue #{issue_number} — {}?\n\n[y] confirm [n/Esc] cancel",
sanitize_terminal_text(title)
),
),
EditorMode::Create { .. } => (
"New issue".to_owned(),
editor_content(editor, "Create issue"),
),
EditorMode::Edit { issue_number } => (
format!("Edit issue #{issue_number}"),
editor_content(editor, "Edit issue"),
),
};
frame.render_widget(
Paragraph::new(content)
.block(
Block::default()
.title(format!(" {title} "))
.borders(Borders::ALL),
)
.wrap(Wrap { trim: false }),
area,
);
}
fn editor_content(editor: &EditorState, action: &str) -> String {
let title_marker = if editor.field == EditorField::Title {
"▶ "
} else {
" "
};
let body_marker = if editor.field == EditorField::Body {
"▶ "
} else {
" "
};
format!(
"{title_marker}Title: {}\n{body_marker}Body: {}\n\nTab: switch field Enter: title → body Ctrl-S: save Esc: cancel\n{action}",
sanitize_terminal_text(&editor.title),
sanitize_editor_text(&editor.body)
)
}
fn centered_rect(area: Rect, width_percent: u16, height_percent: u16) -> Rect {
let vertical = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - height_percent) / 2),
Constraint::Percentage(height_percent),
Constraint::Percentage((100 - height_percent) / 2),
])
.split(area);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - width_percent) / 2),
Constraint::Percentage(width_percent),
Constraint::Percentage((100 - width_percent) / 2),
])
.split(vertical[1])[1]
}
fn draw_columns(frame: &mut Frame<'_>, app: &App, area: Rect) {
let widths = vec![Constraint::Ratio(1, app.columns.len() as u32); app.columns.len()];
let areas = Layout::default()
.direction(Direction::Horizontal)
.constraints(widths)
.split(area);
for (index, column) in app.columns.iter().enumerate() {
draw_column(frame, app, column, index, areas[index]);
}
}
fn draw_column(frame: &mut Frame<'_>, app: &App, column: &Column, index: usize, area: Rect) {
let focused = index == app.focused_column;
let border_style = if focused {
Style::default().fg(Color::Yellow)
} else {
Style::default()
};
let items: Vec<ListItem<'_>> = column
.cards
.iter()
.map(|issue| {
ListItem::new(Line::from(vec![
Span::styled(
format!("#{} ", issue.number),
Style::default().fg(Color::DarkGray),
),
Span::raw(sanitize_terminal_text(&issue.title)),
]))
})
.collect();
let list = List::new(items)
.block(
Block::default()
.title(format!(
" {} ({}) ",
sanitize_terminal_text(&column.spec.title),
column.cards.len()
))
.borders(Borders::ALL)
.border_style(border_style),
)
.highlight_style(
Style::default()
.bg(Color::Blue)
.fg(Color::White)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut state = ListState::default();
if focused && !column.cards.is_empty() {
state.select(Some(app.focused_cards[index]));
}
frame.render_stateful_widget(list, area, &mut state);
}
fn draw_detail(frame: &mut Frame<'_>, app: &App, area: Rect) {
let text = app
.focused_card()
.map(|issue| {
let body = sanitize_terminal_text(
&issue
.body
.as_deref()
.unwrap_or("No description")
.replace('\n', " "),
);
format!(
"#{} {}\n{}",
issue.number,
sanitize_terminal_text(&issue.title),
body
)
})
.unwrap_or_else(|| "No card in focused column".to_owned());
frame.render_widget(
Paragraph::new(text)
.block(Block::default().title(" Detail ").borders(Borders::ALL))
.wrap(Wrap { trim: true }),
area,
);
}
@@ -0,0 +1,712 @@
#!/bin/dash
# Reconcile loop for gitea-runner-controller.
# Owns: TTL sweep, orphan-VM sweep, deferred-job retry, stale-runner dereg,
# startup convergence. Runs forever under systemd; webhook service is separate.
gcr_record_age_sec() {
created_at="$(gcr_record_field "$1" created_at)"
now="$(gcr_now_epoch)"
case "$created_at" in
''|*[!0-9]*) printf '%s' 999999 ;;
*) printf '%s' "$((now - created_at))" ;;
esac
}
gcr_sweep_ttl() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
status="$(gcr_record_field "$rec" status)"
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
if [ "$status" = "idle_vm" ]; then
gcr_lock_acquire idle-pool || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -z "$rec" ] || [ "$(gcr_record_field "$rec" status)" != "idle_vm" ]; then
gcr_lock_release idle-pool
continue
fi
if gcr_idle_record_unexpired "$rec"; then
gcr_lock_release idle-pool
continue
fi
vm_id="$(gcr_record_field "$rec" vm_id)"
if gcr_record_vm_owned_elsewhere "$vm_id" "$job_id" "$attempt"; then
gcr_log warn --ns=sweep "removing superseded idle record job=$job_id vm=$vm_id"
gcr_record_del "$job_id" "$attempt"
gcr_lock_release idle-pool
continue
fi
gcr_log info --ns=sweep "idle slot expired job=$job_id vm=$vm_id"
if [ -n "$vm_id" ] && [ "$vm_id" != "null" ] && [ "$vm_id" != "0" ]; then
if ! gcr_vm_cleanup_intent "$job_id" "$attempt" "$rec" \
idle-expired false; then
gcr_lock_release idle-pool
continue
fi
cleanup_rec="$(gcr_record_get "$job_id" "$attempt")"
gcr_lock_release idle-pool
if gcr_vm_cleanup_pending "$job_id" "$attempt" "$cleanup_rec"; then
gcr_event "vm-destroyed" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"idle-expired\"}"
else
gcr_event "vm-cleanup-pending" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"idle-expired\"}"
fi
else
gcr_record_del "$job_id" "$attempt"
gcr_lock_release idle-pool
fi
continue
fi
case "$status" in
create_pending|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) continue ;;
esac
ttl_min="$(gcr_record_field "$rec" ttl_min)"
case "$ttl_min" in ''|*[!0-9]*) continue ;; esac
max_sec="$((ttl_min * 60))"
age="$(gcr_record_age_sec "$rec")"
if [ "$age" -ge "$max_sec" ]; then
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
case "$(gcr_record_field "$rec" status)" in
create_pending|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) gcr_lock_release "$key"; continue ;;
esac
ttl_min="$(gcr_record_field "$rec" ttl_min)"
case "$ttl_min" in
''|*[!0-9]*) gcr_lock_release "$key"; continue ;;
esac
max_sec="$((ttl_min * 60))"
age="$(gcr_record_age_sec "$rec")"
if [ "$age" -lt "$max_sec" ]; then
gcr_lock_release "$key"
continue
fi
vm_id="$(gcr_record_field "$rec" vm_id)"
gcr_log warn --ns=sweep "TTL exceeded job=$job_id age=${age}s max=${max_sec}s"
if [ -n "$vm_id" ] && [ "$vm_id" != "null" ] && [ "$vm_id" != "0" ]; then
ip="$(gcr_vm_public_ip "$vm_id" || true)"
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" ttl \
"$attempt" || true
if gcr_vm_cleanup_start "$job_id" "$attempt" "$rec" ttl false; then
gcr_event "vm-destroyed" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"ttl\"}"
else
gcr_event "vm-cleanup-pending" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"ttl\"}"
fi
else
gcr_record_del "$job_id" "$attempt"
fi
gcr_event "job-ttl-expired" "$job_id" "{\"age\":$age}"
gcr_lock_release "$key"
fi
done
}
gcr_sweep_orphan_vms() {
vms_json="$(gcr_vm_list_managed)" || return 0
count="$(printf '%s' "$vms_json" | jq 'length')"
i=0
while [ "$i" -lt "$count" ]; do
vm="$(printf '%s' "$vms_json" | jq -c ".[$i]")"
vm_id="$(printf '%s' "$vm" | jq -r '.id')"
vm_name="$(printf '%s' "$vm" | jq -r '.name // ""')"
jid="$(printf '%s' "$vm" | jq -r '.labels["gcr.job-id"] // ""')"
att="$(printf '%s' "$vm" | jq -r '.labels["gcr.run-attempt"] // ""')"
if ! gcr_record_exists_for_vm_owner "$vm_id" "$vm_name" "$jid" "$att"; then
gcr_log warn --ns=sweep "orphan VM $vm_id job=$jid attempt=$att -> destroy"
cleanup_job="${jid:-orphan-$vm_id}"
cleanup_attempt="${att:-0}"
cleanup_rec="$(jq -n --arg j "$cleanup_job" --arg a "$cleanup_attempt" \
--arg v "$vm_id" --arg vn "$vm_name" \
'{job_id:$j, run_attempt:$a, repo:"", label:"", created_at:"0",
ttl_min:0, vm_id:($v|tonumber), vm_name:$vn,
bootstrapped:false, status:"cleanup_pending"}')"
if gcr_vm_cleanup_start "$cleanup_job" "$cleanup_attempt" \
"$cleanup_rec" orphan false; then
gcr_event "orphan-vm-destroyed" "$cleanup_job" "{\"vm_id\":$vm_id}"
else
gcr_event "vm-cleanup-pending" "$cleanup_job" \
"{\"vm_id\":$vm_id,\"reason\":\"orphan\"}"
fi
fi
i=$((i + 1))
done
}
gcr_alloc_deferred() {
job_id="$1"; attempt="$2"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || return 0
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -z "$rec" ] || [ "$(gcr_record_field "$rec" status)" != "deferred" ]; then
gcr_lock_release "$key"
return 0
fi
repo="$(gcr_record_field "$rec" repo)"
label="$(gcr_record_field "$rec" label)"
state="$(gcr_gitea_job_state "$repo" "$job_id")" || {
gcr_lock_release "$key"
return 0
}
case "$state" in
completed:*)
gcr_log info --ns=alloc "deferred job=$job_id already terminal ($state), dropping record"
gcr_record_del "$job_id" "$attempt"
gcr_lock_release "$key"
return 0
;;
esac
profile="$(gcr_label_profile "$label")" || {
gcr_lock_release "$key"
return 0
}
set -- $profile
server_type="$1"; ttl_min="$2"
gcr_lock_acquire admission || {
gcr_lock_release "$key"
return 0
}
active="$(gcr_count_active)"
repo_active="$(gcr_count_active_repo "$repo")"
if [ "$active" -ge "${GCR_CONCURRENCY_CAP:-2}" ] \
|| [ "$repo_active" -ge "${GCR_PER_REPO_CAP:-1}" ]; then
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
claim_status=0
gcr_claim_idle "$job_id" "$attempt" "$repo" "$label" || claim_status="$?"
if [ "$claim_status" -eq 0 ]; then
reused="$(gcr_record_get "$job_id" "$attempt")"
vm_id="$(gcr_record_field "$reused" vm_id)"
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "vm-rebuild-queued" "$job_id" \
"{\"vm_id\":$vm_id,\"label\":\"$label\",\"via\":\"deferred-retry\"}"
gcr_log info --ns=alloc "deferred job=$job_id claimed vm=$vm_id for rebuild"
return 0
fi
if [ "$claim_status" -eq 2 ]; then
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
vm_name="gcr-${job_id}-${attempt}"
created_at="$(gcr_now_epoch)"
create_pending="$(printf '%s' "$rec" | jq -c \
--arg t "$created_at" --arg ttl "$ttl_min" --arg vn "$vm_name" \
'.created_at = $t | .ttl_min = ($ttl | tonumber)
| .vm_id = "" | .vm_name = $vn | .runner_name = $vn
| .bootstrapped = false | .status = "create_pending"')"
if ! gcr_record_put "$job_id" "$attempt" "$create_pending"; then
gcr_lock_release admission
gcr_lock_release "$key"
return 0
fi
gcr_lock_release admission
create_status=0
created="$(gcr_vm_create "$vm_name" "$label" "$server_type" "$ttl_min" \
"" "$job_id" "$attempt" "$repo")" || create_status="$?"
if [ "$create_status" -ne 0 ] || [ -z "$created" ]; then
if [ "$create_status" -ne 2 ]; then
retry_rec="$(printf '%s' "$create_pending" | jq -c \
'.ttl_min = null | .vm_id = "" | .vm_name = ""
| .runner_name = "" | .status = "deferred"')"
if ! gcr_record_put "$job_id" "$attempt" "$retry_rec"; then
gcr_log error --ns=alloc \
"failed restoring deferred state job=$job_id after create failure"
fi
fi
gcr_lock_release "$key"
return 0
fi
set -- $created
vm_id="$1"; actual_server_type="$2"; actual_rate="$3"
actual_location="${4:-}"; actual_arch="${5:-}"; actual_image="${6:-}"
if ! gcr_vm_record_created "$job_id" "$attempt" "$repo" "$label" \
"$created_at" "$vm_id" "$vm_name" "$ttl_min" \
"$actual_server_type" "$actual_rate" "$actual_location" \
"$actual_arch" "$actual_image"; then
gcr_lock_release "$key"
return 0
fi
gcr_lock_release "$key"
gcr_event "vm-created" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\",\"ttl_min\":$ttl_min,\"via\":\"deferred-retry\"}"
gcr_log info --ns=alloc "deferred job=$job_id allocated vm=$vm_id"
}
gcr_sweep_cleanup_pending() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "cleanup_pending" ] || continue
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" = "cleanup_pending" ]; then
gcr_vm_cleanup_pending "$job_id" "$attempt" "$rec" || true
fi
gcr_lock_release "$key"
done
}
gcr_sweep_create_ambiguous() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "create_ambiguous" ] || continue
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" != "create_ambiguous" ]; then
gcr_lock_release "$key"
continue
fi
find_status=0
found_vm_id="$(gcr_vm_find_created \
"$(gcr_record_field "$rec" vm_name)" "$job_id" "$attempt" \
"$(gcr_record_field "$rec" label)" \
"$(gcr_record_field "$rec" server_type)" \
"$(gcr_record_field "$rec" candidate_location)" \
"$(gcr_record_field "$rec" candidate_arch)" \
"$(gcr_record_field "$rec" image_id)")" || find_status="$?"
case "$find_status" in
0)
rec="$(printf '%s' "$rec" | jq -c --arg vm "$found_vm_id" \
'.vm_id = ($vm | tonumber)
| .status = "pending_vm"
| .bootstrapped = false
| .runner_name = .vm_name
| .location = .candidate_location
| .arch = .candidate_arch
| del(.create_http, .create_curl_status,
.candidate_location, .candidate_arch,
.budget_reservation_key,
.budget_reservation_charged)')"
if gcr_record_put "$job_id" "$attempt" "$rec"; then
gcr_event "vm-create-recovered" "$job_id" \
"{\"vm_id\":$found_vm_id,\"label\":\"$(gcr_record_field "$rec" label)\"}"
fi
;;
1)
reservation_key="$(gcr_record_field "$rec" budget_reservation_key)"
refund_budget=true
if [ -n "$reservation_key" ]; then
refund_budget=false
if ! gcr_lock_acquire budget; then
gcr_lock_release "$key"
continue
fi
if gcr_budget_transaction_committed "$reservation_key" \
&& ! gcr_budget_transaction_committed \
"rollback-$reservation_key"; then
refund_budget=true
fi
gcr_lock_release budget
fi
rec="$(printf '%s' "$rec" | jq -c \
--argjson refund "$refund_budget" \
'.status = "cleanup_pending"
| .cleanup_reason = "ambiguous-create-absent"
| .cleanup_refund_budget = $refund
| .cleanup_vm_destroyed = true
| .cleanup_budget_released = false')"
if gcr_record_put "$job_id" "$attempt" "$rec"; then
gcr_vm_cleanup_pending "$job_id" "$attempt" "$rec" || true
fi
;;
2) ;;
esac
gcr_lock_release "$key"
done
}
gcr_sweep_retiring_vms() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "retiring_vm" ] || continue
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" = "retiring_vm" ]; then
retire_status=0
gcr_vm_retire_pending "$job_id" "$attempt" "$rec" || retire_status="$?"
case "$retire_status" in
0|2) ;;
*) gcr_log warn --ns=sweep "retirement retry failed job=$job_id" ;;
esac
fi
gcr_lock_release "$key"
done
}
gcr_rebuild_cleanup() {
rebuild_cleanup_job="$1"; rebuild_cleanup_attempt="$2"
rebuild_cleanup_rec="$3"; rebuild_cleanup_reason="$4"
rebuild_cleanup_vm="$(gcr_record_field "$rebuild_cleanup_rec" vm_id)"
if gcr_vm_cleanup_start "$rebuild_cleanup_job" "$rebuild_cleanup_attempt" \
"$rebuild_cleanup_rec" "$rebuild_cleanup_reason" false; then
gcr_event "vm-destroyed" "$rebuild_cleanup_job" \
"{\"vm_id\":$rebuild_cleanup_vm,\"reason\":\"$rebuild_cleanup_reason\"}"
else
gcr_event "vm-cleanup-pending" "$rebuild_cleanup_job" \
"{\"vm_id\":$rebuild_cleanup_vm,\"reason\":\"$rebuild_cleanup_reason\"}"
fi
}
gcr_reconcile_rebuild() {
rebuild_job="$1"; rebuild_attempt="$2"; rebuild_rec="$3"
rebuild_state="$(gcr_record_field "$rebuild_rec" status)"
rebuild_vm="$(gcr_record_field "$rebuild_rec" vm_id)"
if [ "$rebuild_state" = "rebuild_requesting" ]; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-request-uncertain
return 0
fi
rebuild_repo="$(gcr_record_field "$rebuild_rec" repo)"
rebuild_job_state="$(gcr_gitea_job_state "$rebuild_repo" "$rebuild_job")" \
|| return 0
case "$rebuild_job_state" in
completed:*)
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
job-completed-before-rebuild
return 0
;;
esac
rebuild_image="$(gcr_record_field "$rebuild_rec" rebuild_image_id)"
if [ "$rebuild_image" != "$(gcr_record_field "$rebuild_rec" image_id)" ] \
|| ! gcr_idle_profile_compatible "$rebuild_rec" \
"$(gcr_record_field "$rebuild_rec" label)"; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-profile-invalid
return 0
fi
if [ "$rebuild_state" = "rebuild_pending" ]; then
gcr_vm_host_key_prepare "$rebuild_job" "$rebuild_attempt" || return 1
rebuild_user_data="$(gcr_vm_host_key_userdata \
"$rebuild_job" "$rebuild_attempt")" || return 1
rebuild_requesting="$(printf '%s' "$rebuild_rec" | jq -c \
--arg now "$(gcr_now_epoch)" \
'.status = "rebuild_requesting"
| .rebuild_request_state = "requesting"
| .rebuild_requested_at = ($now | tonumber)')" || return 1
gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_requesting" \
|| return 1
rebuild_action="$(gcr_vm_rebuild_request "$rebuild_vm" "$rebuild_image" \
"$rebuild_user_data")" \
|| {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" \
"$rebuild_requesting" rebuild-request-uncertain
return 0
}
rebuild_rec="$(printf '%s' "$rebuild_requesting" | jq -c \
--arg action "$rebuild_action" \
'.status = "rebuild_running"
| .rebuild_request_state = "accepted"
| .rebuild_action_id = ($action | tonumber)')" || return 1
if ! gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_rec"; then
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" \
"$rebuild_requesting" rebuild-action-state-write-failed
return 0
fi
gcr_event "vm-rebuild-started" "$rebuild_job" \
"{\"vm_id\":$rebuild_vm,\"action_id\":$rebuild_action}"
fi
rebuild_action="$(gcr_record_field "$rebuild_rec" rebuild_action_id)"
rebuild_action_state="$(gcr_vm_rebuild_action_status \
"$rebuild_vm" "$rebuild_action")" || {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-action-uncertain
return 0
}
[ "$rebuild_action_state" = success ] || return 0
rebuild_ip="$(gcr_vm_verify_rebuilt "$rebuild_vm" \
"$(gcr_record_field "$rebuild_rec" server_type)" \
"$(gcr_record_field "$rebuild_rec" location)" \
"$(gcr_record_field "$rebuild_rec" arch)" "$rebuild_image")" || {
gcr_rebuild_cleanup "$rebuild_job" "$rebuild_attempt" "$rebuild_rec" \
rebuild-server-verification-failed
return 0
}
rebuild_ready="$(printf '%s' "$rebuild_rec" | jq -c \
--arg ip "$rebuild_ip" --arg now "$(gcr_now_epoch)" \
'.status = "pending_vm" | .bootstrapped = false | .ip = $ip
| .last_rebuild_action_id = .rebuild_action_id
| .last_rebuild_completed_at = ($now | tonumber)
| del(.rebuild_image_id, .rebuild_action_id,
.rebuild_request_state, .rebuild_requested_at)')" || return 1
gcr_record_put "$rebuild_job" "$rebuild_attempt" "$rebuild_ready" || return 1
gcr_event "vm-rebuild-completed" "$rebuild_job" \
"{\"vm_id\":$rebuild_vm,\"action_id\":$rebuild_action,\"ip\":\"$rebuild_ip\"}"
}
gcr_sweep_rebuilds() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
case "$(gcr_record_field "$rec" status)" in
rebuild_pending|rebuild_requesting|rebuild_running) ;;
*) continue ;;
esac
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
case "$(gcr_record_field "$rec" status)" in
rebuild_pending|rebuild_requesting|rebuild_running)
gcr_reconcile_rebuild "$job_id" "$attempt" "$rec" || \
gcr_log error --ns=sweep "rebuild reconcile failed job=$job_id"
;;
esac
gcr_lock_release "$key"
done
}
gcr_retry_deferred() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "deferred" ] || continue
gcr_alloc_deferred \
"$(gcr_record_field "$rec" job_id)" \
"$(gcr_record_field "$rec" run_attempt)"
done
}
gcr_sweep_stale_runners() {
oldIFS="$IFS"
IFS=,
for allowed_repo in ${GCR_ALLOWED_REPOS:-}; do
IFS="$oldIFS"
case "$allowed_repo" in
*/\*)
owner="${allowed_repo%/*}"
repos="$(gcr_gitea_list_owner_repos "$owner")" || {
IFS=,
continue
}
;;
*/*) repos="$allowed_repo" ;;
*) continue ;;
esac
while read -r repo; do
[ -n "${repo:-}" ] || continue
gcr_repo_allowed "$repo" || continue
runners="$(gcr_gitea_list_runners "$repo")" || continue
# Here-doc instead of pipe: dash runs pipe tails in a subshell, which
# would strand gcr_event/audit writes from the caller's perspective.
while read -r rid rname; do
[ -n "${rid:-}" ] || continue
case "$rname" in
gcr-*) ;;
*) continue ;;
esac
# Runner name stays tied to original VM across later job assignments.
rest="${rname#gcr-}"
jid="${rest%-*}"
if ! gcr_record_exists_for_runner "$repo" "$rname"; then
gcr_log warn --ns=sweep "stale repo=$repo registration id=$rid name=$rname -> retire"
if gcr_gitea_deregister_runner_exact "$repo" "$rname"; then
gcr_event "stale-runner-deleted" "${jid:-unknown}" "{\"repo\":\"$repo\",\"runner_id\":$rid,\"name\":\"$rname\"}"
else
gcr_log error --ns=sweep "failed deleting repo=$repo runner id=$rid"
fi
fi
done <<EOF
$runners
EOF
done <<EOF
$repos
EOF
IFS=,
done
IFS="$oldIFS"
}
# Runs SSH-push bootstrap for VMs that were created but not yet provisioned.
# Registration token is fetched fresh per attempt (short-lived usefulness).
gcr_bootstrap_pending() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
[ "$(gcr_record_field "$rec" status)" = "pending_vm" ] || continue
[ "$(gcr_record_field "$rec" bootstrapped)" = "true" ] && continue
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ "$(gcr_record_field "$rec" status)" != "pending_vm" ] \
|| [ "$(gcr_record_field "$rec" bootstrapped)" = "true" ]; then
gcr_lock_release "$key"
continue
fi
repo="$(gcr_record_field "$rec" repo)"
label="$(gcr_record_field "$rec" label)"
vm_id="$(gcr_record_field "$rec" vm_id)"
runner_name="$(gcr_record_field "$rec" runner_name)"
[ -n "$runner_name" ] || runner_name="$(gcr_record_field "$rec" vm_name)"
state="$(gcr_gitea_job_state "$repo" "$job_id")" || {
gcr_lock_release "$key"
continue
}
case "$state" in
completed:*)
gcr_log info --ns=sweep "pending job=$job_id already terminal ($state), destroying vm=$vm_id"
if [ -n "$vm_id" ] && [ "$vm_id" != "0" ] && [ "$vm_id" != "null" ]; then
case "$state" in
completed:success|completed:cancelled|completed:skipped) ;;
*)
ip="$(gcr_vm_public_ip "$vm_id" || true)"
gcr_vm_collect_diagnostics "$vm_id" "$ip" "$job_id" \
"$state" "$attempt" || true
;;
esac
if gcr_vm_cleanup_start "$job_id" "$attempt" "$rec" \
pending-job-completed false; then
gcr_event "vm-destroyed" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"pending-job-completed\",\"state\":\"$state\"}"
else
gcr_event "vm-cleanup-pending" "$job_id" \
"{\"vm_id\":$vm_id,\"reason\":\"pending-job-completed\"}"
fi
else
gcr_record_del "$job_id" "$attempt"
fi
gcr_lock_release "$key"
continue
;;
esac
ip="$(gcr_vm_public_ip "$vm_id")" || {
gcr_lock_release "$key"
continue
}
if [ -z "$ip" ]; then
gcr_lock_release "$key"
continue
fi
reg_token="$(gcr_gitea_registration_token "$repo")" || {
gcr_lock_release "$key"
continue
}
ttl_min="$(gcr_record_field "$rec" ttl_min)"
known_hosts_file="$(gcr_vm_known_hosts_file \
"$job_id" "$attempt" "$ip")" || {
gcr_log warn --ns=alloc \
"host-key pin unavailable vm=$vm_id job=$job_id"
gcr_lock_release "$key"
continue
}
gcr_log info --ns=alloc "bootstrapping vm=$vm_id ip=$ip job=$job_id"
if gcr_vm_bootstrap_ssh "$ip" "$label" "$reg_token" "$runner_name" \
"$known_hosts_file"; then
rec="$(printf '%s' "$rec" | jq -c '.bootstrapped = true | .ip = $ip' --arg ip "$ip")"
gcr_record_put "$job_id" "$attempt" "$rec"
gcr_event "vm-bootstrapped" "$job_id" "{\"vm_id\":$vm_id,\"ip\":\"$ip\"}"
else
gcr_log warn --ns=alloc "bootstrap failed vm=$vm_id (retry next tick)"
fi
gcr_lock_release "$key"
done
}
# Reap terminal jobs even when completed webhook path lags or is absent.
gcr_reap_finished_jobs() {
for f in $(gcr_active_records); do
rec="$(cat "$f")"
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active) ;;
*) continue ;;
esac
job_id="$(gcr_record_field "$rec" job_id)"
attempt="$(gcr_record_field "$rec" run_attempt)"
repo="$(gcr_record_field "$rec" repo)"
vm_id="$(gcr_record_field "$rec" vm_id)"
state="$(gcr_gitea_job_state "$repo" "$job_id")" || continue
case "$state" in
completed:*)
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || continue
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -z "$rec" ]; then
gcr_lock_release "$key"
continue
fi
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active) ;;
*) gcr_lock_release "$key"; continue ;;
esac
finish_status=0
gcr_vm_finish_terminal "$job_id" "$attempt" "$rec" "$state" reconcile \
|| finish_status="$?"
gcr_lock_release "$key"
case "$finish_status" in
0|2) ;;
*) return "$finish_status" ;;
esac
;;
esac
done
}
gcr_tick() {
gcr_sweep_create_ambiguous
gcr_sweep_cleanup_pending
gcr_sweep_retiring_vms
gcr_sweep_ttl
gcr_reap_finished_jobs
gcr_sweep_orphan_vms
gcr_retry_deferred
gcr_sweep_rebuilds
gcr_bootstrap_pending
gcr_sweep_stale_runners
}
gcr_main() {
: "${GCR_RECONCILE_INTERVAL_SEC:=60}"
gcr_state_init
gcr_log info --ns=core "controller starting, interval=${GCR_RECONCILE_INTERVAL_SEC}s state=$GCR_STATE_DIR"
gcr_tick
while :; do
sleep "$GCR_RECONCILE_INTERVAL_SEC"
if ! gcr_tick; then
gcr_log error --ns=core "tick failed, retrying next interval"
fi
done
}
+185
View File
@@ -0,0 +1,185 @@
#!/bin/dash
# Allocation decision for gitea-runner-controller.
# Fail-closed: anything not explicitly allowed here is refused.
#
# gcr_decide LABEL REPO -> prints "<server_type> <ttl_min> <rate_eur_h>" and
# returns 0 when allowed; returns 1 with reason on stderr otherwise.
gcr_server_hourly_rate() {
case "$1" in
cx23) printf '0.004' ;;
cx33) printf '0.008' ;;
cx43) printf '0.016' ;;
cx53) printf '0.032' ;;
cax21) printf '0.003' ;;
cax31) printf '0.006' ;;
cax41) printf '0.012' ;;
ccx53) printf '0.8550' ;;
cpx52) printf '0.036' ;;
cpx62) printf '0.072' ;;
*) return 1 ;;
esac
}
gcr_label_ttl() {
case "$1" in
ubuntu-latest|gross-x86) printf '180' ;;
gross-arm) printf '180' ;;
gross-x86-perf) printf '180' ;;
gross-mixed-econ) printf '180' ;;
nix) printf '480' ;;
gross-nix-x86) printf '180' ;;
gross-nix-arm) printf '180' ;;
gross-nix-x86-perf) printf '480' ;;
gross-nix-x86-highmem) printf '480' ;;
gross-nix-mixed-econ) printf '180' ;;
*) return 1 ;;
esac
}
# gcr_label_candidates LABEL -> lines: "<server_type> <location> <arch>"
gcr_label_candidates() {
label="$1"
case "$label" in
ubuntu-latest)
printf '%s\n' \
'cx23 nbg1 amd64' 'cx23 fsn1 amd64' 'cx23 hel1 amd64' \
'cx33 nbg1 amd64' 'cx33 fsn1 amd64' 'cx33 hel1 amd64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64'
;;
gross-x86)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64' \
'cx33 nbg1 amd64' 'cx33 fsn1 amd64' 'cx33 hel1 amd64'
;;
gross-arm)
printf '%s\n' \
'cax41 nbg1 arm64' 'cax41 fsn1 arm64' 'cax41 hel1 arm64' \
'cax31 nbg1 arm64' 'cax31 fsn1 arm64' 'cax31 hel1 arm64' \
'cax21 nbg1 arm64' 'cax21 fsn1 arm64' 'cax21 hel1 arm64'
;;
gross-x86-perf)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cpx62 nbg1 amd64' 'cpx62 fsn1 amd64' 'cpx62 hel1 amd64' \
'cpx52 nbg1 amd64' 'cpx52 fsn1 amd64' 'cpx52 hel1 amd64'
;;
gross-mixed-econ)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cax41 nbg1 arm64' 'cax41 fsn1 arm64' 'cax41 hel1 arm64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64'
;;
nix)
printf '%s\n' \
'cx23 nbg1 amd64' 'cx23 fsn1 amd64' 'cx23 hel1 amd64' \
'cx33 nbg1 amd64' 'cx33 fsn1 amd64' 'cx33 hel1 amd64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64'
;;
gross-nix-x86)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64' \
'cx33 nbg1 amd64' 'cx33 fsn1 amd64' 'cx33 hel1 amd64'
;;
gross-nix-arm)
printf '%s\n' \
'cax41 nbg1 arm64' 'cax41 fsn1 arm64' 'cax41 hel1 arm64' \
'cax31 nbg1 arm64' 'cax31 fsn1 arm64' 'cax31 hel1 arm64' \
'cax21 nbg1 arm64' 'cax21 fsn1 arm64' 'cax21 hel1 arm64'
;;
gross-nix-x86-perf)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cpx62 nbg1 amd64' 'cpx62 fsn1 amd64' 'cpx62 hel1 amd64' \
'cpx52 nbg1 amd64' 'cpx52 fsn1 amd64' 'cpx52 hel1 amd64'
;;
gross-nix-x86-highmem)
printf '%s\n' \
'ccx53 nbg1 amd64' 'ccx53 fsn1 amd64' 'ccx53 hel1 amd64'
;;
gross-nix-mixed-econ)
printf '%s\n' \
'cx53 nbg1 amd64' 'cx53 fsn1 amd64' 'cx53 hel1 amd64' \
'cax41 nbg1 arm64' 'cax41 fsn1 arm64' 'cax41 hel1 arm64' \
'cx43 nbg1 amd64' 'cx43 fsn1 amd64' 'cx43 hel1 amd64'
;;
*) return 1 ;;
esac
}
gcr_label_profile() {
label="$1"
ttl="$(gcr_label_ttl "$label")" || return 1
first="$(gcr_label_candidates "$label" | head -n1)" || return 1
set -- $first
rate="$(gcr_server_hourly_rate "$1")" || return 1
printf '%s %s %s' "$1" "$ttl" "$rate"
}
gcr_repo_allowed() {
repo="$1"
oldIFS="$IFS"
IFS=,
for allowed in ${GCR_ALLOWED_REPOS:-}; do
suffix="${allowed#*/}"
if [ "$suffix" = "*" ]; then
prefix="${allowed%/*}/"
case "$repo" in
"$prefix"*) IFS="$oldIFS"; return 0 ;;
esac
elif [ "$allowed" = "$repo" ]; then
IFS="$oldIFS"
return 0
fi
done
IFS="$oldIFS"
return 1
}
gcr_decide() {
label="$1"; repo="$2"
if ! gcr_repo_allowed "$repo"; then
gcr_log warn --ns=decide "repo not allowed: $repo"
return 1
fi
# Multi-label jobs are out of MVP scope: ambiguous VM profile mapping.
if ! profile="$(gcr_label_profile "$label")"; then
gcr_log warn --ns=decide "unknown or unsupported label: $label"
return 1
fi
printf '%s\n' "$profile"
}
gcr_count_active() {
count=0
for f in $(gcr_active_records); do
status="$(gcr_record_field "$(cat "$f")" status)"
case "$status" in
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending)
count=$((count + 1))
;;
esac
done
printf '%s' "$count"
}
gcr_count_active_repo() {
repo="$1"
count=0
for f in $(gcr_active_records); do
rec="$(cat "$f")"
case "$(gcr_record_field "$rec" status)" in
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending) ;;
*) continue ;;
esac
[ "$(gcr_record_field "$rec" repo)" = "$repo" ] && count=$((count + 1))
done
printf '%s' "$count"
}
@@ -0,0 +1,95 @@
{
symlinkJoin,
hectic,
dash,
socat,
curl,
jq,
coreutils,
gawk,
gnugrep,
gnused,
python3,
openssh,
}:
let
shell = "${dash}/bin/dash";
bashOptions = [
"errexit"
"nounset"
];
# SC2329: lib units are sourced wholesale into both binaries; the reconciler
# and webhook each leave a few wrapper functions unreferenced by design.
excludeShellChecks = [
"SC2086" # word splitting on purpose: env lists and profile triples
"SC2046" # same, command substitution into set --
"SC2329"
"SC2154"
];
runtimeDeps = [
curl
jq
coreutils
gawk
gnugrep
gnused
python3
openssh
];
lib = ''
${builtins.readFile ./log.sh}
${builtins.readFile ./state.sh}
${builtins.readFile ./decide.sh}
${builtins.readFile ./hcloud.sh}
${builtins.readFile ./gitea.sh}
'';
handler = hectic.writeShellApplication {
inherit shell bashOptions;
inherit excludeShellChecks;
name = "gcr-webhook-handler";
runtimeInputs = [ socat ] ++ runtimeDeps;
text = ''
${lib}
${builtins.readFile ./webhook.sh}
gcr_state_init
gcr_handle_webhook || gcr_respond 500 "internal error"
exit 0
'';
};
webhook = hectic.writeShellApplication {
inherit shell bashOptions;
inherit excludeShellChecks;
name = "gitea-runner-webhook";
runtimeInputs = [ socat ];
text = ''
: "''${GCR_LISTEN_ADDR:=127.0.0.1}"
: "''${GCR_LISTEN_PORT:=8787}"
exec ${socat}/bin/socat -T120 -t120 \
"TCP-LISTEN:$GCR_LISTEN_PORT,bind=$GCR_LISTEN_ADDR,reuseaddr,fork" \
EXEC:"${handler}/bin/gcr-webhook-handler",pipes
'';
};
controller = hectic.writeShellApplication {
inherit shell bashOptions;
inherit excludeShellChecks;
name = "gitea-runner-controller";
runtimeInputs = runtimeDeps;
text = ''
${lib}
${builtins.readFile ./controller.sh}
gcr_main
'';
};
in
symlinkJoin {
name = "gitea-runner-controller";
paths = [
controller
webhook
];
}
+197
View File
@@ -0,0 +1,197 @@
#!/bin/dash
# Gitea API wrappers for gitea-runner-controller.
# Requires: GCR_GITEA_URL, GITEA_REGISTRATION_TOKEN_FILE, GITEA_ADMIN_TOKEN_FILE
gcr_gitea_curl() {
gcr_gitea_admin_token >/dev/null || return 1
gitea_auth_header="$(mktemp "${TMPDIR:-/tmp}/gcr-gitea-auth.XXXXXX")" \
|| return 1
chmod 0600 "$gitea_auth_header"
if ! printf 'Authorization: token ' > "$gitea_auth_header" \
|| ! tr -d '\n' < "$GITEA_ADMIN_TOKEN_FILE" >> "$gitea_auth_header" \
|| ! printf '\n' >> "$gitea_auth_header"; then
rm -f "$gitea_auth_header"
return 1
fi
gitea_curl_status=0
curl -H "@$gitea_auth_header" "$@" || gitea_curl_status="$?"
rm -f "$gitea_auth_header"
return "$gitea_curl_status"
}
gcr_gitea_registration_token() {
repo="$1"
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
gcr_gitea_curl -fsS -X POST \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/registration-token" \
| jq -er '.token | select(type == "string" and length > 0)'
}
gcr_gitea_admin_token() {
test -r "${GITEA_ADMIN_TOKEN_FILE:-}" || {
gcr_log error --ns=gitea "GITEA_ADMIN_TOKEN_FILE missing"
return 1
}
tr -d '\n' < "$GITEA_ADMIN_TOKEN_FILE"
}
# gcr_gitea_list_runners REPO — prints "id name" lines for repo runners.
gcr_gitea_list_runners() {
repo="$1"
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
page=1
while :; do
runner_page="$(gcr_gitea_curl -fsS \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners?page=$page&limit=50")" \
|| return 1
printf '%s' "$runner_page" | jq -e \
'.runners | select(type == "array")
| all(.[]; (.id | type) == "number" and (.name | type) == "string")' \
>/dev/null || return 1
printf '%s' "$runner_page" \
| jq -r '.runners[] | "\(.id) \(.name)"' || return 1
runner_count="$(printf '%s' "$runner_page" | jq -er '.runners | length')" \
|| return 1
[ "$runner_count" -lt 50 ] && return 0
page=$((page + 1))
done
}
# gcr_gitea_list_owner_repos OWNER — prints fully-qualified repository names.
# Allowed owner globs may refer to either organizations or users. Probe the
# organization route first, then use the user route on a confirmed 404.
gcr_gitea_list_owner_repos() {
owner="$1"
gcr_gitea_admin_token >/dev/null || return 1
owner_kind=orgs
page=1
while :; do
owner_page="$(mktemp "${TMPDIR:-/tmp}/gcr-owner-repos.XXXXXX")" \
|| return 1
owner_status="$(gcr_gitea_curl -sS -o "$owner_page" -w '%{http_code}' \
"$GCR_GITEA_URL/api/v1/$owner_kind/$owner/repos?page=$page&limit=50")" \
|| { rm -f "$owner_page"; return 1; }
if [ "$owner_status" = 404 ] && [ "$owner_kind" = orgs ] && [ "$page" = 1 ]; then
owner_kind=users
rm -f "$owner_page"
continue
fi
[ "$owner_status" = 200 ] || {
rm -f "$owner_page"
return 1
}
jq -e 'type == "array"' "$owner_page" >/dev/null || {
rm -f "$owner_page"
return 1
}
jq -r '.[] | .full_name' "$owner_page"
count="$(jq 'length' "$owner_page")" || {
rm -f "$owner_page"
return 1
}
rm -f "$owner_page"
[ "$count" -lt 50 ] && return 0
page=$((page + 1))
done
}
# Compatibility name for callers outside active controller path.
gcr_gitea_list_org_repos() {
gcr_gitea_list_owner_repos "$1"
}
# gcr_gitea_job_state REPO JOB_ID — prints "<status>:<conclusion>".
gcr_gitea_job_state() {
repo="$1"; job_id="$2"
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
gcr_gitea_curl -fsS \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/jobs/$job_id" \
| jq -r '.status + ":" + (.conclusion // "")'
}
gcr_gitea_delete_runner() {
repo="$1"; id="$2"
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
gcr_gitea_curl -fsS -X DELETE \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/$id"
}
# Remove exactly one repository-scoped runner identity and confirm absence.
# A failed/ambiguous DELETE is safe only when a fresh list proves the exact
# name disappeared. Duplicate exact names fail closed for durable retry.
gcr_gitea_deregister_runner_exact() {
dereg_repo="$1"; dereg_name="$2"
[ -n "$dereg_repo" ] && [ -n "$dereg_name" ] || return 1
dereg_runners="$(gcr_gitea_list_runners "$dereg_repo")" || return 1
dereg_count=0
dereg_id=""
while read -r dereg_candidate_id dereg_candidate_name; do
[ "${dereg_candidate_name:-}" = "$dereg_name" ] || continue
case "$dereg_candidate_id" in ''|*[!0-9]*) return 1 ;; esac
dereg_count=$((dereg_count + 1))
dereg_id="$dereg_candidate_id"
done <<EOF
$dereg_runners
EOF
case "$dereg_count" in
0) return 0 ;;
1) ;;
*)
gcr_log error --ns=gitea \
"duplicate exact runner registrations repo=$dereg_repo name=$dereg_name"
return 1
;;
esac
if ! gcr_gitea_set_runner_disabled "$dereg_repo" "$dereg_id" true; then
gcr_log warn --ns=gitea \
"failed disabling runner repo=$dereg_repo name=$dereg_name"
return 1
fi
if ! gcr_gitea_delete_runner "$dereg_repo" "$dereg_id"; then
gcr_log warn --ns=gitea \
"runner DELETE uncertain repo=$dereg_repo name=$dereg_name; confirming"
fi
dereg_runners="$(gcr_gitea_list_runners "$dereg_repo")" || return 1
while read -r dereg_candidate_id dereg_candidate_name; do
[ "${dereg_candidate_name:-}" != "$dereg_name" ] || return 1
done <<EOF
$dereg_runners
EOF
return 0
}
gcr_gitea_set_runner_disabled() {
repo="$1"; id="$2"; disabled="$3"
case "$disabled" in true|false) ;; *) return 1 ;; esac
gcr_gitea_admin_token >/dev/null || return 1
owner="${repo%%/*}"
name="${repo#*/}"
gcr_gitea_curl -fsS -X PATCH \
-H 'Content-Type: application/json' --data "{\"disabled\":$disabled}" \
"$GCR_GITEA_URL/api/v1/repos/$owner/$name/actions/runners/$id" >/dev/null
}
# gcr_gitea_runner_disabled REPO RUNNER_NAME true|false
gcr_gitea_runner_disabled() {
repo="$1"; runner_name="$2"; disabled="$3"
runners="$(gcr_gitea_list_runners "$repo")" || return 1
while read -r id name; do
[ "$name" = "$runner_name" ] || continue
gcr_gitea_set_runner_disabled "$repo" "$id" "$disabled"
return "$?"
done <<EOF
$runners
EOF
return 1
}
+959
View File
@@ -0,0 +1,959 @@
#!/bin/dash
# Hetzner Cloud API wrappers for gitea-runner-controller.
# Requires: HCLOUD_TOKEN_FILE, GCR_HETZNER_LOCATION, GCR_IMAGE_ID,
# GCR_ACT_RUNNER_VERSION, GCR_ACT_RUNNER_SHA256, GCR_NIX_VERSION,
# GCR_NIX_TARBALL_SHA256, GCR_GITEA_URL
# All VMs carry the tag pair gitea-runner-controller=managed plus gcr.* metadata.
GCR_API="https://api.hetzner.cloud/v1"
gcr_image_id_for_arch() {
arch="$1"; label="${2:-}"
nix_image=0
case "$label" in nix|gross-nix-*) nix_image=1 ;; esac
case "$arch:$nix_image" in
amd64:0) [ -n "${GCR_IMAGE_ID:-}" ] && printf '%s' "$GCR_IMAGE_ID" ;;
arm64:0) [ -n "${GCR_ARM_IMAGE_ID:-}" ] && printf '%s' "$GCR_ARM_IMAGE_ID" ;;
amd64:1) [ -n "${GCR_NIX_IMAGE_ID:-}" ] && printf '%s' "$GCR_NIX_IMAGE_ID" ;;
arm64:1) [ -n "${GCR_ARM_NIX_IMAGE_ID:-}" ] && printf '%s' "$GCR_ARM_NIX_IMAGE_ID" ;;
*) return 1 ;;
esac
}
gcr_hcloud_token() {
test -n "${HCLOUD_TOKEN_FILE:-}" && test -r "$HCLOUD_TOKEN_FILE" || {
gcr_log error --ns=hcloud "HCLOUD_TOKEN_FILE missing or unreadable"
return 1
}
tr -d '\n' < "$HCLOUD_TOKEN_FILE"
}
gcr_vm_host_key_path() {
printf '%s/ssh-host-keys/%s' "$GCR_STATE_DIR" "$(gcr_alloc_key "$1" "$2")"
}
gcr_vm_host_key_prepare() {
host_key_path="$(gcr_vm_host_key_path "$1" "$2")"
if [ -s "$host_key_path" ] && [ -s "$host_key_path.pub" ]; then
return 0
fi
rm -f "$host_key_path" "$host_key_path.pub"
ssh-keygen -q -t ed25519 -N '' -C '' -f "$host_key_path" || return 1
chmod 0600 "$host_key_path"
chmod 0644 "$host_key_path.pub"
}
gcr_vm_host_key_userdata() {
host_key_path="$(gcr_vm_host_key_path "$1" "$2")"
[ -s "$host_key_path" ] && [ -s "$host_key_path.pub" ] || return 1
host_private_b64="$(base64 < "$host_key_path" | tr -d '\n')" || return 1
host_public_b64="$(base64 < "$host_key_path.pub" | tr -d '\n')" || return 1
cat <<EOF
#cloud-config
write_files:
- path: /etc/ssh/ssh_host_ed25519_key
owner: root:root
permissions: '0600'
encoding: b64
content: $host_private_b64
- path: /etc/ssh/ssh_host_ed25519_key.pub
owner: root:root
permissions: '0644'
encoding: b64
content: $host_public_b64
runcmd:
- [ sh, -c, 'systemctl restart sshd.service 2>/dev/null || systemctl restart ssh.service' ]
EOF
}
gcr_vm_known_hosts_file() {
known_job="$1"; known_attempt="$2"; known_ip="$3"
known_key_path="$(gcr_vm_host_key_path "$known_job" "$known_attempt")"
[ -s "$known_key_path.pub" ] || return 1
known_type="$(cut -d' ' -f1 < "$known_key_path.pub")"
known_key="$(cut -d' ' -f2 < "$known_key_path.pub")"
[ -n "$known_type" ] && [ -n "$known_key" ] || return 1
known_file="$known_key_path.known_hosts"
known_tmp="$(mktemp "$GCR_STATE_DIR/ssh-host-keys/.known-hosts.XXXXXX")" \
|| return 1
printf '%s %s %s\n' "$known_ip" "$known_type" "$known_key" > "$known_tmp" \
|| { rm -f "$known_tmp"; return 1; }
chmod 0600 "$known_tmp"
mv -f "$known_tmp" "$known_file" || return 1
printf '%s' "$known_file"
}
# All request state flows through files/exit codes, never command substitution
# ($( ) runs in a subshell and would strand GCR_REQ_FAILED/GCR_LAST_HTTP).
gcr_hcloud_req() {
# gcr_hcloud_req METHOD PATH [JSON_BODY]
# Body written to $GCR_LAST_BODY; exit 0 only on HTTP 2xx.
method="$1"; path="$2"; body="${3:-}"
gcr_hcloud_token >/dev/null || return 1
GCR_LAST_BODY="$(mktemp "${TMPDIR:-/tmp}/gcr-resp.XXXXXX")"
auth_header="$(mktemp "${TMPDIR:-/tmp}/gcr-hcloud-auth.XXXXXX")" || return 1
chmod 0600 "$auth_header"
if ! printf 'Authorization: Bearer ' > "$auth_header" \
|| ! tr -d '\n' < "$HCLOUD_TOKEN_FILE" >> "$auth_header" \
|| ! printf '\n' >> "$auth_header"; then
rm -f "$auth_header"
return 1
fi
curl_status=0
if [ -n "$body" ]; then
code="$(printf '%s' "$body" | curl -sS -X "$method" \
-H "@$auth_header" \
-H 'Content-Type: application/json' \
--data-binary @- \
-o "$GCR_LAST_BODY" \
-w '%{http_code}' \
"$GCR_API$path")" || curl_status="$?"
else
code="$(curl -sS -X "$method" \
-H "@$auth_header" \
-o "$GCR_LAST_BODY" \
-w '%{http_code}' \
"$GCR_API$path")" || curl_status="$?"
fi
rm -f "$auth_header"
case "$code" in ''|*[!0-9]*) code=000 ;; esac
GCR_LAST_CURL_STATUS="$curl_status"
GCR_LAST_HTTP="$code"
if [ "$curl_status" -ne 0 ]; then
gcr_log warn --ns=hcloud "transport failed path=$path curl=$curl_status http=$code"
return 1
fi
case "$code" in 2??) return 0 ;; esac
gcr_log warn --ns=hcloud "request failed path=$path http=$code body=$(head -c 200 "$GCR_LAST_BODY" | gcr_redact)"
return 1
}
gcr_vm_list_managed() {
managed_servers='[]'
managed_page=1
while :; do
gcr_hcloud_req GET \
"/servers?label_selector=gitea-runner-controller%3Dmanaged&per_page=50&page=$managed_page" \
|| return 1
managed_servers="$(jq -c --argjson current "$managed_servers" \
'$current + (.servers // [])' "$GCR_LAST_BODY")" || return 1
managed_next="$(jq -r '.meta.pagination.next_page // 0' "$GCR_LAST_BODY")" \
|| return 1
case "$managed_next" in
0|null) printf '%s' "$managed_servers" | jq -S .; return 0 ;;
''|*[!0-9]*) return 1 ;;
*) managed_page="$managed_next" ;;
esac
done
}
# Exact deterministic create identity. Exit 0 = one match (prints id),
# 1 = confirmed absent, 2 = lookup failed or identity invariant violated.
gcr_vm_find_created() {
find_name="$1"; find_job="$2"; find_attempt="$3"; find_label="$4"
find_type="$5"; find_location="$6"; find_arch="$7"; find_image="${8:-}"
if ! gcr_hcloud_req GET "/servers?name=$find_name"; then
return 2
fi
find_matches="$(jq -c \
--arg name "$find_name" --arg job "$find_job" --arg attempt "$find_attempt" \
--arg label "$find_label" --arg type "$find_type" \
--arg location "$find_location" --arg arch "$find_arch" \
--arg image "$find_image" \
'[.servers[] | select(
.name == $name
and .labels["gitea-runner-controller"] == "managed"
and .labels["gcr.job-id"] == $job
and .labels["gcr.run-attempt"] == $attempt
and .labels["gcr.label"] == $label
and .labels["gcr.location"] == $location
and .labels["gcr.arch"] == $arch
and ($image == "" or .labels["gcr.image-id"] == $image)
and ((.server_type.name // .server_type) == $type))]' \
"$GCR_LAST_BODY")" || return 2
find_count="$(printf '%s' "$find_matches" | jq 'length')" || return 2
case "$find_count" in
0) return 1 ;;
1) printf '%s' "$find_matches" | jq -r '.[0].id' ;;
*) return 2 ;;
esac
}
gcr_create_explicitly_rejected() {
case "$1" in
400|401|403|404|405|409|412|422|423) return 0 ;;
*) return 1 ;;
esac
}
gcr_vm_record_create_ambiguous() {
ambiguous_name="$1"; ambiguous_label="$2"; ambiguous_ttl="$3"
ambiguous_job="$4"; ambiguous_attempt="$5"; ambiguous_repo="$6"
ambiguous_type="$7"; ambiguous_rate="$8"; ambiguous_location="$9"
shift 9; ambiguous_arch="$1"; ambiguous_http="$2"; ambiguous_curl="$3"
ambiguous_image="${4:-}"
ambiguous_budget_key="${5:-}"
ambiguous_budget_reserved="${6:-false}"
case "$ambiguous_budget_reserved" in true|false) ;; *) return 1 ;; esac
ambiguous_rec="$(jq -n --arg j "$ambiguous_job" --arg a "$ambiguous_attempt" \
--arg r "$ambiguous_repo" --arg l "$ambiguous_label" \
--arg t "$(gcr_now_epoch)" --arg vn "$ambiguous_name" \
--arg ttl "$ambiguous_ttl" --arg st "$ambiguous_type" \
--arg rate "$ambiguous_rate" --arg loc "$ambiguous_location" \
--arg arch "$ambiguous_arch" --arg http "$ambiguous_http" \
--arg curl "$ambiguous_curl" --arg image "$ambiguous_image" \
--arg budget_key "$ambiguous_budget_key" \
--argjson budget_reserved "$ambiguous_budget_reserved" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:"", vm_name:$vn,
server_type:$st, budget_rate:$rate, candidate_location:$loc,
candidate_arch:$arch, image_id:$image,
create_http:$http, create_curl_status:$curl,
budget_reservation_key:$budget_key,
budget_reservation_charged:$budget_reserved,
bootstrapped:false,
status:"create_ambiguous"}')"
gcr_record_put "$ambiguous_job" "$ambiguous_attempt" "$ambiguous_rec"
}
gcr_vm_build_userdata() {
vm_name="$1"; label="$2"; reg_token="$3"
nix_conf='accept-flake-config = true
experimental-features = nix-command flakes
http2 = false
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false'
runner_config="log:
level: info
runner:
file: /var/lib/gitea-runner/.runner
capacity: 1
timeout: $(printf '%s' "$(gcr_label_profile "$label")" | awk '{print $2}')m
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
labels:
- \"$label:host\""
ssh_key_block=""
if [ -n "${GCR_DEBUG_SSH_PUBKEY:-}" ]; then
ssh_key_block=" - path: /root/.ssh/authorized_keys
permissions: '0600'
content: |
$GCR_DEBUG_SSH_PUBKEY"
fi
# NOTE(yukkop): token reaches only this VM's Hetzner metadata service and
# is used for initial registration, not for later idle-slot assignments.
printf '%s' "#cloud-config
write_files:
$ssh_key_block
- path: /etc/ssh/sshd_config.d/99-gcr-root.conf
permissions: '0644'
content: |
PermitRootLogin prohibit-password
PubkeyAuthentication yes
- path: /etc/nix/nix.conf
content: |
$(printf '%s\n' "$nix_conf" | sed 's/^/ /')
- path: /etc/gitea-runner/config.yaml
content: |
$(printf '%s\n' "$runner_config" | sed 's/^/ /')
- path: /etc/systemd/system/gitea-runner.service
content: |
[Unit]
Description=Gitea on-demand Actions runner
After=network-online.target gcr-bootstrap.service
Requires=gcr-bootstrap.service
[Service]
Type=simple
Environment=GITEA_INSTANCE_URL=$GCR_GITEA_URL
Environment=GITEA_RUNNER_REGISTRATION_TOKEN=$reg_token
ExecStart=/usr/local/bin/act_runner daemon --config /etc/gitea-runner/config.yaml
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
- path: /etc/systemd/system/gcr-bootstrap.service
content: |
[Unit]
Description=Bootstrap gitea-runner for ephemeral CI job
After=network-online.target
Wants=network-online.target
Before=gitea-runner.service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/local/sbin/gcr-bootstrap
[Install]
WantedBy=multi-user.target
- path: /usr/local/sbin/gcr-bootstrap
permissions: '0700'
content: |
#!/bin/sh
set -eu
exec > /var/log/gcr-bootstrap.log 2>&1
curl -fsSL \"https://nixos.org/releases/nix/$GCR_NIX_VERSION/nix-$GCR_NIX_VERSION-x86_64-linux.tar.xz\" -o /tmp/nix.tar.xz
printf '%s /tmp/nix.tar.xz\n' \"$GCR_NIX_TARBALL_SHA256\" | sha256sum -c -
tar -xJf /tmp/nix.tar.xz -C /tmp
/tmp/nix-$GCR_NIX_VERSION-x86_64-linux/install --no-daemon
rm -rf /tmp/nix*
curl -fsSL \"https://dl.gitea.com/gitea-runner/$GCR_ACT_RUNNER_VERSION/gitea-runner-$GCR_ACT_RUNNER_VERSION-linux-amd64\" -o /usr/local/bin/gitea-runner
printf '%s /usr/local/bin/gitea-runner\n' \"$GCR_ACT_RUNNER_SHA256\" | sha256sum -c -
chmod 0755 /usr/local/bin/gitea-runner
mkdir -p /var/lib/gitea-runner
runcmd:
- [ sh, -c, 'systemctl enable --now sshd.service 2>/dev/null || systemctl enable --now ssh 2>/dev/null || true' ]
- [ sh, -c, 'systemctl restart sshd.service 2>/dev/null || systemctl restart ssh 2>/dev/null || true' ]
- [ systemctl, enable, --now, gitea-runner.service ]
"
}
# gcr_vm_create NAME LABEL SERVER_TYPE TTL_MIN REG_TOKEN JOB_ID ATTEMPT REPO
# Reserves each affordable candidate under the short-lived budget lock, then
# releases it before provider I/O. Prints id, type, rate, location, arch, image.
gcr_vm_create() {
vm_name="$1"; label="$2"; ttl_min="$4"
reg_token="$5"; job_id="$6"; attempt="$7"; repo="$8"
create_nonce="${GCR_CREATE_NONCE:-$$-$(gcr_now_epoch)}"
gcr_vm_host_key_prepare "$job_id" "$attempt" || return 1
host_user_data="$(gcr_vm_host_key_userdata "$job_id" "$attempt")" || return 1
ttl_min="$(gcr_label_ttl "$label")" || return 1
candidates="$(gcr_label_candidates "$label")" || return 1
candidate_n=0
while read -r candidate_type candidate_loc candidate_arch; do
[ -n "${candidate_type:-}" ] || continue
candidate_n=$((candidate_n + 1))
candidate_rate="$(gcr_server_hourly_rate "$candidate_type")" || continue
image_id="$(gcr_image_id_for_arch "$candidate_arch" "$label")" || {
gcr_log warn --ns=hcloud \
"skip candidate[$candidate_n] label=$label arch=$candidate_arch no image"
continue
}
budget_key="create-$(gcr_alloc_key "$job_id" "$attempt")-$create_nonce-$candidate_n"
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" not-requested 0 "$image_id" \
"$budget_key" false; then
return 1
fi
gcr_lock_acquire budget || return 1
if ! gcr_budget_can_add "$candidate_rate" "$ttl_min"; then
gcr_lock_release budget
gcr_log info --ns=hcloud "skip candidate[$candidate_n] label=$label type=$candidate_type over budget"
continue
fi
if ! gcr_budget_add "$candidate_rate" "$ttl_min" "$budget_key"; then
gcr_lock_release budget
gcr_log error --ns=hcloud "budget reservation write failed label=$label type=$candidate_type"
return 1
fi
gcr_lock_release budget
budget_rec="$(gcr_record_get "$job_id" "$attempt")"
budget_rec="$(printf '%s' "$budget_rec" | jq -c \
'.budget_reservation_charged = true')" || return 2
gcr_record_put "$job_id" "$attempt" "$budget_rec" || return 2
payload="$(jq -n \
--arg name "$vm_name" \
--arg stype "$candidate_type" \
--arg image "$image_id" \
--arg loc "$candidate_loc" \
--arg jid "$job_id" \
--arg att "$attempt" \
--arg repo "$repo" \
--arg label "$label" \
--arg arch "$candidate_arch" \
--arg ts "$(date -u '+%s')" \
--arg ttl "$ttl_min" \
--arg ssh_key_id "${GCR_HCLOUD_SSH_KEY_ID:-}" \
--arg user_data "$host_user_data" \
--arg repo_safe "$(printf '%s' "$repo" | tr '/:' '--')" \
'{name:$name, server_type:$stype, image:$image, location:$loc,
user_data:$user_data,
start_after_create:true,
ssh_keys:(if $ssh_key_id == "" then [] else [$ssh_key_id | tonumber] end),
labels:{
"gitea-runner-controller":"managed",
"gcr.job-id":$jid, "gcr.run-attempt":$att,
"gcr.repo":$repo_safe, "gcr.label":$label,
"gcr.arch":$arch, "gcr.location":$loc,
"gcr.image-id":$image,
"gcr.created-at":$ts, "gcr.ttl-min":$ttl}}')"
gcr_log info --ns=hcloud "try candidate[$candidate_n] label=$label type=$candidate_type arch=$candidate_arch loc=$candidate_loc"
if gcr_hcloud_req POST /servers "$payload"; then
created_id="$(jq -er '.server.id | select(type == "number")' \
"$GCR_LAST_BODY")" || created_id=""
if [ -n "$created_id" ]; then
printf '%s %s %s %s %s %s\n' "$created_id" "$candidate_type" \
"$candidate_rate" "$candidate_loc" "$candidate_arch" "$image_id"
return 0
fi
create_http="${GCR_LAST_HTTP:-000}"
create_curl="${GCR_LAST_CURL_STATUS:-0}"
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" "$create_http" "$create_curl" \
"$image_id" "$budget_key" true; then
gcr_log error --ns=hcloud \
"cannot persist malformed successful create job=$job_id type=$candidate_type"
fi
return 2
fi
create_http="${GCR_LAST_HTTP:-000}"
create_curl="${GCR_LAST_CURL_STATUS:-0}"
find_status=0
found_vm_id="$(gcr_vm_find_created "$vm_name" "$job_id" "$attempt" \
"$label" "$candidate_type" "$candidate_loc" "$candidate_arch" \
"$image_id")" \
|| find_status="$?"
if [ "$find_status" -eq 0 ]; then
printf '%s %s %s %s %s %s\n' "$found_vm_id" "$candidate_type" \
"$candidate_rate" "$candidate_loc" "$candidate_arch" "$image_id"
return 0
fi
if [ "$find_status" -eq 1 ] \
&& gcr_create_explicitly_rejected "$create_http"; then
gcr_lock_acquire budget || return 1
if ! gcr_budget_sub "$candidate_rate" "$ttl_min" \
"rollback-$budget_key"; then
gcr_lock_release budget
gcr_log error --ns=hcloud "budget reservation rollback failed label=$label type=$candidate_type"
return 1
fi
gcr_lock_release budget
else
if ! gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$candidate_type" "$candidate_rate" \
"$candidate_loc" "$candidate_arch" "$create_http" "$create_curl" \
"$image_id" "$budget_key" true; then
gcr_log error --ns=hcloud "cannot persist ambiguous create job=$job_id type=$candidate_type"
fi
return 2
fi
if [ "$candidate_n" -le 3 ]; then
sleep 5
else
sleep 1
fi
done <<EOF
$candidates
EOF
return 1
}
# gcr_vm_destroy SERVER_ID — success means DELETE returned HTTP 2xx.
gcr_vm_destroy() {
if ! gcr_hcloud_req DELETE "/servers/$1"; then
gcr_log warn --ns=hcloud "destroy failed or already gone: server $1"
return 1
fi
}
# Only cleanup records establish prior ownership, making DELETE 404 a
# confirmed-absent success rather than an ambiguous lookup failure.
gcr_vm_destroy_owned() {
gcr_vm_destroy "$1" && return 0
[ "${GCR_LAST_HTTP:-}" = "404" ]
}
# Caller holds the lifecycle path's existing ownership locks.
gcr_vm_cleanup_pending() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_rec="$3"
cleanup_vm_id="$(gcr_record_field "$cleanup_rec" vm_id)"
if [ "$(gcr_record_field "$cleanup_rec" cleanup_vm_destroyed)" != "true" ]; then
gcr_vm_destroy_owned "$cleanup_vm_id" || return 1
cleanup_rec="$(printf '%s' "$cleanup_rec" | jq -c '.cleanup_vm_destroyed = true')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec" || return 1
fi
if [ "$(gcr_record_field "$cleanup_rec" cleanup_refund_budget)" = "true" ] \
&& [ "$(gcr_record_field "$cleanup_rec" cleanup_budget_released)" != "true" ]; then
cleanup_rate="$(gcr_record_field "$cleanup_rec" budget_rate)"
cleanup_ttl="$(gcr_record_field "$cleanup_rec" ttl_min)"
cleanup_refund_key="$(gcr_alloc_key "$cleanup_job" "$cleanup_attempt")"
gcr_lock_acquire budget || return 1
if ! gcr_budget_refund_once "$cleanup_refund_key" "$cleanup_rate" \
"$cleanup_ttl"; then
gcr_lock_release budget
return 1
fi
gcr_lock_release budget
cleanup_rec="$(printf '%s' "$cleanup_rec" | jq -c '.cleanup_budget_released = true')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec" || return 1
fi
gcr_record_del "$cleanup_job" "$cleanup_attempt"
}
# Persist cleanup ownership without provider I/O. Callers can use this while a
# short-lived coordination lock is held, release it, then run cleanup_pending.
gcr_vm_cleanup_intent() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_source="$3"
cleanup_reason="$4"; cleanup_refund="$5"
cleanup_rec="$(printf '%s' "$cleanup_source" | jq -c \
--arg reason "$cleanup_reason" --argjson refund "$cleanup_refund" \
'.status = "cleanup_pending"
| .cleanup_reason = $reason
| .cleanup_refund_budget = $refund
| .cleanup_vm_destroyed = false
| .cleanup_budget_released = false')"
gcr_record_put "$cleanup_job" "$cleanup_attempt" "$cleanup_rec"
}
# Persist intent before DELETE. Normal lifecycle teardown never changes budget;
# failed creation passes REFUND_BUDGET=true to release its unused reservation.
gcr_vm_cleanup_start() {
cleanup_job="$1"; cleanup_attempt="$2"; cleanup_source="$3"
cleanup_reason="$4"; cleanup_refund="$5"
gcr_vm_cleanup_intent "$cleanup_job" "$cleanup_attempt" "$cleanup_source" \
"$cleanup_reason" "$cleanup_refund" || return 1
cleanup_rec="$(gcr_record_get "$cleanup_job" "$cleanup_attempt")"
gcr_vm_cleanup_pending "$cleanup_job" "$cleanup_attempt" "$cleanup_rec"
}
# Caller holds allocation and admission locks. A failed primary write first
# persists cleanup ownership; reservation is released only after destroy.
gcr_vm_record_created() {
record_job="$1"; record_attempt="$2"; record_repo="$3"; record_label="$4"
record_created="$5"; record_vm_id="$6"; record_vm_name="$7"
record_ttl="$8"; record_type="$9"; shift 9; record_rate="$1"
record_location="${2:-}"; record_arch="${3:-}"; record_image="${4:-}"
record_rec="$(jq -n --arg j "$record_job" --arg a "$record_attempt" \
--arg r "$record_repo" --arg l "$record_label" --arg t "$record_created" \
--arg v "$record_vm_id" --arg vn "$record_vm_name" --arg ttl "$record_ttl" \
--arg st "$record_type" --arg rate "$record_rate" \
--arg loc "$record_location" --arg arch "$record_arch" \
--arg image "$record_image" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:($v|tonumber),
vm_name:$vn, runner_name:$vn, server_type:$st, budget_rate:$rate,
location:$loc, arch:$arch, image_id:$image,
bootstrapped:false, status:"pending_vm"}')"
gcr_record_put "$record_job" "$record_attempt" "$record_rec" && return 0
if ! gcr_vm_cleanup_start "$record_job" "$record_attempt" "$record_rec" \
state-write-failed true; then
cleanup_rec="$(gcr_record_get "$record_job" "$record_attempt")"
[ "$(gcr_record_field "$cleanup_rec" status)" = "cleanup_pending" ] && return 1
gcr_log error --ns=alloc "cannot persist cleanup record job=$record_job vm=$record_vm_id"
return 1
fi
return 1
}
gcr_vm_public_ip() {
# gcr_vm_public_ip SERVER_ID -> ipv4 or empty
if gcr_hcloud_req GET "/servers/$1"; then
jq -r '.server.public_net.ipv4.ip // ""' "$GCR_LAST_BODY"
fi
}
# POST rebuild starts an asynchronous clean-image replacement. Output is the
# validated action id; every malformed or mismatched response is uncertain.
gcr_vm_rebuild_request() {
rebuild_vm_id="$1"; rebuild_image_id="$2"; rebuild_user_data="${3:-}"
case "$rebuild_vm_id" in ''|0|*[!0-9]*) return 1 ;; esac
[ -n "$rebuild_image_id" ] || return 1
rebuild_payload="$(jq -n --arg image "$rebuild_image_id" \
--arg user_data "$rebuild_user_data" \
'{image:$image, user_data:$user_data}')" || return 1
gcr_hcloud_req POST "/servers/$rebuild_vm_id/actions/rebuild" \
"$rebuild_payload" || return 1
jq -er --arg vm "$rebuild_vm_id" \
'.action
| select((.id | type) == "number")
| select(.command == "rebuild")
| select(.status == "running" or .status == "success")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .id' "$GCR_LAST_BODY"
}
# Prints running or success. Provider-reported errors and malformed/mismatched
# action data fail closed; caller owns the durable cleanup transition.
gcr_vm_rebuild_action_status() {
rebuild_vm_id="$1"; rebuild_action_id="$2"
case "$rebuild_vm_id:$rebuild_action_id" in
*[!0-9:]*|0:*|*:0|:*|*::*|*:) return 1 ;;
esac
gcr_hcloud_req GET "/actions/$rebuild_action_id" || return 1
rebuild_status="$(jq -er --arg vm "$rebuild_vm_id" \
--arg action "$rebuild_action_id" \
'.action
| select((.id | tostring) == $action)
| select(.command == "rebuild")
| select([.resources[]? | select(.type == "server") | (.id | tostring)] == [$vm])
| .status
| select(. == "running" or . == "success" or . == "error")' \
"$GCR_LAST_BODY")" || return 1
[ "$rebuild_status" != error ] || return 1
printf '%s' "$rebuild_status"
}
# Successful action is insufficient by itself: verify provider server identity,
# immutable profile, clean image, running state, and current public IP.
gcr_vm_verify_rebuilt() {
verify_vm_id="$1"; verify_type="$2"; verify_location="$3"
verify_arch="$4"; verify_image="$5"
gcr_hcloud_req GET "/servers/$verify_vm_id" || return 1
jq -er --arg vm "$verify_vm_id" --arg type "$verify_type" \
--arg location "$verify_location" --arg arch "$verify_arch" \
--arg image "$verify_image" \
'.server
| select((.id | tostring) == $vm)
| select(.status == "running")
| select((.server_type.name // "") == $type)
| select((.server_type.architecture // "") == $arch)
| select((.datacenter.location.name // "") == $location)
| select((.image.id | tostring) == $image)
| .public_net.ipv4.ip
| select(type == "string" and length > 0)' "$GCR_LAST_BODY"
}
# Stop idle runners so Gitea cannot schedule work before atomic reuse claim.
# The controller starts the service only after the claim record is written.
gcr_vm_runner_service() {
vm_id="$1"; action="$2"
case "$action" in
start|stop) service_command="systemctl $action gitea-runner.service" ;;
health) service_command="systemctl is-active --quiet gitea-runner.service" ;;
*) return 1 ;;
esac
ip="$(gcr_vm_public_ip "$vm_id")" || return 1
[ -n "$ip" ] || return 1
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || return 1
test -n "${GCR_SSH_KNOWN_HOSTS_FILE:-}" \
&& test -r "$GCR_SSH_KNOWN_HOSTS_FILE" || return 1
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-runner-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$GCR_SSH_KNOWN_HOSTS_FILE -o ConnectTimeout=5 -o BatchMode=yes"
if timeout 30 ssh $ssh_opts "root@$ip" "$service_command"; then
rm -f "$key_tmp"
return 0
fi
rm -f "$key_tmp"
return 1
}
gcr_vm_collect_diagnostics() {
vm_id="$1"; ip="$2"; job_id="$3"; reason="$4"; diag_attempt="${5:-}"
[ "${GCR_DESTROY_DIAGNOSTICS:-1}" = "1" ] || return 0
[ -n "$ip" ] || return 0
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || {
gcr_log warn --ns=hcloud "skip diagnostics vm=$vm_id job=$job_id reason=$reason: SSH key unavailable"
return 0
}
diag_known_hosts="${GCR_SSH_KNOWN_HOSTS_FILE:-}"
if [ -n "$diag_attempt" ]; then
diag_known_hosts="$(gcr_vm_known_hosts_file \
"$job_id" "$diag_attempt" "$ip")" || diag_known_hosts=""
fi
test -n "$diag_known_hosts" && test -r "$diag_known_hosts" || {
gcr_log warn --ns=hcloud "skip diagnostics vm=$vm_id job=$job_id reason=$reason: SSH host key unavailable"
return 0
}
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-diag-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
timeout_sec="${GCR_DESTROY_DIAGNOSTICS_TIMEOUT_SEC:-20}"
ssh_opts="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$diag_known_hosts -o ConnectTimeout=5 -o BatchMode=yes"
diag_out="$(mktemp "${TMPDIR:-/tmp}/gcr-diag-out.XXXXXX")"
gcr_log warn --ns=hcloud "pre-destroy diagnostics begin vm=$vm_id ip=$ip job=$job_id reason=$reason timeout=${timeout_sec}s"
if timeout -k 5 "$timeout_sec" ssh $ssh_opts "root@$ip" \
'set +e
export LC_ALL=C
printf "== time ==\n"; date -u
printf "== uptime ==\n"; uptime
printf "== memory ==\n"; free -h
printf "== disk ==\n"; df -h / /nix /var/lib 2>/dev/null || df -h
printf "== pressure ==\n"; cat /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io 2>/dev/null
printf "== kernel failure signals ==\n"; dmesg -T 2>/dev/null | grep -Ei "out of memory|oom-kill|killed process|no space|I/O error|EXT4-fs error|xfs.*error|nvme.*error" | tail -n 80
printf "== runner service ==\n"; systemctl show gitea-runner.service -p ActiveState -p SubState -p Result -p ExecMainStatus -p ExecMainCode -p NRestarts 2>/dev/null
printf "== bootstrap service ==\n"; systemctl show gcr-bootstrap.service -p ActiveState -p SubState -p Result -p ExecMainStatus -p ExecMainCode 2>/dev/null
printf "== process sample ==\n"; ps -eo pid,ppid,stat,etime,comm 2>/dev/null | head -n 80' \
> "$diag_out" 2>&1; then
gcr_redact < "$diag_out" >&2
gcr_log warn --ns=hcloud "pre-destroy diagnostics complete vm=$vm_id job=$job_id reason=$reason"
else
gcr_redact < "$diag_out" >&2
gcr_log warn --ns=hcloud "pre-destroy diagnostics failed vm=$vm_id job=$job_id reason=$reason"
fi
rm -f "$key_tmp" "$diag_out"
return 0
}
# Retry durable repository-runner retirement. Generic idle is written only
# after exact-name absence is confirmed and the persisted VM profile is valid.
gcr_vm_retire_pending() {
retire_job="$1"; retire_attempt="$2"; retire_rec="$3"
[ "$(gcr_record_field "$retire_rec" status)" = "retiring_vm" ] || return 1
retire_vm_id="$(gcr_record_field "$retire_rec" vm_id)"
retire_expires="$(gcr_record_field "$retire_rec" idle_expires_at)"
retire_created="$(gcr_record_field "$retire_rec" created_at)"
retire_ttl="$(gcr_record_field "$retire_rec" ttl_min)"
case "$retire_vm_id:$retire_expires:$retire_created:$retire_ttl" in
*[!0-9:]*|0:*|:*|*::*|*:) return 1 ;;
esac
retire_now="$(gcr_now_epoch)"
retire_hard_expires="$((retire_created + retire_ttl * 60))"
if [ "$retire_now" -ge "$retire_expires" ] \
|| [ "$retire_now" -ge "$retire_hard_expires" ]; then
gcr_vm_cleanup_start "$retire_job" "$retire_attempt" "$retire_rec" \
retirement-expired false
return "$?"
fi
retire_repo="$(gcr_record_field "$retire_rec" retirement_repo)"
retire_runner="$(gcr_record_field "$retire_rec" retirement_runner_name)"
if ! gcr_gitea_deregister_runner_exact "$retire_repo" "$retire_runner"; then
gcr_log warn --ns=gitea \
"runner retirement pending job=$retire_job repo=$retire_repo name=$retire_runner"
return 2
fi
retire_idle="$(printf '%s' "$retire_rec" | jq -c \
'.status = "idle_vm"
| .repo = "" | .label = "" | .runner_name = ""
| .bootstrapped = false
| del(.retirement_repo, .retirement_runner_name)')" || return 1
gcr_record_put "$retire_job" "$retire_attempt" "$retire_idle" || return 1
gcr_event "vm-idle" "$retire_job" \
"{\"vm_id\":$retire_vm_id,\"expires_at\":$retire_expires}"
return 0
}
# Finish a terminal job under its allocation lock. Registration retirement is
# durable; every unsafe or incompatible transition uses cleanup_pending.
gcr_vm_finish_terminal() {
finish_job="$1"; finish_attempt="$2"; finish_rec="$3"; finish_state="$4"
finish_via="${5:-webhook}"
finish_vm_id="$(gcr_record_field "$finish_rec" vm_id)"
case "$finish_vm_id" in
''|0|null|*[!0-9]*)
gcr_record_del "$finish_job" "$finish_attempt"
return 0
;;
esac
case "$finish_state" in
completed:success|completed:cancelled|completed:skipped) ;;
completed:*)
finish_ip="$(gcr_vm_public_ip "$finish_vm_id" || true)"
gcr_vm_collect_diagnostics "$finish_vm_id" "$finish_ip" \
"$finish_job" "$finish_state" "$finish_attempt" || true
;;
esac
if finish_retiring_rec="$(gcr_record_retiring_json "$finish_rec")" \
&& gcr_idle_profile_compatible "$finish_retiring_rec" \
"$(gcr_record_field "$finish_rec" label)"; then
if ! gcr_record_put "$finish_job" "$finish_attempt" "$finish_retiring_rec"; then
finish_cleanup_reason=retirement-state-write-failed
else
gcr_event "vm-retiring" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"via\":\"$finish_via\"}"
gcr_vm_retire_pending "$finish_job" "$finish_attempt" \
"$finish_retiring_rec"
return "$?"
fi
else
finish_cleanup_reason=idle-profile-invalid
fi
if gcr_vm_cleanup_start "$finish_job" "$finish_attempt" "$finish_rec" \
"$finish_cleanup_reason" false; then
gcr_event "vm-destroyed" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
else
gcr_event "vm-cleanup-pending" "$finish_job" \
"{\"vm_id\":$finish_vm_id,\"reason\":\"$finish_cleanup_reason\",\"via\":\"$finish_via\"}"
fi
return 0
}
# Package bootstrap is SSH-pushed because image provisioning over cloud-init is
# not reliable enough for the full install. Cloud-init is limited to installing
# the controller-generated per-lifecycle SSH host key; strict verification must
# succeed before this token-bearing payload is sent.
gcr_bootstrap_script() {
# gcr_bootstrap_script LABEL REG_TOKEN TTL_MIN RUNNER_NAME -> POSIX sh payload
label="$1"; reg_token="$2"; ttl_min="$3"; runner_name="$4"
reg_token_b64="$(printf '%s' "$reg_token" | base64 | tr -d '\n')" \
|| return 1
nix_conf='accept-flake-config = true
experimental-features = nix-command flakes
http2 = false
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
sandbox = false'
runner_config="log:
level: info
runner:
file: /var/lib/gitea-runner/.runner
capacity: 1
timeout: ${ttl_min}m
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
labels:
- \"$label:host\""
cat <<BSEOF
exec >/var/log/gcr-bootstrap.log 2>&1
set -eu
mkdir -p /etc/nix /etc/gitea-runner /var/lib/gitea-runner /usr/local/bin
cat > /etc/nix/nix.conf <<'NIXEOF'
$nix_conf
NIXEOF
cat > /etc/gitea-runner/config.yaml <<'CFGEOF'
$runner_config
CFGEOF
cat > /usr/local/sbin/gcr-runner-start <<STARTEOF
#!/bin/sh
set -eu
exec /usr/local/bin/gitea-runner daemon --config /etc/gitea-runner/config.yaml
STARTEOF
chmod 0700 /usr/local/sbin/gcr-runner-start
cat > /etc/systemd/system/gitea-runner.service <<UNITEOF
[Unit]
Description=Gitea on-demand Actions runner
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/var/lib/gitea-runner
Environment=HOME=/var/lib/gitea-runner
ExecStart=/usr/local/sbin/gcr-runner-start
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
UNITEOF
cat > /usr/local/sbin/gcr-install <<INSEOF
#!/bin/sh
set -eu
nix_arch=""
nix_sha=""
case "$label" in
nix|gross-nix-*)
case "\$(uname -m)" in
x86_64)
nix_arch=x86_64-linux
nix_sha="$GCR_NIX_TARBALL_SHA256"
;;
aarch64|arm64)
nix_arch=aarch64-linux
nix_sha="$GCR_ARM_NIX_TARBALL_SHA256"
;;
*)
echo "unsupported arch for Nix bootstrap: $(uname -m)" >&2
exit 1
;;
esac
curl -fsSL "https://releases.nixos.org/nix/nix-$GCR_NIX_VERSION/nix-$GCR_NIX_VERSION-\\\$nix_arch.tar.xz" -o /tmp/nix.tar.xz
printf '%s /tmp/nix.tar.xz\n' "\\\$nix_sha" | sha256sum -c -
tar -xJf /tmp/nix.tar.xz -C /tmp
mkdir -p /nix
getent group nixbld >/dev/null 2>&1 || groupadd --system nixbld
for nixbld_user in 1 2 3 4 5 6 7 8 9 10; do
if ! id "nixbld\\\$nixbld_user" >/dev/null 2>&1; then
useradd --system --no-create-home --shell /usr/sbin/nologin \
--gid nixbld "nixbld\\\$nixbld_user"
fi
usermod --append --groups nixbld "nixbld\\\$nixbld_user"
done
/tmp/nix-$GCR_NIX_VERSION-\\\$nix_arch/install --no-daemon
ln -sf /root/.nix-profile/bin/nix /usr/local/bin/nix
rm -rf /tmp/nix*
;;
esac
case "$label" in
nix|gross-nix-*)
if command -v apt-get >/dev/null 2>&1; then
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nodejs
fi
;;
esac
case "\$(uname -m)" in
x86_64) runner_arch=amd64 ;;
aarch64|arm64) runner_arch=arm64 ;;
*) echo "unsupported arch for runner bootstrap: \$(uname -m)" >&2; exit 1 ;;
esac
curl -fsSL "https://dl.gitea.com/gitea-runner/$GCR_ACT_RUNNER_VERSION/gitea-runner-$GCR_ACT_RUNNER_VERSION-linux-\\\$runner_arch" -o /usr/local/bin/gitea-runner
if [ "\\\$runner_arch" = amd64 ]; then
printf '%s /usr/local/bin/gitea-runner\n' "$GCR_ACT_RUNNER_SHA256" | sha256sum -c -
fi
chmod 0755 /usr/local/bin/gitea-runner
INSEOF
chmod 0700 /usr/local/sbin/gcr-install
/usr/local/sbin/gcr-install
token_file=/run/gcr-registration-token
umask 077
printf '%s' '$reg_token_b64' | base64 -d > "\$token_file"
trap 'rm -f "\$token_file"' EXIT HUP INT TERM
if [ ! -s /var/lib/gitea-runner/.runner ]; then
/usr/local/bin/gitea-runner register --no-interactive \
--instance '$GCR_GITEA_URL' --token "\$(cat "\$token_file")" \
--name '$runner_name' --labels '$label:host' \
--config /etc/gitea-runner/config.yaml
fi
rm -f "\$token_file"
trap - EXIT HUP INT TERM
systemctl daemon-reload
systemctl enable --now gitea-runner.service
BSEOF
}
# gcr_vm_bootstrap_ssh IP LABEL REG_TOKEN — blocking; returns ssh exit status.
gcr_vm_bootstrap_ssh() {
ip="$1"; label="$2"; reg_token="$3"; runner_name="$4"
known_hosts_file="${5:-${GCR_SSH_KNOWN_HOSTS_FILE:-}}"
test -n "${GCR_SSH_PRIVKEY_FILE:-}" && test -r "$GCR_SSH_PRIVKEY_FILE" || {
gcr_log error --ns=hcloud "GCR_SSH_PRIVKEY_FILE missing or unreadable"
return 1
}
test -n "$known_hosts_file" && test -r "$known_hosts_file" || {
gcr_log error --ns=hcloud "SSH known-hosts file missing or unreadable"
return 1
}
key_tmp="$(mktemp "${TMPDIR:-/tmp}/gcr-sshkey.XXXXXX")"
cat "$GCR_SSH_PRIVKEY_FILE" > "$key_tmp"
printf '\n' >> "$key_tmp"
chmod 0600 "$key_tmp"
SSH_OPTS="-i $key_tmp -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$known_hosts_file -o ConnectTimeout=5 -o BatchMode=yes"
waited=0
until ssh $SSH_OPTS "root@$ip" true 2>/dev/null; do
waited=$((waited + 5))
[ "$waited" -ge 900 ] && {
gcr_log warn --ns=hcloud "sshd never came up on $ip"
rm -f "$key_tmp"
return 1
}
sleep 5
done
ttl_min="$(printf '%s' "$(gcr_label_profile "$label")" | awk '{print $2}')"
script="$(gcr_bootstrap_script "$label" "$reg_token" "$ttl_min" "$runner_name")"
if printf '%s' "$script" | ssh $SSH_OPTS "root@$ip" sh -s; then
rm -f "$key_tmp"
return 0
fi
rm -f "$key_tmp"
return 1
}
+77
View File
@@ -0,0 +1,77 @@
#!/bin/dash
# Log helper for gitea-runner-controller.
# Verbosity via GCR_LOG env: "<level>[;<ns>=<level>]..." e.g. "info;alloc=debug".
MAGENTA='\033[0;35m'
BLUE='\033[0;34m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
WHITE='\033[0;37m'
NC='\033[0m'
gcr_log_enabled() {
level="$1"
ns="${2:-core}"
conf="${GCR_LOG:-info}"
ns_level=""
default_level=""
oldIFS="$IFS"
IFS=';'
for pair in $conf; do
case "$pair" in
*=*) ns_name="${pair%%=*}"; ns_level="${pair#*=}"
[ "$ns_name" = "$ns" ] && { IFS="$oldIFS"; echo "$ns_level"; return 0; } ;;
*) default_level="$pair" ;;
esac
done
IFS="$oldIFS"
echo "${default_level:-info}"
}
gcr_log_level_rank() {
case "$1" in
trace) echo 0 ;;
debug) echo 1 ;;
info) echo 2 ;;
notice) echo 3 ;;
warn) echo 4 ;;
error) echo 5 ;;
panic) echo 6 ;;
*) echo 7 ;;
esac
}
gcr_log() {
level="$1"; shift
ns="core"
case "$1" in
--ns=*) ns="${1#--ns=}"; shift ;;
esac
want="$(gcr_log_enabled "$level" "$ns")"
[ "$(gcr_log_level_rank "$level")" -ge "$(gcr_log_level_rank "$want")" ] || return 0
ts="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
msg="$1"
case "$level" in
trace) color="$WHITE" ;;
debug) color="$BLUE" ;;
info) color="$GREEN" ;;
notice) color="$CYAN" ;;
warn) color="$YELLOW" ;;
error) color="$RED" ;;
panic) color="$MAGENTA" ;;
*) color="$WHITE" ;;
esac
printf '%b\n' "${color}${ts} ${level}[${ns}]${NC} $msg" >&2
}
# Security: keep credential values out of logs; keys containing TOKEN/SECRET
# and Authorization token headers are rewritten to <redacted>.
gcr_redact() {
sed -E \
-e 's/([A-Za-z0-9_]*(TOKEN|SECRET)[A-Za-z0-9_]*)(=|: ?"?)[^ "]+/\1\3<redacted>/g' \
-e 's/(Authorization: *token )[^ ]+/\1<redacted>/g'
}
+534
View File
@@ -0,0 +1,534 @@
#!/bin/dash
# State primitives for gitea-runner-controller.
# Layout:
# $GCR_STATE_DIR/jobs/<job_id>.json allocation records
# $GCR_STATE_DIR/jobs/.lock.<key>/ mkdir(2) atomicity guards
# $GCR_STATE_DIR/events.jsonl append-only audit
# $GCR_STATE_DIR/budget/<YYYY-MM> estimated EUR spent this month
gcr_state_init() {
test -n "${GCR_STATE_DIR:-}" || { echo "GCR_STATE_DIR is not set" >&2; return 1; }
mkdir -p "$GCR_STATE_DIR/jobs" "$GCR_STATE_DIR/budget"
mkdir -p "$GCR_STATE_DIR/ssh-host-keys"
chmod 0700 "$GCR_STATE_DIR/ssh-host-keys"
touch "$GCR_STATE_DIR/events.jsonl"
}
gcr_alloc_key() {
printf '%s-%s' "$1" "$2"
}
gcr_record_path() {
printf '%s/jobs/%s.json' "$GCR_STATE_DIR" "$(gcr_alloc_key "$1" "$2")"
}
# Atomic hard-link publication includes owner metadata before lock visibility.
# Legacy directory locks remain readable for safe upgrade/recovery.
gcr_lock_owner_read() {
if [ -f "$1" ]; then
cat "$1" 2>/dev/null || true
else
cat "$1/owner" 2>/dev/null || true
fi
}
gcr_lock_publish() {
gcr_publish_dir="$1"
gcr_publish_tmp="$gcr_publish_dir.owner.$$"
rm -f "$gcr_publish_tmp"
printf '%s %s\n' "$$" "$(gcr_now_epoch)" > "$gcr_publish_tmp" || return 1
if ln -T "$gcr_publish_tmp" "$gcr_publish_dir" 2>/dev/null; then
rm -f "$gcr_publish_tmp"
return 0
fi
rm -f "$gcr_publish_tmp"
return 1
}
gcr_lock_takeover() {
gcr_takeover_dir="$1"
gcr_takeover_old="$gcr_takeover_dir.reclaim.$$"
# Rename is atomic: exactly one reclaimer can move the observed stale
# directory. Never rm -rf the active lock pathname during recovery.
rm -rf "$gcr_takeover_old"
mv "$gcr_takeover_dir" "$gcr_takeover_old" 2>/dev/null || return 1
if gcr_lock_publish "$gcr_takeover_dir"; then
rm -rf "$gcr_takeover_old"
return 0
fi
rm -rf "$gcr_takeover_old"
return 1
}
gcr_lock_acquire() {
gcr_lock_key="$1"
gcr_lock_dir="$(printf '%s/jobs/.lock.%s' "$GCR_STATE_DIR" "$gcr_lock_key")"
if gcr_lock_publish "$gcr_lock_dir"; then
return 0
fi
gcr_lock_owner="$(gcr_lock_owner_read "$gcr_lock_dir")"
if [ -z "$gcr_lock_owner" ]; then
# A crash between mkdir and owner write leaves no PID. Give a live
# creator a short initialization window, then unblock hard TTL work.
gcr_lock_mtime="$(stat -c %Y "$gcr_lock_dir" 2>/dev/null || true)"
gcr_lock_now="$(gcr_now_epoch)"
case "$gcr_lock_mtime:$gcr_lock_now" in
*[!0-9:]*|:*|*::*|*:) return 1 ;;
esac
[ "$((gcr_lock_now - gcr_lock_mtime))" -ge 30 ] || return 1
gcr_lock_takeover "$gcr_lock_dir"
return "$?"
fi
set -- $gcr_lock_owner
gcr_lock_pid="${1:-}"
case "$gcr_lock_pid" in ''|*[!0-9]*) return 1 ;; esac
if kill -0 "$gcr_lock_pid" 2>/dev/null; then
return 1
fi
# Dead PID means a process crash, not live contention. Atomically take
# over its directory; concurrent recovery cannot erase a new lock.
gcr_lock_takeover "$gcr_lock_dir"
}
gcr_lock_release() {
gcr_release_dir="$(printf '%s/jobs/.lock.%s' "$GCR_STATE_DIR" "$1")"
gcr_release_owner="$(gcr_lock_owner_read "$gcr_release_dir")"
set -- $gcr_release_owner
[ "${1:-}" = "$$" ] || return 0
rm -rf "$gcr_release_dir"
}
gcr_record_get() {
# Missing record is a normal answer, not an error; must not trip errexit.
{ cat "$(gcr_record_path "$1" "$2")" 2>/dev/null || true; }
}
# mktemp+mv keeps concurrent readers away from partially written records.
gcr_record_put() {
tmp="$(mktemp "$(dirname "$(gcr_record_path "$1" "$2")")/.tmp.XXXXXX")"
printf '%s\n' "$3" > "$tmp"
mv -f "$tmp" "$(gcr_record_path "$1" "$2")"
}
gcr_record_del() {
rm -f "$(gcr_record_path "$1" "$2")"
rm -f "$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2")" \
"$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2").pub" \
"$GCR_STATE_DIR/ssh-host-keys/$(gcr_alloc_key "$1" "$2").known_hosts"
}
gcr_record_field() {
printf '%s' "$1" | jq -r --arg f "$2" 'if has($f) then .[$f] else "" end'
}
gcr_now_epoch() {
date -u '+%s'
}
# Healthy bootstrapped VMs can enter registration retirement until the next
# billing-hour boundary, but never beyond original hard TTL. The VM is not
# generic idle until the old repository registration is confirmed absent.
gcr_record_retiring_json() {
gcr_idle_rec="$1"
[ "$(gcr_record_field "$gcr_idle_rec" bootstrapped)" = "true" ] || return 1
gcr_idle_vm_id="$(gcr_record_field "$gcr_idle_rec" vm_id)"
gcr_idle_created="$(gcr_record_field "$gcr_idle_rec" created_at)"
gcr_idle_ttl="$(gcr_record_field "$gcr_idle_rec" ttl_min)"
case "$gcr_idle_vm_id:$gcr_idle_created:$gcr_idle_ttl" in
*[!0-9:]*|0:*|:*|*::*|*:) return 1 ;;
esac
gcr_idle_now="$(gcr_now_epoch)"
gcr_idle_hard_expires="$((gcr_idle_created + gcr_idle_ttl * 60))"
[ "$gcr_idle_now" -lt "$gcr_idle_hard_expires" ] || return 1
gcr_idle_age="$((gcr_idle_now - gcr_idle_created))"
[ "$gcr_idle_age" -ge 0 ] || gcr_idle_age=0
gcr_idle_slots="$((gcr_idle_age / 3600))"
[ "$((gcr_idle_age % 3600))" -eq 0 ] || gcr_idle_slots=$((gcr_idle_slots + 1))
[ "$gcr_idle_slots" -gt 0 ] || gcr_idle_slots=1
gcr_idle_expires="$((gcr_idle_created + gcr_idle_slots * 3600))"
[ "$gcr_idle_expires" -le "$gcr_idle_hard_expires" ] \
|| gcr_idle_expires="$gcr_idle_hard_expires"
gcr_idle_repo="$(gcr_record_field "$gcr_idle_rec" repo)"
gcr_idle_runner="$(gcr_record_field "$gcr_idle_rec" runner_name)"
[ -n "$gcr_idle_runner" ] \
|| gcr_idle_runner="$(gcr_record_field "$gcr_idle_rec" vm_name)"
[ -n "$gcr_idle_repo" ] && [ -n "$gcr_idle_runner" ] || return 1
printf '%s' "$gcr_idle_rec" | jq -c \
--arg now "$gcr_idle_now" --arg expires "$gcr_idle_expires" \
--arg repo "$gcr_idle_repo" --arg runner "$gcr_idle_runner" \
'.status = "retiring_vm"
| .bootstrapped = false
| .retirement_repo = $repo
| .retirement_runner_name = $runner
| .idle_since = ($now | tonumber)
| .idle_expires_at = ($expires | tonumber)'
}
# Compatibility alias for callers using the old helper name. Output follows
# the new fail-closed retirement contract, not the old directly-idle contract.
gcr_record_idle_json() {
gcr_record_retiring_json "$1"
}
gcr_idle_record_unexpired() {
gcr_idle_rec="$1"
[ "$(gcr_record_field "$gcr_idle_rec" status)" = "idle_vm" ] || return 1
gcr_idle_now="$(gcr_now_epoch)"
gcr_idle_vm_id="$(gcr_record_field "$gcr_idle_rec" vm_id)"
gcr_idle_vm_name="$(gcr_record_field "$gcr_idle_rec" vm_name)"
gcr_idle_type="$(gcr_record_field "$gcr_idle_rec" server_type)"
gcr_idle_location="$(gcr_record_field "$gcr_idle_rec" location)"
gcr_idle_arch="$(gcr_record_field "$gcr_idle_rec" arch)"
gcr_idle_image="$(gcr_record_field "$gcr_idle_rec" image_id)"
gcr_idle_expires="$(gcr_record_field "$gcr_idle_rec" idle_expires_at)"
gcr_idle_created="$(gcr_record_field "$gcr_idle_rec" created_at)"
gcr_idle_ttl="$(gcr_record_field "$gcr_idle_rec" ttl_min)"
case "$gcr_idle_expires:$gcr_idle_created:$gcr_idle_ttl" in
*[!0-9:]*|:*|*::*|*:) return 1 ;;
esac
case "$gcr_idle_vm_id" in ''|0|*[!0-9]*) return 1 ;; esac
[ -n "$gcr_idle_vm_name" ] || return 1
[ -n "$gcr_idle_type" ] && [ -n "$gcr_idle_location" ] \
&& [ -n "$gcr_idle_arch" ] && [ -n "$gcr_idle_image" ] || return 1
gcr_idle_hard_expires="$((gcr_idle_created + gcr_idle_ttl * 60))"
[ "$gcr_idle_now" -lt "$gcr_idle_expires" ] \
&& [ "$gcr_idle_now" -lt "$gcr_idle_hard_expires" ]
}
# Generic idle reuse is profile-based, never repository- or label-based. The
# exact persisted server tuple and clean image must be valid for the new label.
gcr_idle_profile_compatible() {
gcr_compat_rec="$1"; gcr_compat_label="$2"
gcr_compat_type="$(gcr_record_field "$gcr_compat_rec" server_type)"
gcr_compat_location="$(gcr_record_field "$gcr_compat_rec" location)"
gcr_compat_arch="$(gcr_record_field "$gcr_compat_rec" arch)"
gcr_compat_image="$(gcr_record_field "$gcr_compat_rec" image_id)"
[ -n "$gcr_compat_type" ] && [ -n "$gcr_compat_location" ] \
&& [ -n "$gcr_compat_arch" ] && [ -n "$gcr_compat_image" ] || return 1
gcr_compat_wanted_image="$(gcr_image_id_for_arch \
"$gcr_compat_arch" "$gcr_compat_label")" || return 1
[ "$gcr_compat_image" = "$gcr_compat_wanted_image" ] || return 1
while read -r gcr_compat_candidate_type gcr_compat_candidate_location \
gcr_compat_candidate_arch; do
[ -n "${gcr_compat_candidate_type:-}" ] || continue
if [ "$gcr_compat_candidate_type" = "$gcr_compat_type" ] \
&& [ "$gcr_compat_candidate_location" = "$gcr_compat_location" ] \
&& [ "$gcr_compat_candidate_arch" = "$gcr_compat_arch" ]; then
return 0
fi
done <<EOF
$(gcr_label_candidates "$gcr_compat_label")
EOF
return 1
}
gcr_idle_record_usable() {
gcr_idle_rec="$1"
gcr_idle_record_unexpired "$gcr_idle_rec" || return 1
gcr_idle_min_remaining="${GCR_RECONCILE_INTERVAL_SEC:-60}"
case "$gcr_idle_min_remaining" in ''|*[!0-9]*) return 1 ;; esac
[ "$((gcr_idle_expires - gcr_idle_now))" -ge "$gcr_idle_min_remaining" ] \
&& [ "$((gcr_idle_hard_expires - gcr_idle_now))" -ge "$gcr_idle_min_remaining" ]
}
# Caller must hold destination allocation lock. Global pool lock ensures one
# queued job claims an idle VM; destination write precedes source deletion so
# orphan/stale sweeps always see an owner during transfer.
gcr_claim_idle() {
gcr_claim_job="$1"; gcr_claim_attempt="$2"
gcr_claim_repo="$3"; gcr_claim_label="$4"
# Exit 2 means pool is busy; callers must defer instead of charging for a
# new VM without knowing whether matching paid capacity is available.
gcr_lock_acquire idle-pool || return 2
for gcr_claim_file in $(gcr_active_records); do
gcr_claim_rec="$(cat "$gcr_claim_file")"
[ "$(gcr_record_field "$gcr_claim_rec" status)" = "idle_vm" ] || continue
gcr_idle_record_usable "$gcr_claim_rec" || continue
gcr_idle_profile_compatible "$gcr_claim_rec" "$gcr_claim_label" || continue
gcr_claim_old_job="$(gcr_record_field "$gcr_claim_rec" job_id)"
gcr_claim_old_attempt="$(gcr_record_field "$gcr_claim_rec" run_attempt)"
gcr_claim_vm_id="$(gcr_record_field "$gcr_claim_rec" vm_id)"
gcr_claim_image="$(gcr_record_field "$gcr_claim_rec" image_id)"
gcr_record_vm_owned_elsewhere "$gcr_claim_vm_id" \
"$gcr_claim_old_job" "$gcr_claim_old_attempt" && continue
gcr_claim_now="$(gcr_now_epoch)"
gcr_claim_new="$(printf '%s' "$gcr_claim_rec" | jq -c \
--arg job "$gcr_claim_job" --arg attempt "$gcr_claim_attempt" \
--arg repo "$gcr_claim_repo" --arg label "$gcr_claim_label" \
--arg runner "gcr-${gcr_claim_job}-${gcr_claim_attempt}" \
--arg image "$gcr_claim_image" \
--arg now "$gcr_claim_now" \
'.job_id = $job | .run_attempt = $attempt
| .repo = $repo | .label = $label | .runner_name = $runner
| .status = "rebuild_pending"
| .bootstrapped = false
| .rebuild_image_id = $image
| .rebuild_action_id = ""
| .rebuild_request_state = "pending"
| .assigned_at = ($now | tonumber)
| del(.idle_since, .idle_expires_at,
.retirement_repo, .retirement_runner_name)')"
if ! gcr_record_put "$gcr_claim_job" "$gcr_claim_attempt" "$gcr_claim_new"; then
gcr_lock_release idle-pool
return 1
fi
gcr_record_del "$gcr_claim_old_job" "$gcr_claim_old_attempt"
gcr_lock_release idle-pool
return 0
done
gcr_lock_release idle-pool
return 1
}
gcr_record_exists_for_vm_id() {
gcr_lookup="$1"
for gcr_lookup_file in $(gcr_active_records); do
[ "$(gcr_record_field "$(cat "$gcr_lookup_file")" vm_id)" = "$gcr_lookup" ] \
&& return 0
done
return 1
}
# Provider sweeps also honor deterministic create ownership before vm_id is
# known locally. This closes the POST-success/state-write race without locks.
gcr_record_exists_for_vm_owner() {
gcr_owner_vm_id="$1"; gcr_owner_vm_name="$2"
gcr_owner_job="$3"; gcr_owner_attempt="$4"
gcr_record_exists_for_vm_id "$gcr_owner_vm_id" && return 0
[ -n "$gcr_owner_job" ] && [ -n "$gcr_owner_attempt" ] || return 1
gcr_owner_rec="$(gcr_record_get "$gcr_owner_job" "$gcr_owner_attempt")"
[ -n "$gcr_owner_rec" ] || return 1
[ "$(gcr_record_field "$gcr_owner_rec" vm_name)" = "$gcr_owner_vm_name" ] \
|| return 1
case "$(gcr_record_field "$gcr_owner_rec" status)" in
create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|idle_vm|rebuild_pending|rebuild_requesting|rebuild_running|cleanup_pending)
return 0
;;
esac
return 1
}
gcr_record_exists_for_runner() {
gcr_lookup_repo="$1"; gcr_lookup_runner="$2"
for gcr_lookup_file in $(gcr_active_records); do
gcr_lookup_rec="$(cat "$gcr_lookup_file")"
case "$(gcr_record_field "$gcr_lookup_rec" status)" in
retiring_vm)
gcr_lookup_owner_repo="$(gcr_record_field "$gcr_lookup_rec" retirement_repo)"
gcr_lookup_owner_runner="$(gcr_record_field "$gcr_lookup_rec" retirement_runner_name)"
;;
create_pending|pending_vm|vm_active|rebuild_pending|rebuild_requesting|rebuild_running)
gcr_lookup_owner_repo="$(gcr_record_field "$gcr_lookup_rec" repo)"
gcr_lookup_owner_runner="$(gcr_record_field "$gcr_lookup_rec" runner_name)"
;;
*) continue ;;
esac
if [ "$gcr_lookup_owner_repo" = "$gcr_lookup_repo" ] \
&& [ "$gcr_lookup_owner_runner" = "$gcr_lookup_runner" ]; then
return 0
fi
done
return 1
}
gcr_record_vm_owned_elsewhere() {
gcr_lookup_vm="$1"; gcr_lookup_job="$2"; gcr_lookup_attempt="$3"
for gcr_lookup_file in $(gcr_active_records); do
gcr_lookup_rec="$(cat "$gcr_lookup_file")"
[ "$(gcr_record_field "$gcr_lookup_rec" vm_id)" = "$gcr_lookup_vm" ] || continue
if [ "$(gcr_record_field "$gcr_lookup_rec" job_id)" != "$gcr_lookup_job" ] \
|| [ "$(gcr_record_field "$gcr_lookup_rec" run_attempt)" != "$gcr_lookup_attempt" ]; then
return 0
fi
done
return 1
}
gcr_event() {
printf '{"ts":"%s","event":"%s","job_id":"%s","detail":%s}\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$1" "$2" \
"$(printf '%s' "$3" | jq -Rs .)" >> "$GCR_STATE_DIR/events.jsonl"
}
# Exit-code contract: 0 = remains under budget, 1 = would exceed cap.
gcr_budget_can_add() {
rate="$1"; ttl_min="$2"
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
projected="$(awk -v c="$current" -v r="$rate" -v t="$ttl_min" 'BEGIN {printf "%.4f", c + r * t / 60}')"
if awk -v p="$projected" -v b="${GCR_BUDGET_EUR_MONTHLY:-15}" 'BEGIN {exit !(p > b)}'; then
return 1
fi
return 0
}
# Atomic replacement preserves last valid total when a write fails.
gcr_budget_write() {
gcr_budget_file="$1"; gcr_budget_value="$2"
gcr_budget_tmp="$(mktemp "$(dirname "$gcr_budget_file")/.budget.XXXXXX")" \
|| return 1
if ! printf '%s\n' "$gcr_budget_value" > "$gcr_budget_tmp"; then
rm -f "$gcr_budget_tmp"
return 1
fi
if ! mv -f "$gcr_budget_tmp" "$gcr_budget_file"; then
rm -f "$gcr_budget_tmp"
return 1
fi
}
# Caller holds budget lock. Transaction intent makes aggregate updates
# recoverable when a process exits between the total write and commit marker.
gcr_budget_add() {
rate="$1"; ttl_min="$2"
if [ "$#" -ge 3 ]; then
budget_txn_key="$3"
else
budget_key_tmp="$(mktemp "$GCR_STATE_DIR/budget/.transaction-key.XXXXXX")" \
|| return 1
budget_txn_key="add-${budget_key_tmp##*.transaction-key.}"
rm -f "$budget_key_tmp"
fi
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
projected="$(awk -v c="$current" -v r="$rate" -v t="$ttl_min" 'BEGIN {printf "%.4f", c + r * t / 60}')"
gcr_budget_transaction "$budget_txn_key" "$current" "$projected"
}
# Caller holds budget lock and is rolling back a matching budget addition.
gcr_budget_sub() {
rate="$1"; ttl_min="$2"
if [ "$#" -ge 3 ]; then
budget_txn_key="$3"
else
budget_key_tmp="$(mktemp "$GCR_STATE_DIR/budget/.transaction-key.XXXXXX")" \
|| return 1
budget_txn_key="sub-${budget_key_tmp##*.transaction-key.}"
rm -f "$budget_key_tmp"
fi
gcr_budget_recover_pending || return 1
month="$(date -u '+%Y-%m')"
file="$GCR_STATE_DIR/budget/$month"
current="$(cat "$file" 2>/dev/null || echo 0)"
projected="$(awk -v c="$current" -v r="$rate" -v t="$ttl_min" \
'BEGIN {v = c - r * t / 60; if (v < 0) v = 0; printf "%.4f", v}')"
gcr_budget_transaction "$budget_txn_key" "$current" "$projected"
}
gcr_budget_transaction() {
budget_txn_key="$1"; budget_txn_before="$2"; budget_txn_after="$3"
case "$budget_txn_key" in ''|*[!A-Za-z0-9_.-]*) return 1 ;; esac
budget_txn_month="$(date -u '+%Y-%m')"
budget_txn_file="$GCR_STATE_DIR/budget/$budget_txn_month"
budget_txn_root="$GCR_STATE_DIR/budget/transactions/$budget_txn_month"
budget_txn_dir="$budget_txn_root/$budget_txn_key"
mkdir -p "$budget_txn_root" || return 1
if [ -d "$budget_txn_dir" ]; then
gcr_budget_transaction_recover "$budget_txn_key"
return "$?"
fi
mkdir "$budget_txn_dir" 2>/dev/null || return 1
printf '%s\n' "$budget_txn_before" > "$budget_txn_dir/before" || return 1
printf '%s\n' "$budget_txn_after" > "$budget_txn_dir/after" || return 1
if ! gcr_budget_write "$budget_txn_file" "$budget_txn_after"; then
budget_txn_current="$(cat "$budget_txn_file" 2>/dev/null || echo 0)"
if [ "$budget_txn_current" = "$budget_txn_before" ]; then
rm -rf "$budget_txn_dir"
fi
return 1
fi
printf 'committed\n' > "$budget_txn_dir/status" || return 1
}
gcr_budget_transaction_recover() {
budget_recover_key="$1"
budget_recover_month="$(date -u '+%Y-%m')"
budget_recover_dir="$GCR_STATE_DIR/budget/transactions/$budget_recover_month/$budget_recover_key"
[ -d "$budget_recover_dir" ] || return 1
[ "$(cat "$budget_recover_dir/status" 2>/dev/null || true)" != committed ] \
|| return 0
budget_recover_before="$(cat "$budget_recover_dir/before" 2>/dev/null || true)"
budget_recover_after="$(cat "$budget_recover_dir/after" 2>/dev/null || true)"
if [ -z "$budget_recover_before" ] || [ -z "$budget_recover_after" ]; then
# Both metadata files are written before the aggregate total. A crash
# before either file completes therefore cannot have changed budget.
rm -rf "$budget_recover_dir"
return 0
fi
budget_recover_file="$GCR_STATE_DIR/budget/$budget_recover_month"
budget_recover_current="$(cat "$budget_recover_file" 2>/dev/null || echo 0)"
if [ "$budget_recover_current" = "$budget_recover_before" ]; then
gcr_budget_write "$budget_recover_file" "$budget_recover_after" || return 1
elif [ "$budget_recover_current" != "$budget_recover_after" ]; then
return 1
fi
printf 'committed\n' > "$budget_recover_dir/status" || return 1
}
gcr_budget_recover_pending() {
budget_pending_month="$(date -u '+%Y-%m')"
budget_pending_root="$GCR_STATE_DIR/budget/transactions/$budget_pending_month"
[ -d "$budget_pending_root" ] || return 0
for budget_pending_dir in "$budget_pending_root"/*; do
[ -d "$budget_pending_dir" ] || continue
budget_pending_key="${budget_pending_dir##*/}"
gcr_budget_transaction_recover "$budget_pending_key" || return 1
done
}
gcr_budget_transaction_committed() {
budget_committed_key="$1"
budget_committed_month="$(date -u '+%Y-%m')"
budget_committed_dir="$GCR_STATE_DIR/budget/transactions/$budget_committed_month/$budget_committed_key"
[ -d "$budget_committed_dir" ] || return 1
gcr_budget_transaction_recover "$budget_committed_key" || return 1
[ "$(cat "$budget_committed_dir/status" 2>/dev/null || true)" = committed ]
}
# Claim is durable before credit. Existing claim means credit is consumed:
# it may have completed, or it may have leaked fail-closed after a crash.
# Never subtract twice when outcome between aggregate and state writes is unknown.
gcr_budget_refund_once() {
refund_key="$1"; refund_rate="$2"; refund_ttl="$3"
refund_month="$(date -u '+%Y-%m')"
refund_root="$GCR_STATE_DIR/budget/refunds/$refund_month"
refund_claim="$refund_root/$refund_key"
mkdir -p "$refund_root" || return 1
if ! mkdir "$refund_claim" 2>/dev/null; then
if [ -d "$refund_claim" ]; then
if [ ! -f "$refund_claim/status" ]; then
gcr_log error --ns=budget \
"refund outcome uncertain key=$refund_key; retaining fail-closed claim"
fi
return 0
fi
return 1
fi
if ! printf '%s %s\n' "$refund_rate" "$refund_ttl" > "$refund_claim/intent"; then
return 1
fi
gcr_budget_sub "$refund_rate" "$refund_ttl" "refund-$refund_key" || return 1
printf 'refunded\n' > "$refund_claim/status" || return 1
}
gcr_active_records() {
grep -El '"status"[[:space:]]*:[[:space:]]*"(create_pending|create_ambiguous|pending_vm|vm_active|retiring_vm|idle_vm|rebuild_pending|rebuild_requesting|rebuild_running|deferred|cleanup_pending)"' "$GCR_STATE_DIR"/jobs/*.json 2>/dev/null || true
}
+354
View File
@@ -0,0 +1,354 @@
#!/bin/dash
# One-shot HTTP handler for Gitea workflow_job webhooks.
# Invoked per connection by socat; request on stdin, response on stdout.
RESPONSE_CODE=204
RESPONSE_BODY=""
gcr_respond() {
code="$1"; body="${2:-}"
reason=""
case "$code" in
200) reason="OK" ;;
202) reason="Accepted" ;;
204) reason="No Content" ;;
400) reason="Bad Request" ;;
403) reason="Forbidden" ;;
413) reason="Payload Too Large" ;;
*) reason="No Content" ;;
esac
printf 'HTTP/1.1 %s %s\r\n' "$code" "$reason"
printf 'Content-Type: text/plain\r\n'
printf 'Content-Length: %s\r\n' "$(printf '%s' "$body" | wc -c)"
printf 'Connection: close\r\n\r\n'
[ -n "$body" ] && printf '%s\n' "$body"
}
gcr_read_request() {
request_line=""
gcr_hdr_event_type=""
gcr_hdr_delivery=""
gcr_hdr_signature=""
content_length=0
# Correctness depends on dash reading stdin byte-by-byte (no lookahead
# buffer); body bytes must remain unconsumed for `head -c` below.
IFS= read -r request_line || return 1
while :; do
IFS= read -r line || break
line="$(printf '%s' "$line" | tr -d '\r')"
[ -z "$line" ] && break
name="$(printf '%s' "$line" | cut -d: -f1 | tr '[:upper:]' '[:lower:]')"
value="$(printf '%s' "${line#*:}" | sed 's/^ *//')"
case "$name" in
x-gitea-event-type) gcr_hdr_event_type="$value" ;;
x-gitea-delivery) gcr_hdr_delivery="$value" ;;
x-gitea-signature) gcr_hdr_signature="$value" ;;
content-length) content_length="$value" ;;
esac
done
case "$request_line" in
"POST "*" HTTP/"*) ;;
*) return 1 ;;
esac
case "$content_length" in
''|*[!0-9]*) return 1 ;;
esac
[ "$content_length" -le 65536 ] || { gcr_respond 413 "payload too large"; exit 0; }
GCR_BODY_FILE="$(mktemp "${TMPDIR:-/tmp}/gcr-webhook-body.XXXXXX")" \
|| return 1
chmod 0600 "$GCR_BODY_FILE"
trap 'rm -f "$GCR_BODY_FILE"' EXIT HUP INT TERM
head -c "$content_length" > "$GCR_BODY_FILE" || return 1
gcr_body="$(cat "$GCR_BODY_FILE")"
}
gcr_verify_signature() {
test -r "${GITEA_WEBHOOK_SECRET_FILE:-}" || {
gcr_log error --ns=webhook "GITEA_WEBHOOK_SECRET_FILE missing"
return 1
}
test -r "${GCR_BODY_FILE:-}" || return 1
expected="$(python3 - "$GITEA_WEBHOOK_SECRET_FILE" "$GCR_BODY_FILE" <<'PY'
import hashlib
import hmac
import pathlib
import sys
secret = pathlib.Path(sys.argv[1]).read_bytes().rstrip(b"\n")
body = pathlib.Path(sys.argv[2]).read_bytes()
print(hmac.new(secret, body, hashlib.sha256).hexdigest())
PY
)" || return 1
# NOTE(yukkop): shell string compare is not constant-time; acceptable here
# because the secret is high-entropy and bodies are signed, not encrypted.
[ "$expected" = "$gcr_hdr_signature" ]
}
gcr_alloc() {
job_id="$1"; attempt="$2"; repo="$3"; labels_json="$4"
label="$(printf '%s' "$labels_json" | jq -r '.[0] // ""')"
label_count="$(printf '%s' "$labels_json" | jq 'length')"
existing="$(gcr_record_get "$job_id" "$attempt")"
if [ -n "$existing" ]; then
gcr_log debug --ns=alloc "duplicate delivery for $(gcr_alloc_key "$job_id" "$attempt")"
RESPONSE_CODE=204
return 0
fi
key="$(gcr_alloc_key "$job_id" "$attempt")"
if ! gcr_lock_acquire "$key"; then
RESPONSE_CODE=204
return 0
fi
existing="$(gcr_record_get "$job_id" "$attempt")"
if [ -n "$existing" ]; then
gcr_lock_release "$key"
RESPONSE_CODE=204
return 0
fi
if [ "$label_count" -ne 1 ]; then
gcr_lock_release "$key"
gcr_event "refused" "$job_id" "{\"repo\":\"$repo\",\"label_count\":$label_count}"
RESPONSE_CODE=202; RESPONSE_BODY="refused: exactly one label required"
return 0
fi
if ! profile="$(gcr_decide "$label" "$repo")"; then
gcr_lock_release "$key"
gcr_event "refused" "$job_id" "{\"repo\":\"$repo\",\"label\":\"$label\"}"
RESPONSE_CODE=202; RESPONSE_BODY="refused: repo or label not allowed"
return 0
fi
set -- $profile
server_type="$1"; ttl_min="$2"
if ! gcr_lock_acquire admission; then
rec="$(jq -n --arg j "$job_id" --arg a "$attempt" --arg r "$repo" \
--arg l "$label" --arg t "$(gcr_now_epoch)" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:null, vm_id:"", vm_name:"",
status:"deferred"}')"
gcr_record_put "$job_id" "$attempt" "$rec"
gcr_lock_release "$key"
gcr_event "deferred" "$job_id" "{\"reason\":\"admission-busy\"}"
RESPONSE_CODE=202; RESPONSE_BODY="deferred: admission busy"
return 0
fi
active="$(gcr_count_active)"
repo_active="$(gcr_count_active_repo "$repo")"
if [ "$active" -ge "${GCR_CONCURRENCY_CAP:-2}" ] \
|| [ "$repo_active" -ge "${GCR_PER_REPO_CAP:-1}" ]; then
rec="$(jq -n --arg j "$job_id" --arg a "$attempt" --arg r "$repo" \
--arg l "$label" --arg t "$(gcr_now_epoch)" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:null, vm_id:"", vm_name:"",
status:"deferred"}')"
gcr_record_put "$job_id" "$attempt" "$rec"
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "deferred" "$job_id" "{\"active\":$active,\"repo_active\":$repo_active}"
RESPONSE_CODE=202; RESPONSE_BODY="deferred: capacity"
return 0
fi
claim_status=0
gcr_claim_idle "$job_id" "$attempt" "$repo" "$label" || claim_status="$?"
if [ "$claim_status" -eq 0 ]; then
reused="$(gcr_record_get "$job_id" "$attempt")"
vm_id="$(gcr_record_field "$reused" vm_id)"
vm_name="$(gcr_record_field "$reused" vm_name)"
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "vm-rebuild-queued" "$job_id" \
"{\"vm_id\":$vm_id,\"label\":\"$label\"}"
RESPONSE_CODE=202; RESPONSE_BODY="rebuilding $vm_name"
return 0
fi
if [ "$claim_status" -eq 2 ]; then
rec="$(jq -n --arg j "$job_id" --arg a "$attempt" --arg r "$repo" \
--arg l "$label" --arg t "$(gcr_now_epoch)" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:null, vm_id:"", vm_name:"",
status:"deferred"}')"
gcr_record_put "$job_id" "$attempt" "$rec"
gcr_lock_release admission
gcr_lock_release "$key"
gcr_event "deferred" "$job_id" "{\"reason\":\"idle-pool-busy\"}"
RESPONSE_CODE=202; RESPONSE_BODY="deferred: idle pool busy"
return 0
fi
vm_name="gcr-${job_id}-${attempt}"
created_at="$(gcr_now_epoch)"
create_pending="$(jq -n --arg j "$job_id" --arg a "$attempt" \
--arg r "$repo" --arg l "$label" --arg t "$created_at" \
--arg ttl "$ttl_min" --arg vn "$vm_name" \
'{job_id:$j, run_attempt:$a, repo:$r, label:$l,
created_at:$t, ttl_min:($ttl|tonumber), vm_id:"", vm_name:$vn,
runner_name:$vn, bootstrapped:false, status:"create_pending"}')"
if ! gcr_record_put "$job_id" "$attempt" "$create_pending"; then
gcr_lock_release admission
gcr_lock_release "$key"
RESPONSE_CODE=202; RESPONSE_BODY="VM state write failed"
return 0
fi
gcr_lock_release admission
create_status=0
created="$(gcr_vm_create "$vm_name" "$label" "$server_type" "$ttl_min" \
"" "$job_id" "$attempt" "$repo")" || create_status="$?"
if [ "$create_status" -ne 0 ]; then
if [ "$create_status" -eq 2 ]; then
gcr_event "vm-create-ambiguous" "$job_id" "{}"
RESPONSE_CODE=202; RESPONSE_BODY="VM creation pending recovery"
else
gcr_record_del "$job_id" "$attempt"
gcr_event "vm-create-failed" "$job_id" "{}"
RESPONSE_CODE=202; RESPONSE_BODY="VM creation failed"
fi
gcr_lock_release "$key"
return 0
fi
set -- $created
vm_id="$1"; actual_server_type="$2"; actual_rate="$3"
actual_location="${4:-}"; actual_arch="${5:-}"; actual_image="${6:-}"
if ! gcr_vm_record_created "$job_id" "$attempt" "$repo" "$label" \
"$created_at" "$vm_id" "$vm_name" "$ttl_min" \
"$actual_server_type" "$actual_rate" "$actual_location" \
"$actual_arch" "$actual_image"; then
created_rec="$(gcr_record_get "$job_id" "$attempt")"
gcr_vm_record_create_ambiguous "$vm_name" "$label" "$ttl_min" \
"$job_id" "$attempt" "$repo" "$actual_server_type" \
"$actual_rate" "$actual_location" "$actual_arch" \
"${GCR_LAST_HTTP:-201}" "${GCR_LAST_CURL_STATUS:-0}" \
"$actual_image" \
"$(gcr_record_field "$created_rec" budget_reservation_key)" true || true
gcr_lock_release "$key"
RESPONSE_CODE=202; RESPONSE_BODY="VM state write failed"
return 0
fi
gcr_lock_release "$key"
gcr_event "vm-created" "$job_id" "{\"vm_id\":$vm_id,\"label\":\"$label\",\"ttl_min\":$ttl_min}"
RESPONSE_CODE=202; RESPONSE_BODY="allocated $vm_name"
}
gcr_deallocate() {
job_id="$1"; attempt="$2"; new_status="$3"
expected_repo="${4:-}"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || return 0
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -z "$rec" ]; then
gcr_lock_release "$key"
return 0
fi
if [ -n "$expected_repo" ] \
&& [ "$(gcr_record_field "$rec" repo)" != "$expected_repo" ]; then
gcr_log warn --ns=alloc \
"repository mismatch for terminal job=$job_id expected=$expected_repo"
gcr_lock_release "$key"
return 0
fi
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active) ;;
*)
gcr_lock_release "$key"
return 0
;;
esac
finish_status=0
gcr_vm_finish_terminal "$job_id" "$attempt" "$rec" "$new_status" webhook \
|| finish_status="$?"
gcr_lock_release "$key"
case "$finish_status" in
0|2) return 0 ;;
*) return "$finish_status" ;;
esac
}
gcr_mark_in_progress() {
job_id="$1"; attempt="$2"; expected_repo="${3:-}"
key="$(gcr_alloc_key "$job_id" "$attempt")"
gcr_lock_acquire "$key" || return 0
rec="$(gcr_record_get "$job_id" "$attempt")"
if [ -n "$expected_repo" ] \
&& [ "$(gcr_record_field "$rec" repo)" != "$expected_repo" ]; then
gcr_log warn --ns=alloc \
"repository mismatch for in-progress job=$job_id expected=$expected_repo"
gcr_lock_release "$key"
return 0
fi
case "$(gcr_record_field "$rec" status)" in
pending_vm|vm_active)
rec="$(printf '%s' "$rec" | jq -c '.status = "vm_active"')"
gcr_record_put "$job_id" "$attempt" "$rec"
;;
esac
gcr_lock_release "$key"
}
gcr_handle_webhook() {
gcr_read_request || { gcr_respond 400 ""; exit 0; }
[ "$gcr_hdr_event_type" = "workflow_job" ] || {
gcr_log debug --ns=webhook "ignored event type: $gcr_hdr_event_type"
gcr_respond 204 ""; exit 0
}
gcr_verify_signature || {
gcr_log warn --ns=webhook "invalid signature, delivery=$gcr_hdr_delivery"
gcr_respond 403 "invalid signature"; exit 0
}
action="$(printf '%s' "$gcr_body" | jq -r '.action // ""')"
job_id="$(printf '%s' "$gcr_body" | jq -r '.workflow_job.id // ""')"
attempt="$(printf '%s' "$gcr_body" | jq -r '.workflow_job.run_attempt // ""')"
conclusion="$(printf '%s' "$gcr_body" | jq -r '.workflow_job.conclusion // ""')"
repo="$(printf '%s' "$gcr_body" | jq -r '.repository.full_name // ""')"
labels_json="$(printf '%s' "$gcr_body" | jq -c '.workflow_job.labels // []')"
[ -n "$action" ] && [ -n "$repo" ] \
|| { gcr_respond 400 "malformed payload"; exit 0; }
case "$job_id:$attempt" in
*[!0-9:]*|:*|*::*|*:|0:*)
gcr_respond 400 "malformed payload"; exit 0
;;
esac
case "$action" in
queued)
gcr_alloc "$job_id" "$attempt" "$repo" "$labels_json"
gcr_log info --ns=alloc "queued job=$job_id repo=$repo code=$RESPONSE_CODE $RESPONSE_BODY"
;;
in_progress)
gcr_mark_in_progress "$job_id" "$attempt" "$repo"
RESPONSE_CODE=204
;;
completed)
gcr_deallocate "$job_id" "$attempt" \
"completed:${conclusion:-unknown}" "$repo"
RESPONSE_CODE=204
;;
*)
gcr_log debug --ns=webhook "unhandled action: $action"
RESPONSE_CODE=204
;;
esac
gcr_respond "$RESPONSE_CODE" "$RESPONSE_BODY"
}
+2 -1
View File
@@ -56,7 +56,8 @@ dockerTools.buildLayeredImageWithNixDb {
accept-flake-config = true
experimental-features = nix-command flakes
substituters = https://cache.nixos.org https://cache.hectic-lab.com/hectic
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gW4x6l1xP+GxgH0r7u+f6p1VFlr0= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
http2 = false
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hectic:KMQsKow4SoA9K2vOJlOljmx7/Zpf91Yy+5qEtxDDCzA=
trusted-users = root
sandbox = false
EOF
+15 -12
View File
@@ -18,20 +18,26 @@
let
pname = "gitea";
version = "1.26.2";
version = "1.27.3";
src = ./source;
pnpm = pnpm_10;
pnpmPatches = [ ./pnpm-engine.patch ];
frontend = stdenv.mkDerivation {
pname = "gitea-frontend";
inherit src version;
patches = pnpmPatches;
pnpmDeps = fetchPnpmDeps {
pname = "gitea-frontend";
inherit version src;
inherit pnpm;
patches = pnpmPatches;
fetcherVersion = 3;
hash = "sha256-Qo0DLuZv+2GVLsBfCv/6CC9E/qhSE4HwV4StQL4HX4Y=";
prePnpmInstall = ''
pnpm config set engine-strict false
'';
hash = "sha256-H1sNMKRkoPlkheJFJVaof4bJ4gQHnbhosJaUqj9X8Gg=";
};
nativeBuildInputs = [
@@ -40,6 +46,10 @@ let
pnpm
];
prePnpmInstall = ''
pnpm config set engine-strict false
'';
buildPhase = ''
make frontend
'';
@@ -54,7 +64,8 @@ buildGo126Module rec {
inherit pname version src;
proxyVendor = true;
vendorHash = "sha256-7+M1n8RSgB3gZ/2na4RF9kYOf90H0bnsJZMDKpgAy64=";
deleteVendor = true;
vendorHash = "sha256-YRBMGWKIZgMxOXaXG2bIBj1XzkhSwiMyfRy+yQGw+Bo=";
outputs = [
"out"
@@ -63,17 +74,8 @@ buildGo126Module rec {
patches = [ ./static-root-path.patch ];
overrideModAttrs = _: {
postPatch = ''
substituteInPlace go.mod \
--replace-fail "go 1.26.3" "go 1.26"
'';
};
postPatch = ''
substituteInPlace modules/setting/server.go --subst-var data
substituteInPlace go.mod \
--replace-fail "go 1.26.3" "go 1.26"
'';
subPackages = [ "." ];
@@ -93,6 +95,7 @@ buildGo126Module rec {
];
postInstall = ''
mv "$out/bin/gitea.dev" "$out/bin/gitea"
mkdir $data
ln -s ${frontend}/public $data/public
cp -R ./{templates,options} $data
+13
View File
@@ -0,0 +1,13 @@
diff --git a/package.json b/package.json
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"type": "module",
- "packageManager": "pnpm@11.9.0",
+ "packageManager": "pnpm@10.12.4",
"engines": {
"node": ">= 22.18.0",
- "pnpm": ">= 11.0.0"
+ "pnpm": ">= 10.0.0"
},

Some files were not shown because too many files have changed in this diff Show More