diff --git a/.env.example b/.env.example index 93f52a50..9b1dd0d5 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,8 @@ HADES_EXECUTOR="docker" # Executor to use for running jobs (options: docker, k8s ### HadesScheduler Options ### CONCURRENCY=1 # Number of jobs to run concurrently (default: 1) +NATS_ACK_WAIT=1m # How long JetStream waits for an ack before redelivering a job to another worker; a liveness backstop, not a job-duration budget (default: 1m, minimum: 300ms) +NATS_MAX_DELIVER=3 # Max deliveries per job; the last one publishes a terminal Failed status instead of running the job again (minimum: 2, default: 3) ### HadesOperator Options ### WATCH_NAMESPACE="hades" diff --git a/AGENTS.md b/AGENTS.md index 86abd564..4cc9ce6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,7 @@ Go workspace (`go.work`, Go 1.26) with five modules: - **Status subjects:** `hades.jobstatus.{Queued,Running,Succeeded,Failed,Stopped}` (payload = job ID string, optional `X-Hades-Reason` header). `HadesAPI` publishes `Queued` on enqueue; the scheduler/operator publish `Running`/`Succeeded`/`Failed`. Nothing publishes `Stopped` today. `HadesLogManager` and the dashboard subscribe to the whole `hades.jobstatus.*` lifecycle over **core NATS**. - **Status stream:** `HADES_JOB_STATUS` is a JetStream stream over `hades.jobstatus.*` that durably captures those same core-NATS publishes. `HadesLogManager` consumes it through the durable `HADES_STATUS_WEBHOOK` consumer to deliver the **job-status webhook** (`status_callback_url`). Publishers are unchanged and core subscribers still receive every event. - **Log subjects:** see `shared/buildlogs/buildlog_stream.go`. +- **Job leases:** the scheduler acks a job only after the executor returns, and the Docker executor blocks for the whole job. `shared/nats/consumer.go` therefore heartbeats `msg.InProgress()` on a ticker while a job runs so the `NATS_ACK_WAIT` (default 1m) timer keeps resetting - job duration must never determine AckWait. `NATS_MAX_DELIVER` (default 3) caps redeliveries; the last delivery is not executed but publishes a terminal `Failed` status and terminates the message. - **Job DTO:** `shared/payload/payload.go` (`QueuePayload` with ordered `Step`s). Job-level: `timeout_seconds` (whole-job timeout). Each step has `image`, optional `script`, `metadata` env vars, `cpu_limit` (whole cores), `memory_limit`, and the Docker-only limits `network`, `memory_swap`, `pids_limit`. - **Two outbound pushes, do not conflate them:** `callback_url` forwards the aggregated **log array** and only after `stopWatchingJobLogs` drains the JetStream log consumer; `status_callback_url` receives the **job-status webhook** (`{event, job_id, name, status, reason, queued_at, started_at, finished_at, duration_ms, attempt}`) on the terminal status itself, with at-least-once retry. Neither may be repurposed as the other. - **Executor parity:** `timeout_seconds`, env (`metadata`), `cpu_limit`, `memory_limit` are enforced on both executors (Kubernetes: per-container resources + Job `activeDeadlineSeconds`). `network`, `memory_swap`, `pids_limit` are enforced on the **Docker executor only**; the operator accepts them for schema parity but does not apply them (pod containers share a network namespace; no per-container swap/PID field). diff --git a/HadesScheduler/HadesOperator/go.sum b/HadesScheduler/HadesOperator/go.sum index 13806903..bec75b95 100644 --- a/HadesScheduler/HadesOperator/go.sum +++ b/HadesScheduler/HadesOperator/go.sum @@ -1,23 +1,51 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= +github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M= +github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k= github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU= github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78= @@ -29,6 +57,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= @@ -88,6 +118,28 @@ github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJn github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= +github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= +github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= +github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= +github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= +github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -106,11 +158,17 @@ github.com/onsi/ginkgo/v2 v2.27.4 h1:fcEcQW/A++6aZAZQNUmNjvA9PSOzefMJBerHJ4t8v8Y github.com/onsi/ginkgo/v2 v2.27.4/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= github.com/onsi/gomega v1.39.0/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= @@ -119,6 +177,10 @@ github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -127,10 +189,20 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Q github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI= diff --git a/HadesScheduler/Readme.md b/HadesScheduler/Readme.md index d09e5499..0dea63bf 100644 --- a/HadesScheduler/Readme.md +++ b/HadesScheduler/Readme.md @@ -10,6 +10,12 @@ The scheduler subscribes to the priority-bucketed job subjects (`hades.jobs.{hig NATS (hades.jobs.*) ──► HadesScheduler ──► executor ──► containers (one per step) ``` +### Job leases and redelivery + +A pulled job stays leased until it is acknowledged. Because the Docker executor blocks for the whole job, the worker signals `InProgress` to JetStream every few seconds while the job runs, which keeps resetting the `NATS_ACK_WAIT` timer. A job is therefore only redelivered when the worker itself stops responding (crash, OOM kill, pod eviction, network partition) - never because it runs for a long time, including a job running all the way to its `timeout_seconds`. + +`NATS_MAX_DELIVER` (default `3`) bounds how often a job that keeps taking down its worker is retried. The last delivery is not executed: it publishes a terminal `Failed` status (with a reason explaining the redeliveries) and drops the job, so a poisonous job neither loops forever nor disappears without a status. + ## Executors ### Docker (`HADES_EXECUTOR=docker`) - local development @@ -22,7 +28,7 @@ The scheduler creates a `BuildJob` custom resource; the [HadesOperator](HadesOpe ## Configuration -Common variables: `HADES_EXECUTOR` (default `docker`), `CONCURRENCY` (default `1`), `NATS_URL`, and the executor-specific `DOCKER_*` or `K8S_*` variables. See [docs/configuration.md](../docs/configuration.md) for the complete list. +Common variables: `HADES_EXECUTOR` (default `docker`), `CONCURRENCY` (default `1`), `NATS_URL`, `NATS_ACK_WAIT` (default `1m`), `NATS_MAX_DELIVER` (default `3`), and the executor-specific `DOCKER_*` or `K8S_*` variables. See [docs/configuration.md](../docs/configuration.md) for the complete list. ## Run locally diff --git a/HadesScheduler/go.sum b/HadesScheduler/go.sum index f2658f1a..e450b96f 100644 --- a/HadesScheduler/go.sum +++ b/HadesScheduler/go.sum @@ -1,3 +1,5 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= @@ -6,6 +8,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -14,6 +18,12 @@ github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= +github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -26,6 +36,8 @@ github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUE github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= @@ -37,6 +49,8 @@ github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= @@ -94,12 +108,26 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= +github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -123,6 +151,8 @@ github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgr github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= @@ -133,6 +163,10 @@ github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+ github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -141,8 +175,16 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Q github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= diff --git a/HadesScheduler/main.go b/HadesScheduler/main.go index 08ce962e..d0b8b503 100644 --- a/HadesScheduler/main.go +++ b/HadesScheduler/main.go @@ -24,9 +24,13 @@ import ( // HadesSchedulerConfig holds the scheduler's runtime configuration. The // executor is selected separately via utils.ExecutorConfig (HADES_EXECUTOR). type HadesSchedulerConfig struct { - Concurrency uint `env:"CONCURRENCY" envDefault:"1"` - MetricsPort uint `env:"METRICS_PORT,notEmpty" envDefault:"8082"` - NatsConfig hadesnats.ConnectionConfig + // Concurrency moved into ConsumerConfig alongside AckWait and MaxDeliver: + // the three are one contract (how many workers, how long a job may hold a + // message, how many deliveries it gets) and splitting them across two + // structs made it possible to set one without the others. + ConsumerConfig hadesnats.ConsumerConfig + MetricsPort uint `env:"METRICS_PORT,notEmpty" envDefault:"8082"` + NatsConfig hadesnats.ConnectionConfig } func main() { @@ -46,10 +50,12 @@ func main() { slog.Info("HadesScheduler configuration", "executor", executorCfg.Executor, - "concurrency", cfg.Concurrency, + "concurrency", cfg.ConsumerConfig.Concurrency, "metrics_port", cfg.MetricsPort, "nats_url", cfg.NatsConfig.URL, "nats_tls", cfg.NatsConfig.TLS, + "nats_ack_wait", cfg.ConsumerConfig.AckWait, + "nats_max_deliver", cfg.ConsumerConfig.MaxDeliver, ) natsConn, err := hadesnats.SetupDefaultNatsConnection(cfg.NatsConfig) @@ -59,7 +65,7 @@ func main() { } defer natsConn.Close() - consumer, err := hadesnats.NewHadesConsumer(natsConn, cfg.Concurrency) + consumer, err := hadesnats.NewHadesConsumer(natsConn, cfg.ConsumerConfig) if err != nil { slog.Error("Failed to create Hades consumer", "error", err) os.Exit(1) diff --git a/HadesScheduler/main_test.go b/HadesScheduler/main_test.go new file mode 100644 index 00000000..271a241e --- /dev/null +++ b/HadesScheduler/main_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "os" + "testing" + + hadesnats "github.com/hades-scheduler/hades/shared/nats" + "github.com/hades-scheduler/hades/shared/utils" +) + +// TestConsumerConfigDefaultsAreLoaded pins that the envDefault tags on the +// nested ConsumerConfig actually apply when the environment sets nothing. +// +// This matters because Concurrency lives in a nested struct rather than on +// HadesSchedulerConfig directly. If nested traversal ever stopped working - +// for instance by making the field a pointer, or by switching config loader - +// the fields would silently stay at their zero values. NewHadesConsumer's +// withDefaults() would still run the consumer correctly, so nothing would +// break at runtime; the damage would be confined to the startup log reporting +// 0 / 0s / 0 while the consumer actually used 1 / 1m / 3. A configuration log +// that disagrees with the effective configuration is worse than no log. +func TestConsumerConfigDefaultsAreLoaded(t *testing.T) { + // Clear rather than set: t.Setenv with an empty string is still a set + // variable, and an explicit empty value is not the same as an absent one. + // Restored by t.Cleanup so the test does not leak into its neighbours. + for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { + if old, ok := os.LookupEnv(key); ok { + t.Cleanup(func() { + if err := os.Setenv(key, old); err != nil { + t.Errorf("restoring %s: %v", key, err) + } + }) + } + if err := os.Unsetenv(key); err != nil { + t.Fatalf("unsetting %s: %v", key, err) + } + } + + var cfg HadesSchedulerConfig + if err := utils.LoadConfig(&cfg); err != nil { + t.Fatalf("LoadConfig: %v", err) + } + + if got := cfg.ConsumerConfig.Concurrency; got != hadesnats.DefaultConcurrency { + t.Errorf("Concurrency = %d, want %d", got, hadesnats.DefaultConcurrency) + } + if got := cfg.ConsumerConfig.AckWait; got != hadesnats.DefaultAckWait { + t.Errorf("AckWait = %v, want %v", got, hadesnats.DefaultAckWait) + } + if got := cfg.ConsumerConfig.MaxDeliver; got != hadesnats.DefaultMaxDeliver { + t.Errorf("MaxDeliver = %d, want %d", got, hadesnats.DefaultMaxDeliver) + } +} diff --git a/docs/configuration.md b/docs/configuration.md index d0e032c4..5586d4c0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -78,7 +78,7 @@ The bundled Jaeger UI Service is cluster-internal (ClusterIP) by default, so you Plus the [NATS](#nats-connection-all-components) and [global](#global-all-components) variables. -> **Reserved (not yet implemented):** `PROMETHEUS_ADDRESS`, `RETENTION_IN_MIN`, `MAX_RETRIES`, and `TIMEOUT_IN_MIN` appear in `.env.example` and some compose files but are **not read by any component today**. They are placeholders for planned features and currently have no effect. (Note: a per-job timeout *is* supported, but it is set on the job payload as `timeout_seconds`, not via this env var - see [API: `Step`/`QueuePayload`](./api.md#queuepayload).) +> **Reserved (not yet implemented):** `PROMETHEUS_ADDRESS`, `RETENTION_IN_MIN`, `MAX_RETRIES`, and `TIMEOUT_IN_MIN` appear in `.env.example` and some compose files but are **not read by any component today**. They are placeholders for planned features and currently have no effect. (Note: a per-job timeout *is* supported, but it is set on the job payload as `timeout_seconds`, not via this env var - see [API: `Step`/`QueuePayload`](./api.md#queuepayload). How often a job is retried after its worker died is bounded by the scheduler's `NATS_MAX_DELIVER`, not by `MAX_RETRIES`.) > > **Per-job/per-step resource controls** are set on the job payload, not via environment variables: `timeout_seconds` (job), and per-step `cpu_limit`, `memory_limit`, `network`, `memory_swap`, `pids_limit`. Timeout, CPU, memory and environment variables are enforced on both executors; `network`, `memory_swap` and `pids_limit` are Docker-executor only (Kubernetes has no per-container swap/PID field, and a pod's containers share one network namespace). See [api.md](./api.md#step). @@ -86,7 +86,9 @@ Plus the [NATS](#nats-connection-all-components) and [global](#global-all-compon | Variable | Default | Description | Source | | -------- | ------- | ----------- | ------ | -| `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `HadesScheduler/main.go` (`HadesSchedulerConfig`) | +| `CONCURRENCY` | `1` | Number of jobs processed concurrently. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. This is a liveness backstop, **not** a job-duration budget: a worker signals progress every few seconds while a job runs, so jobs of any length (including ones running to their `timeout_seconds`) are never redelivered while the worker is alive. Lower it for faster recovery after a scheduler crash, raise it if the network is flaky. Minimum `300ms`: the heartbeat targets `AckWait/3` so three ticks fall inside each ack window, but it is clamped to a `100ms` floor. Below `300ms` that clamp leaves fewer than three ticks per window and erodes the margin that absorbs a delayed or dropped heartbeat; below `100ms` the first heartbeat arrives after `AckWait` has elapsed and a running job is redelivered. | `shared/nats/consumer.go` (`ConsumerConfig`) | +| `NATS_MAX_DELIVER` | `3` | Maximum number of times a single job is delivered. The last delivery is not executed: it is used to publish a terminal `Failed` status and drop the job, so the default allows two execution attempts before Hades gives up on a job that keeps crashing or stalling its worker. Must be at least `2`; the scheduler refuses to start otherwise, because `1` would spend the only delivery on the failure report and never execute a job. | `shared/nats/consumer.go` (`ConsumerConfig`) | | `METRICS_PORT` | `8082` | Port the Prometheus `/metrics` endpoint listens on (see [Metrics](#metrics-all-components)). | `HadesScheduler/main.go` (`HadesSchedulerConfig`) | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. | `shared/utils/config.go` (`ExecutorConfig`) | diff --git a/shared/go.mod b/shared/go.mod index 9719c5c8..a38d8f24 100644 --- a/shared/go.mod +++ b/shared/go.mod @@ -9,6 +9,7 @@ require ( github.com/nats-io/nats.go v1.52.0 github.com/prometheus/client_golang v1.24.1 github.com/stretchr/testify v1.11.1 + github.com/testcontainers/testcontainers-go v0.44.0 go.opentelemetry.io/otel v1.44.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 go.opentelemetry.io/otel/sdk v1.44.0 @@ -16,22 +17,57 @@ require ( ) require ( + dario.cat/mergo v1.0.2 // indirect + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + github.com/Microsoft/go-winio v0.6.2 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/containerd/errdefs v1.0.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/containerd/log v0.1.0 // indirect + github.com/containerd/platforms v0.2.1 // indirect + github.com/cpuguy83/dockercfg v0.3.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/go-connections v0.8.1 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/ebitengine/purego v0.10.1 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect github.com/klauspost/compress v1.19.1 // indirect + github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect + github.com/magiconair/properties v1.8.10 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect + github.com/moby/go-archive v0.2.0 // indirect + github.com/moby/moby/api v1.55.0 // indirect + github.com/moby/moby/client v0.5.1 // indirect + github.com/moby/patternmatcher v0.6.1 // indirect + github.com/moby/sys/sequential v0.7.0 // indirect + github.com/moby/sys/user v0.4.0 // indirect + github.com/moby/sys/userns v0.1.0 // indirect + github.com/moby/term v0.5.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/procfs v0.21.1 // indirect + github.com/shirou/gopsutil/v4 v4.26.6 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect go.opentelemetry.io/otel/metric v1.44.0 // indirect go.opentelemetry.io/proto/otlp v1.10.0 // indirect diff --git a/shared/go.sum b/shared/go.sum index d949e87b..657c853a 100644 --- a/shared/go.sum +++ b/shared/go.sum @@ -1,18 +1,53 @@ +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= +github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA= +github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-connections v0.8.1 h1:JibmG5hULs5qXSr/cp/w3Pw5fZuStt4MOHMUExb29/M= +github.com/docker/go-connections v0.8.1/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= +github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -31,6 +66,28 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= +github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= +github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8= +github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU= +github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= +github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= +github.com/moby/moby/client v0.5.1 h1:tYNaJno4c0HXz12y5BiqEDy0rVTYkWzI26lGvnTMiJw= +github.com/moby/moby/client v0.5.1/go.mod h1:odLstlZ6uSnfvAgVxMpvgmb8SUdd+siH2T0GBuxVAlM= +github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= +github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8= +github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o= +github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= +github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc= @@ -39,8 +96,14 @@ github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= @@ -51,10 +114,26 @@ github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+ github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs= +github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI= +github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI= @@ -79,8 +158,14 @@ golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= @@ -98,3 +183,7 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= +pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= +pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/shared/nats/ackprogress_test.go b/shared/nats/ackprogress_test.go new file mode 100644 index 00000000..9f82252d --- /dev/null +++ b/shared/nats/ackprogress_test.go @@ -0,0 +1,139 @@ +package nats + +import ( + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAckProgressInterval(t *testing.T) { + tests := []struct { + name string + ackWait time.Duration + want time.Duration + }{ + {"default ack wait is capped", DefaultAckWait, maxAckProgressInterval}, + {"long ack wait is capped", 1 * time.Hour, maxAckProgressInterval}, + {"short ack wait scales down", 3 * time.Second, 1 * time.Second}, + {"tiny ack wait hits the floor", 10 * time.Millisecond, minAckProgressInterval}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, ackProgressInterval(tt.ackWait)) + // The heartbeat must always be well below AckWait, otherwise it + // cannot reset the ack timer in time. + if tt.ackWait > minAckProgressInterval { + assert.Less(t, ackProgressInterval(tt.ackWait), tt.ackWait) + } + }) + } +} + +func TestConsumerConfigWithDefaults(t *testing.T) { + cfg := ConsumerConfig{}.withDefaults() + assert.Equal(t, uint(1), cfg.Concurrency) + assert.Equal(t, DefaultAckWait, cfg.AckWait) + assert.Equal(t, DefaultMaxDeliver, cfg.MaxDeliver) + + // MaxDeliver must never end up unlimited (0), which is the JetStream default. + assert.Positive(t, ConsumerConfig{MaxDeliver: -1}.withDefaults().MaxDeliver) + + // Explicit values are kept. + custom := ConsumerConfig{Concurrency: 4, AckWait: 5 * time.Second, MaxDeliver: 2}.withDefaults() + assert.Equal(t, ConsumerConfig{Concurrency: 4, AckWait: 5 * time.Second, MaxDeliver: 2}, custom) +} + +// TestConsumerConfigValidate pins the MaxDeliver lower bound: because the last +// allowed delivery reports the terminal failure instead of running the job, +// MaxDeliver = 1 would silently stop the scheduler from ever executing a job. +// That must fail loudly at startup instead. +func TestConsumerConfigValidate(t *testing.T) { + err := ConsumerConfig{MaxDeliver: 1}.withDefaults().validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "NATS_MAX_DELIVER") + + // Unset (zero/negative) means "use the default", not "one delivery". + assert.NoError(t, ConsumerConfig{}.withDefaults().validate()) + assert.NoError(t, ConsumerConfig{MaxDeliver: -1}.withDefaults().validate()) + + // The smallest usable value still allows one execution attempt. + assert.NoError(t, ConsumerConfig{MaxDeliver: minMaxDeliver}.withDefaults().validate()) +} + +// TestConsumerConfigValidateAckWait pins the AckWait lower bound. The heartbeat +// targets AckWait/3, giving three ticks per ack window so a delayed or dropped +// one is harmless. Below 3*minAckProgressInterval the clamp wins and that +// margin collapses towards a single tick; under minAckProgressInterval it is +// gone altogether and the first heartbeat lands after AckWait has elapsed, +// redelivering a job that is still running. +func TestConsumerConfigValidateAckWait(t *testing.T) { + err := ConsumerConfig{AckWait: 10 * time.Millisecond}.withDefaults().validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "NATS_ACK_WAIT") + + // Unset (zero/negative) means "use the default", not "expire immediately". + assert.NoError(t, ConsumerConfig{}.withDefaults().validate()) + assert.NoError(t, ConsumerConfig{AckWait: -1}.withDefaults().validate()) + + // At the bound the heartbeat is exactly minAckProgressInterval, which still + // leaves two further heartbeats before AckWait elapses. + assert.NoError(t, ConsumerConfig{AckWait: minAckWait}.withDefaults().validate()) + assert.Equal(t, minAckProgressInterval, ackProgressInterval(minAckWait)) + + // Just below it, the clamp holds the interval above AckWait/3 and the + // three-ticks-per-window margin starts to erode. + assert.Error(t, ConsumerConfig{AckWait: minAckWait - time.Millisecond}.withDefaults().validate()) +} + +func TestStartAckProgressSignalsRepeatedly(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return nil + }, 10*time.Millisecond, "job-1") + + assert.Eventually(t, func() bool { return calls.Load() >= 3 }, 2*time.Second, 5*time.Millisecond, + "expected repeated in-progress signals while the job is running") + + stop() +} + +// TestStartAckProgressStopIsFinalAndIdempotent guards the two failure modes of +// the heartbeat goroutine: leaking past the job, and signalling in-progress on a +// message that has already been ACKed or NAKed. +func TestStartAckProgressStopIsFinalAndIdempotent(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return nil + }, time.Millisecond, "job-1") + + assert.Eventually(t, func() bool { return calls.Load() > 0 }, 2*time.Second, time.Millisecond) + + stop() + after := calls.Load() + + // Calling stop twice (defer plus explicit call in processJob) must not panic + // on a closed channel or block. + require.NotPanics(t, stop) + + time.Sleep(50 * time.Millisecond) + assert.Equal(t, after, calls.Load(), "in-progress must not be signalled after stop returns") +} + +func TestStartAckProgressSurvivesSignalErrors(t *testing.T) { + var calls atomic.Int64 + stop := startAckProgress(func() error { + calls.Add(1) + return errors.New("connection closed") + }, time.Millisecond, "job-1") + defer stop() + + // A failed heartbeat is logged, not fatal: the next tick tries again. + assert.Eventually(t, func() bool { return calls.Load() >= 3 }, 2*time.Second, time.Millisecond) +} diff --git a/shared/nats/consumer.go b/shared/nats/consumer.go index 7e5863fd..9697a0b4 100644 --- a/shared/nats/consumer.go +++ b/shared/nats/consumer.go @@ -12,6 +12,7 @@ import ( "github.com/google/uuid" hades "github.com/hades-scheduler/hades/shared" + "github.com/hades-scheduler/hades/shared/buildstatus" "github.com/hades-scheduler/hades/shared/payload" "github.com/nats-io/nats.go" "github.com/nats-io/nats.go/jetstream" @@ -19,17 +20,147 @@ import ( var _ hades.JobConsumer = (*HadesNATSConsumer)(nil) +const ( + // DefaultAckWait is how long JetStream waits for an ack (or an in-progress + // signal) before it redelivers a job to another worker. It is deliberately + // unrelated to how long a job runs: while a job is being processed the + // worker resets this timer every ackProgressInterval (see startAckProgress), + // so AckWait only bounds how long an *unresponsive* worker keeps a job + // hostage. One minute means a crashed or partitioned scheduler releases its + // in-flight jobs quickly, while still tolerating six consecutive lost + // heartbeats before a healthy worker's job is handed to someone else. + DefaultAckWait = 1 * time.Minute + + // DefaultMaxDeliver bounds how often a single job may be delivered. Without + // it JetStream retries forever, so a job that reliably kills its worker + // loops for the stream's whole 24h retention. The last delivery is not + // executed: it is used to report the terminal failure and terminate the + // message (see processJob), so the default allows two execution attempts. + DefaultMaxDeliver = 3 + + // DefaultConcurrency is how many jobs one scheduler instance processes at + // once. Named rather than inlined so the envDefault tag below, withDefaults + // and the documentation all point at one value. + DefaultConcurrency = 1 + + // maxAckProgressInterval caps the in-progress heartbeat so a long AckWait + // does not lead to a needlessly coarse heartbeat. + maxAckProgressInterval = 10 * time.Second + + // minAckProgressInterval keeps the heartbeat from becoming a busy loop when + // a very small AckWait is configured (mainly in tests). + minAckProgressInterval = 100 * time.Millisecond +) + +// ConsumerConfig holds the tunables of the JetStream job consumer. +// Zero values fall back to the defaults above. +// +// The envDefault tags matter beyond convenience. withDefaults() below is +// applied inside NewHadesConsumer, so the consumer always RUNS with the right +// values - but without these tags a config parsed from an environment that sets +// none of them stays at zero, and anything inspecting it (notably the +// scheduler's startup log) reports 0/0s/0 while the consumer actually uses +// 1/1m/3. A configuration log that disagrees with the effective configuration +// is worse than no log, so the defaults are declared here as well. +// +// The tag literals must stay in step with the constants above; the values are +// duplicated because struct tags cannot reference Go constants. +// TestConsumerConfigEnvDefaultsMatchConstants pins them together. +type ConsumerConfig struct { + // Concurrency is the maximum number of jobs processed simultaneously by a + // single scheduler instance. + Concurrency uint `env:"CONCURRENCY" envDefault:"1"` + // AckWait is the JetStream ack timeout for an in-flight job. See + // DefaultAckWait: it is a liveness backstop, not a job-duration budget. + AckWait time.Duration `env:"NATS_ACK_WAIT" envDefault:"1m"` + // MaxDeliver is the maximum number of times a single job is delivered. See + // DefaultMaxDeliver. + MaxDeliver int `env:"NATS_MAX_DELIVER" envDefault:"3"` +} + +// withDefaults returns the config with non-positive values replaced by the +// package defaults. Still required despite the envDefault tags above: a +// ConsumerConfig built programmatically (tests, direct struct literals) never +// goes through env.Parse and would otherwise reach JetStream as zeros. +func (c ConsumerConfig) withDefaults() ConsumerConfig { + if c.Concurrency == 0 { + c.Concurrency = DefaultConcurrency + } + if c.AckWait <= 0 { + c.AckWait = DefaultAckWait + } + if c.MaxDeliver <= 0 { + c.MaxDeliver = DefaultMaxDeliver + } + return c +} + +// minMaxDeliver is the smallest MaxDeliver that still lets a job run. The last +// allowed delivery is spent reporting the terminal failure instead of executing +// the job (see processJob), so MaxDeliver = 1 would mean the very first delivery +// is already the last one and no job would ever be executed. +const minMaxDeliver = 2 + +// minAckWait is the smallest AckWait that preserves the heartbeat's safety +// margin. ackProgressInterval targets AckWait/3 so at least three heartbeats +// fall inside every ack window and a couple of delayed or lost ticks still +// cannot trigger a redelivery. Below this bound the minAckProgressInterval +// clamp wins, that margin shrinks towards a single tick, and under 100ms it +// disappears entirely: the first InProgress call would land after AckWait had +// already elapsed and JetStream would redeliver a job that is still running. +const minAckWait = 3 * minAckProgressInterval + +// validate rejects a configuration that would silently break job execution. +// It runs after withDefaults, so a zero or negative value has already been +// replaced by its default and only an explicit, unusable one is left. +func (c ConsumerConfig) validate() error { + if c.AckWait < minAckWait { + return fmt.Errorf( + "NATS_ACK_WAIT must be at least %s, got %s: the in-progress heartbeat is clamped to a %s floor, so a shorter AckWait leaves fewer than three heartbeats per ack window and loses the margin that keeps a delayed or dropped tick from redelivering a job that is still running", + minAckWait, c.AckWait, minAckProgressInterval) + } + if c.MaxDeliver < minMaxDeliver { + return fmt.Errorf( + "NATS_MAX_DELIVER must be at least %d, got %d: the last allowed delivery reports the terminal failure instead of running the job, so a lower value would never execute any job", + minMaxDeliver, c.MaxDeliver) + } + return nil +} + +// ackProgressInterval returns how often an in-flight job signals progress for +// the given AckWait. It stays well below AckWait so several lost heartbeats do +// not trigger a redelivery. +func ackProgressInterval(ackWait time.Duration) time.Duration { + interval := ackWait / 3 + if interval > maxAckProgressInterval { + interval = maxAckProgressInterval + } + if interval < minAckProgressInterval { + interval = minAckProgressInterval + } + return interval +} + // HadesNATSConsumer manages job consumption from the NATS queue system with priority handling. type HadesNATSConsumer struct { natsConnection *nats.Conn concurrency uint + ackWait time.Duration + maxDeliver int consumers map[hades.Priority]jetstream.Consumer kv jetstream.KeyValue } // NewHadesConsumer creates a new job consumer with priority queue support. -// The concurrency parameter controls the maximum number of jobs processed simultaneously. -func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, error) { +// The config controls how many jobs are processed simultaneously and how +// JetStream redelivers jobs whose worker stops responding. +func NewHadesConsumer(nc *nats.Conn, cfg ConsumerConfig) (*HadesNATSConsumer, error) { + cfg = cfg.withDefaults() + if err := cfg.validate(); err != nil { + slog.Error("Invalid consumer configuration", "error", err) + return nil, err + } + ctx := context.Background() js, err := jetstream.New(nc) if err != nil { @@ -46,17 +177,23 @@ func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, erro Durable: consumerName, AckPolicy: jetstream.AckExplicitPolicy, FilterSubject: prioritySubject(priority), + // Set both explicitly instead of inheriting the client defaults + // (AckWait 30s, MaxDeliver unlimited): a 30s ack timeout redelivered + // every job that ran longer than half a minute, and an unlimited + // MaxDeliver turned any job that kills its worker into an endless + // loop. + AckWait: cfg.AckWait, + MaxDeliver: cfg.MaxDeliver, }) if err != nil { slog.Error("Failed to create JetStream consumer", "error", err, "priority", priority) return nil, err } consumers[priority] = cons - slog.Info("Created JetStream consumer", "consumer", consumerName, "priority", prioritySubject(priority)) + slog.Info("Created JetStream consumer", "consumer", consumerName, "priority", prioritySubject(priority), + "ack_wait", cfg.AckWait, "max_deliver", cfg.MaxDeliver) } - slog.Info("Created JetStream consumer", "consumers", consumers) - kv, err := js.CreateOrUpdateKeyValue(ctx, jetstream.KeyValueConfig{ Bucket: "HADES_JOBS", }) @@ -67,7 +204,9 @@ func NewHadesConsumer(nc *nats.Conn, concurrency uint) (*HadesNATSConsumer, erro return &HadesNATSConsumer{ natsConnection: nc, consumers: consumers, - concurrency: concurrency, + concurrency: cfg.Concurrency, + ackWait: cfg.AckWait, + maxDeliver: cfg.MaxDeliver, kv: kv, }, nil } @@ -160,6 +299,27 @@ func (hc *HadesNATSConsumer) processJob( priority hades.Priority, processing hades.PayloadHandler, ) { + // A job that reaches its last allowed delivery has already stalled or + // crashed a worker on every previous attempt. Running it once more would + // only burn another AckWait and then be dropped silently by JetStream, so + // the final delivery is spent reporting the terminal failure instead - the + // same Failed status the executors publish for any other job failure. + if numDelivered := deliveryCount(msg, job.ID.String()); numDelivered >= uint64(hc.maxDeliver) { + reason := fmt.Sprintf("job was delivered %d times without completing (max_deliver=%d); giving up", numDelivered, hc.maxDeliver) + slog.Error("Giving up on job after repeated redeliveries", + "workerID", workerID, + "jobID", job.ID.String(), + "priority", priority, + "numDelivered", numDelivered) + if err := publishJobStatus(hc.natsConnection, buildstatus.StatusFailed, job.ID.String(), reason); err != nil { + slog.Error("Failed to publish terminal failure status", "error", err, "jobID", job.ID.String()) + } + if err := msg.Term(); err != nil { + slog.Error("Failed to terminate exhausted message", "error", err, "jobID", job.ID.String()) + } + return + } + defer func() { if r := recover(); r != nil { slog.Error("Job processing panic", @@ -179,8 +339,24 @@ func (hc *HadesNATSConsumer) processJob( "jobID", job.ID.String(), "priority", priority) + // processing(job) blocks for the whole job on the Docker executor (it waits + // on every step's container). Without a heartbeat, any job longer than + // AckWait is redelivered and executed a second time while the first copy is + // still running - both copies then share the same shared- volume. + // Signalling in-progress resets the ack timer for as long as the job runs, + // however long that legitimately is. + // + // The stop function is registered as a defer so a panic in processing also + // stops it; it runs before the recover defer above (defers are LIFO) and so + // before the NAK. It is also called explicitly below so no heartbeat can + // race with the Ack. + stopAckProgress := startAckProgress(msg.InProgress, ackProgressInterval(hc.ackWait), job.ID.String()) + defer stopAckProgress() + processing(job) + stopAckProgress() + slog.Info("Worker finished job", "workerID", workerID, "jobID", job.ID.String(), @@ -194,6 +370,52 @@ func (hc *HadesNATSConsumer) processJob( } } +// deliveryCount reports how many times msg has been delivered, starting at 1 +// for the first delivery. It returns 0 if the metadata is unreadable, which +// keeps an unexpected message shape from being terminated as poisonous. +func deliveryCount(msg jetstream.Msg, jobID string) uint64 { + meta, err := msg.Metadata() + if err != nil { + slog.Warn("Failed to read message metadata", "error", err, "jobID", jobID) + return 0 + } + return meta.NumDelivered +} + +// startAckProgress repeatedly calls inProgress (jetstream.Msg.InProgress) every +// interval until the returned stop function is called, resetting the message's +// AckWait timer while the job runs. +// +// The returned stop function is idempotent and waits for the goroutine to exit, +// so once it returns, inProgress is guaranteed not to be called again - an +// in-progress signal sent after Ack/Nak would be an error on a terminated +// message. +func startAckProgress(inProgress func() error, interval time.Duration, jobID string) func() { + done := make(chan struct{}) + stopped := make(chan struct{}) + + go func() { + defer close(stopped) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-done: + return + case <-ticker.C: + if err := inProgress(); err != nil { + slog.Warn("Failed to signal job progress to JetStream", "error", err, "jobID", jobID) + } + } + } + }() + + return sync.OnceFunc(func() { + close(done) + <-stopped + }) +} + // parseMessage handles message parsing and validation func (hc *HadesNATSConsumer) parseMessage(ctx context.Context, msg jetstream.Msg) (payload.QueuePayload, error) { var job payload.QueuePayload diff --git a/shared/nats/consumer_redelivery_test.go b/shared/nats/consumer_redelivery_test.go new file mode 100644 index 00000000..e72e1d30 --- /dev/null +++ b/shared/nats/consumer_redelivery_test.go @@ -0,0 +1,192 @@ +package nats + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + hades "github.com/hades-scheduler/hades/shared" + "github.com/hades-scheduler/hades/shared/buildstatus" + "github.com/hades-scheduler/hades/shared/payload" + "github.com/nats-io/nats.go" + "github.com/nats-io/nats.go/jetstream" + "github.com/stretchr/testify/suite" + "github.com/testcontainers/testcontainers-go" + "github.com/testcontainers/testcontainers-go/wait" +) + +const natsImage = "nats:2.11.4" + +// testAckWait is deliberately tiny so a "long-running" job in these tests only +// has to outlive a couple of seconds instead of the production AckWait. +const testAckWait = 2 * time.Second + +// ConsumerRedeliverySuite exercises the JetStream redelivery behaviour of +// HadesNATSConsumer against a real NATS server. +type ConsumerRedeliverySuite struct { + suite.Suite + natsC testcontainers.Container + conn *nats.Conn + publisher *HadesNATSPublisher +} + +func TestConsumerRedeliverySuite(t *testing.T) { + suite.Run(t, new(ConsumerRedeliverySuite)) +} + +func (s *ConsumerRedeliverySuite) SetupSuite() { + ctx := context.Background() + container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: natsImage, + ExposedPorts: []string{"4222/tcp", "8222/tcp"}, + Cmd: []string{"-js", "-m", "8222"}, + WaitingFor: wait.ForHTTP("/healthz").WithPort("8222/tcp"), + }, + Started: true, + }) + s.Require().NoError(err) + s.natsC = container + + endpoint, err := container.Endpoint(ctx, "") + s.Require().NoError(err) + + s.conn, err = SetupDefaultNatsConnection(ConnectionConfig{URL: "nats://" + endpoint}) + s.Require().NoError(err) + + s.publisher, err = NewHadesPublisher(s.conn) + s.Require().NoError(err) +} + +func (s *ConsumerRedeliverySuite) TearDownSuite() { + if s.conn != nil { + s.conn.Close() + } + if s.natsC != nil { + s.Require().NoError(testcontainers.TerminateContainer(s.natsC)) + } +} + +// runConsumer starts the consumer's dequeue loop in the background and returns a +// function that stops it and waits for the workers to exit. +func (s *ConsumerRedeliverySuite) runConsumer(cfg ConsumerConfig, handler hades.PayloadHandler) func() { + consumer, err := NewHadesConsumer(s.conn, cfg) + s.Require().NoError(err) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + consumer.DequeueJob(ctx, handler) + }() + + return func() { + cancel() + <-done + } +} + +func newTestJob(name string) payload.QueuePayload { + return payload.QueuePayload{ + ID: uuid.New(), + Name: name, + Timestamp: time.Now(), + Steps: []payload.Step{{ID: 1, Name: "step", Image: "alpine:latest"}}, + } +} + +// TestLongRunningJobIsExecutedExactlyOnce is the regression test for the +// redelivery bug: the consumer used to ack only after the handler returned, so +// with the library's 30s AckWait every Docker-mode job longer than half a minute +// was redelivered and executed a second time while the first copy was still +// running - both copies sharing the same shared- volume. +// +// The handler here blocks for several multiples of AckWait. With the in-progress +// heartbeat the job stays leased for as long as it runs, so it must be handed to +// a handler exactly once. +func (s *ConsumerRedeliverySuite) TestLongRunningJobIsExecutedExactlyOnce() { + var started atomic.Int64 + finished := make(chan struct{}) + + // Runs for 3x AckWait: without a heartbeat JetStream would have redelivered + // the job twice by the time the handler returns. + jobDuration := 3 * testAckWait + + stop := s.runConsumer(ConsumerConfig{Concurrency: 2, AckWait: testAckWait, MaxDeliver: DefaultMaxDeliver}, + func(job payload.QueuePayload) { + if started.Add(1) == 1 { + time.Sleep(jobDuration) + close(finished) + } + }) + defer stop() + + job := newTestJob("long-running-job") + s.Require().NoError(s.publisher.EnqueueHighJob(context.Background(), job)) + + select { + case <-finished: + case <-time.After(jobDuration + 15*time.Second): + s.FailNow("job handler never finished") + } + + // Give JetStream more than a full AckWait to redeliver if the ack timer was + // not being reset, plus time for a redelivered copy to reach the handler. + time.Sleep(2 * testAckWait) + + s.Equal(int64(1), started.Load(), "a job running longer than AckWait must be executed exactly once") +} + +// TestPoisonJobIsTerminatedAndReportedFailed covers the MaxDeliver backstop: a +// job that keeps killing its worker must stop being redelivered and must surface +// as Failed rather than disappearing silently. +func (s *ConsumerRedeliverySuite) TestPoisonJobIsTerminatedAndReportedFailed() { + const maxDeliver = 2 + + failures := make(chan *nats.Msg, 4) + sub, err := s.conn.ChanSubscribe(buildstatus.StatusSubject(buildstatus.StatusFailed), failures) + s.Require().NoError(err) + defer func() { _ = sub.Unsubscribe() }() + + var attempts atomic.Int64 + stop := s.runConsumer(ConsumerConfig{Concurrency: 1, AckWait: testAckWait, MaxDeliver: maxDeliver}, + func(job payload.QueuePayload) { + attempts.Add(1) + panic("executor exploded") + }) + defer stop() + + job := newTestJob("poison-job") + s.Require().NoError(s.publisher.EnqueueHighJob(context.Background(), job)) + + // Delivery 1 panics and is NAKed with a 5s delay; delivery 2 is the last + // allowed one and is spent reporting the failure instead of running again. + var failure *nats.Msg + select { + case failure = <-failures: + case <-time.After(30 * time.Second): + s.FailNow("no terminal Failed status was published for the poison job") + } + + s.Equal(job.ID.String(), string(failure.Data)) + s.NotEmpty(failure.Header.Get(buildstatus.ReasonHeader), "the terminal failure must explain itself") + s.Equal(int64(maxDeliver-1), attempts.Load(), "the final delivery must not execute the job again") + + // The message is terminated, so it must not come back. + time.Sleep(3 * testAckWait) + s.Equal(int64(maxDeliver-1), attempts.Load(), "a terminated job must not be redelivered") + s.Empty(failures, "the terminal failure must be reported once") +} + +// TearDownTest drops any job left over from a failed test so the next one starts +// from an empty work queue. +func (s *ConsumerRedeliverySuite) TearDownTest() { + ctx := context.Background() + js, err := jetstream.New(s.conn) + s.Require().NoError(err) + stream, err := js.Stream(ctx, "HADES_JOBS") + s.Require().NoError(err) + s.Require().NoError(stream.Purge(ctx)) +} diff --git a/shared/nats/consumerconfig_test.go b/shared/nats/consumerconfig_test.go new file mode 100644 index 00000000..301c418b --- /dev/null +++ b/shared/nats/consumerconfig_test.go @@ -0,0 +1,84 @@ +package nats + +import ( + "os" + "reflect" + "testing" + "time" + + "github.com/caarlos0/env/v11" +) + +// TestConsumerConfigEnvDefaultsMatchConstants pins the envDefault tag literals +// to the exported constants they mirror. +// +// Struct tags cannot reference Go constants, so the default values exist twice: +// once as DefaultConcurrency/DefaultAckWait/DefaultMaxDeliver and once as tag +// literals. Nothing but this test stops the two from drifting, and drift would +// be quiet - withDefaults() would keep the consumer running correctly while the +// parsed config, and therefore the scheduler's startup log, reported something +// else. +func TestConsumerConfigEnvDefaultsMatchConstants(t *testing.T) { + ty := reflect.TypeOf(ConsumerConfig{}) + for _, tc := range []struct { + field string + want string + }{ + {"Concurrency", "1"}, + {"AckWait", "1m"}, + {"MaxDeliver", "3"}, + } { + f, ok := ty.FieldByName(tc.field) + if !ok { + t.Fatalf("ConsumerConfig has no field %s", tc.field) + } + if got := f.Tag.Get("envDefault"); got != tc.want { + t.Errorf("%s envDefault = %q, want %q", tc.field, got, tc.want) + } + } + + // The literals above are only meaningful if they parse to the constants. + if d, err := time.ParseDuration("1m"); err != nil || d != DefaultAckWait { + t.Errorf("AckWait tag %q does not equal DefaultAckWait (%v)", "1m", DefaultAckWait) + } + if DefaultMaxDeliver != 3 { + t.Errorf("DefaultMaxDeliver = %d, but the envDefault tag says 3", DefaultMaxDeliver) + } + if DefaultConcurrency != 1 { + t.Errorf("DefaultConcurrency = %d, but the envDefault tag says 1", DefaultConcurrency) + } +} + +// TestConsumerConfigParsesDefaultsFromEmptyEnv is the behavioural half: with none +// of the variables set, a parsed config must already carry the documented +// defaults rather than zeros. +func TestConsumerConfigParsesDefaultsFromEmptyEnv(t *testing.T) { + // Clear rather than set: t.Setenv with an empty string still leaves the + // variable defined, and an explicit empty value is not an absent one. + for _, key := range []string{"CONCURRENCY", "NATS_ACK_WAIT", "NATS_MAX_DELIVER"} { + if old, ok := os.LookupEnv(key); ok { + t.Cleanup(func() { + if err := os.Setenv(key, old); err != nil { + t.Errorf("restoring %s: %v", key, err) + } + }) + } + if err := os.Unsetenv(key); err != nil { + t.Fatalf("unsetting %s: %v", key, err) + } + } + + var cfg ConsumerConfig + if err := env.Parse(&cfg); err != nil { + t.Fatalf("env.Parse: %v", err) + } + if cfg.Concurrency != DefaultConcurrency { + t.Errorf("Concurrency = %d, want %d", cfg.Concurrency, DefaultConcurrency) + } + if cfg.AckWait != DefaultAckWait { + t.Errorf("AckWait = %v, want %v", cfg.AckWait, DefaultAckWait) + } + if cfg.MaxDeliver != DefaultMaxDeliver { + t.Errorf("MaxDeliver = %d, want %d", cfg.MaxDeliver, DefaultMaxDeliver) + } +} diff --git a/shared/nats/publisher.go b/shared/nats/publisher.go index 0bfe8b16..03cd1e28 100644 --- a/shared/nats/publisher.go +++ b/shared/nats/publisher.go @@ -106,7 +106,15 @@ func (hp *HadesNATSPublisher) EnqueueJobWithPriority(ctx context.Context, queueP // subject "hades.jobstatus.{status}". Subscribers such as HadesLogManager use // these events to track a job's lifecycle. Nothing publishes the Queued status // today except the API on enqueue, so this completes the lifecycle feed. -func (hp *HadesNATSPublisher) PublishJobStatus(ctx context.Context, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { +func (hp *HadesNATSPublisher) PublishJobStatus(_ context.Context, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { + return publishJobStatus(hp.natsConnection, jobStatus, jobID, reason...) +} + +// publishJobStatus publishes a status transition on the core-NATS status +// subject "hades.jobstatus.{status}". It backs HadesNATSPublisher's +// StatusPublisher implementation and is also used by the consumer to report a +// job it gives up on, so both report failures the same way. +func publishJobStatus(nc *nats.Conn, jobStatus buildstatus.JobStatus, jobID string, reason ...string) error { if jobID == "" { return fmt.Errorf("empty job ID") } @@ -120,7 +128,7 @@ func (hp *HadesNATSPublisher) PublishJobStatus(ctx context.Context, jobStatus bu if r := buildstatus.FirstReason(reason...); r != "" { msg.Header = nats.Header{buildstatus.ReasonHeader: []string{r}} } - if err := hp.natsConnection.PublishMsg(msg); err != nil { + if err := nc.PublishMsg(msg); err != nil { return fmt.Errorf("publishing job status %s for job %s: %w", jobStatus, jobID, err) } slog.Debug("Published job status", "job_id", jobID, "status", jobStatus, "subject", subject) diff --git a/website/docs/reference/configuration.md b/website/docs/reference/configuration.md index e43e7b76..6d4b6aff 100644 --- a/website/docs/reference/configuration.md +++ b/website/docs/reference/configuration.md @@ -62,6 +62,8 @@ Hades measures how much overhead it adds around a job, per step and per phase, c | Variable | Default | Description | | -------- | ------- | ----------- | | `CONCURRENCY` | `1` | Number of jobs processed concurrently. | +| `NATS_ACK_WAIT` | `1m` | How long JetStream waits for an ack before redelivering a job to another worker. A liveness backstop, not a job-duration budget: a worker signals progress while a job runs, so long jobs are never redelivered while the worker is alive. Minimum `300ms`: the heartbeat targets `AckWait/3` but is clamped to a `100ms` floor, so shorter values leave fewer than three ticks per ack window and lose the margin that absorbs a delayed or dropped heartbeat. | +| `NATS_MAX_DELIVER` | `3` | Maximum number of deliveries per job. The last delivery is spent publishing a terminal `Failed` status and dropping the job, so the default allows two execution attempts. Must be at least `2` - the scheduler refuses to start otherwise. | | `METRICS_PORT` | `8082` | Port the Prometheus `/metrics` endpoint listens on. | | `HADES_EXECUTOR` | `docker` | Execution platform: `docker` or `k8s`. |