Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ DOCKER_CPU_LIMIT=2 # Number of CPUs to limit the container to (see Docker docume
DOCKER_MEMORY_LIMIT=2g # Memory limit for the container (see Docker documentation for more info)
DOCKER_CONTAINER_AUTOREMOVE=false # Disable auto-removal to retain container logs post-execution (default: false)
DOCKER_IMAGE_PULL_POLICY=always # always | if-not-present | never. "always" contacts the registry once per step even when the image is already local, which costs ~2.2s per step for a small image and more for a large one; "if-not-present" skips that but never picks up a moved tag (default: always)
DOCKER_IMAGE_PULL_FRESHNESS=0s # under "always", skip the registry for a present image this scheduler pulled within this window, e.g. 30s (default: 0s)

### Traefik Deployment configuration ###
LETSENCRYPT_EMAIL=you@example.com
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Go workspace (`go.work`, Go 1.26) with five modules:
| `HadesScheduler/` | NATS consumer. Reads `HADES_EXECUTOR` and dispatches to either the `docker/` or `k8s/` package. |
| `HadesScheduler/docker/` | Runs each step as a Docker container; shares state between steps via a per-job named volume `shared-<uuid>`. |
| `HadesScheduler/k8s/` | Creates a `BuildJob` CR via the dynamic client for the operator to reconcile. |
| `HadesScheduler/HadesOperator/` | Standalone kubebuilder operator. Watches `BuildJob` CRs (`build.hades.tum.de/v1`) and reconciles them into `batchv1.Job`s with one initContainer per step plus a finalizer pod. |
| `HadesScheduler/HadesOperator/` | Standalone kubebuilder operator. Watches `BuildJob` CRs (`build.hades.tum.de/v1`) and reconciles them into `batchv1.Job`s with one initContainer per step plus a finalizer pod. Progress is event-driven (watches its labelled Pods, owned Jobs, and a log-stream-finished channel); `REQUEUE_DELAY` is only a safety resync, so don't reintroduce polling for latency. |
| `HadesLogManager/` | Subscribes to `hades.jobstatus.*` and `hades.logs.<jobID>` on NATS, aggregates logs in-memory (`sync.Map`), exposes `GET /jobs`, `/jobs/:id/logs`, `/jobs/:id/status` on port 8081. Also hosts the **job-status webhook** dispatcher (`status_webhook.go` + `status_dispatcher.go`), which is independent of log forwarding. |
| `shared/` | Cross-module: `payload` (DTOs), `nats` (publisher/consumer/connection), `buildlogs` (log types + `LogPublisher`/`LogAggregator` interfaces), `buildstatus` (job status enum + subjects), `redact` (metadata secret masking used by the API + dashboard), `utils` (env config loader, memory-limit parsing), `prio.go` (priority enum: high/medium/low ←→ ints). |

Expand Down
12 changes: 8 additions & 4 deletions HadesAPI/dashboard/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,14 @@ import (

hades "github.com/hades-scheduler/hades/shared"
"github.com/hades-scheduler/hades/shared/buildstatus"
hadesnats "github.com/hades-scheduler/hades/shared/nats"
"github.com/hades-scheduler/hades/shared/redact"
"github.com/hades-scheduler/hades/shared/utils"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)

const (
// jobsBucket is the JetStream KV bucket holding full job payloads.
jobsBucket = "HADES_JOBS"
// jobsStream is the JetStream stream carrying queued job references.
jobsStream = "HADES_JOBS"
// metricsBroadcastInterval is how often aggregate metrics are pushed to
Expand Down Expand Up @@ -114,9 +113,9 @@ func NewServer(ctx context.Context, cfg Config, nc *nats.Conn) (*Server, error)
if err != nil {
return nil, fmt.Errorf("creating JetStream context: %w", err)
}
kv, err = js.KeyValue(ctx, jobsBucket)
kv, err = js.KeyValue(ctx, hadesnats.JobsBucket)
if err != nil {
return nil, fmt.Errorf("opening KV bucket %q: %w", jobsBucket, err)
return nil, fmt.Errorf("opening KV bucket %q: %w", hadesnats.JobsBucket, err)
}
}

Expand Down Expand Up @@ -190,6 +189,11 @@ func (s *Server) metricsLoop(ctx context.Context) {
case <-ctx.Done():
return
case <-ticker.C:
// Metrics cost three JetStream round-trips and a tracker scan; with
// nobody watching they would be computed only to be thrown away.
if s.hub.clientCount() == 0 {
continue
}
s.hub.broadcast(event{Type: eventMetrics, Metrics: s.metrics(ctx)})
}
}
Expand Down
92 changes: 92 additions & 0 deletions HadesAPI/dashboard/dashboard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,95 @@ func TestTrackerSweep(t *testing.T) {
t.Fatal("expected finished job to be swept")
}
}

func TestTrackerIdentityIsLookedUpOnce(t *testing.T) {
tr := newTracker(time.Hour)
tr.enqueue("enqueued", "Named Job", 3, hades.HighPriority)
if tr.needsIdentity("enqueued") {
t.Fatal("a job recorded at enqueue already has its identity")
}

tr.observe("seen", buildstatus.StatusRunning, "")
if !tr.needsIdentity("seen") {
t.Fatal("a job learned from a status event needs a lookup")
}
tr.setIdentity("seen", "From KV", 2)
if tr.needsIdentity("seen") {
t.Fatal("identity must be remembered after a lookup")
}
if got, _ := tr.get("seen"); got.Name != "From KV" || got.StepCount != 2 {
t.Fatalf("identity not written back: %+v", got)
}

// A definitive miss is remembered too.
tr.observe("gone", buildstatus.StatusRunning, "")
tr.setIdentity("gone", "", 0)
if tr.needsIdentity("gone") {
t.Fatal("a missing payload must not be looked up again")
}
}

func TestTrackerStatsSinglePass(t *testing.T) {
tr := newTracker(time.Hour)
tr.observe("a", buildstatus.StatusRunning, "")
tr.observe("a", buildstatus.StatusSucceeded, "")
tr.observe("b", buildstatus.StatusQueued, "")
tr.observe("c", buildstatus.StatusFailed, "")
tr.mu.Lock()
tr.jobs["c"].finishedAt = time.Now().Add(-time.Hour)
tr.mu.Unlock()

st := tr.stats(time.Minute)
if st.counts["Succeeded"] != 1 || st.counts["Queued"] != 1 || st.counts["Failed"] != 1 {
t.Fatalf("unexpected counts: %v", st.counts)
}
if len(st.durations) != 1 {
t.Fatalf("only jobs with a start and finish have a duration, got %v", st.durations)
}
if st.finishedRecently != 1 {
t.Fatalf("finishedRecently = %d, want 1", st.finishedRecently)
}
}

func TestTrackerCapEvictsOldest(t *testing.T) {
tr := newTracker(time.Hour)
base := time.Now().Add(-time.Hour)
tr.mu.Lock()
for i := range maxTrackedJobs + 10 {
id := strconv.Itoa(i)
tr.jobs[id] = &jobRecord{id: id, updatedAt: base.Add(time.Duration(i) * time.Millisecond)}
}
tr.enforceCapLocked()
_, oldest := tr.jobs["0"]
_, newest := tr.jobs[strconv.Itoa(maxTrackedJobs+9)]
n := len(tr.jobs)
tr.mu.Unlock()
if n != maxTrackedJobs || oldest || !newest {
t.Fatalf("len=%d oldestKept=%v newestKept=%v", n, oldest, newest)
}
}

// Every client receives the same pre-encoded frame, and the raw log bytes pass
// through unchanged in the shape the SPA parses.
func TestHubBroadcastsEncodedFrame(t *testing.T) {
h := newHub()
h.broadcast(event{Type: eventJob}) // no clients: must not panic or block
a, b := h.add(), h.add()
raw := json.RawMessage(`{"job_id":"j","container_id":"c","logs":[{"timestamp":"2026-01-01T00:00:00Z","message":"hi","output_stream":"stdout"}]}`)
h.broadcast(event{Type: eventLog, Log: raw})

got := <-a
if string(got) != string(<-b) {
t.Fatal("clients received different frames")
}
var decoded struct {
Type string `json:"type"`
Log json.RawMessage `json:"log"`
}
if err := json.Unmarshal(got, &decoded); err != nil {
t.Fatalf("frame is not JSON: %v", err)
}
if decoded.Type != eventLog || string(decoded.Log) != string(raw) {
t.Fatalf("unexpected frame: %s", got)
}
}
66 changes: 50 additions & 16 deletions HadesAPI/dashboard/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,21 @@ func (s *Server) handleListJobs(c *gin.Context) {

// The tracker already carries name and step count for jobs this replica
// enqueued, so a KV read is only needed for the rare job we learned about
// purely from a status event (no name). This keeps the list from doing a
// KV round-trip per row.
// purely from a status event (no name). The result, including a definitive
// miss, is written back so each such job costs one KV read in total rather
// than one per list request.
for i := range jobs {
if jobs[i].Name != "" {
if jobs[i].Name != "" || !s.tracker.needsIdentity(jobs[i].ID) {
continue
}
if job, ok := s.fetchPayload(c.Request.Context(), jobs[i].ID); ok {
jobs[i].Name = job.Name
if jobs[i].StepCount == 0 {
jobs[i].StepCount = len(job.Steps)
}
ident, ok := s.fetchIdentity(c.Request.Context(), jobs[i].ID)
if !ok {
continue
}
s.tracker.setIdentity(jobs[i].ID, ident.Name, len(ident.Steps))
jobs[i].Name = ident.Name
if jobs[i].StepCount == 0 {
jobs[i].StepCount = len(ident.Steps)
}
}

Expand Down Expand Up @@ -206,22 +210,52 @@ func (s *Server) handleJobLogs(c *gin.Context) {

// fetchPayload reads and unmarshals a job's full payload from the KV bucket.
func (s *Server) fetchPayload(ctx context.Context, id string) (payload.QueuePayload, bool) {
if s.kv == nil {
var job payload.QueuePayload
if found, _ := s.getStoredJob(ctx, id, &job); !found {
return payload.QueuePayload{}, false
}
return job, true
}

// jobIdentity is the part of a stored payload the job list shows. Steps are
// left undecoded since only their count is needed.
type jobIdentity struct {
Name string `json:"name"`
Steps []json.RawMessage `json:"steps"`
}

// fetchIdentity reads a job's name and steps from the KV bucket. ok is false
// only for a transient failure worth retrying on a later request; a missing or
// undecodable payload is reported as ok with a zero identity so it is cached.
func (s *Server) fetchIdentity(ctx context.Context, id string) (ident jobIdentity, ok bool) {
found, transient := s.getStoredJob(ctx, id, &ident)
if !found {
return jobIdentity{}, !transient
}
return ident, true
}

// getStoredJob unmarshals the job's stored payload into out. found is false
// when there is nothing usable; transient then says whether a later read might
// succeed (KV unavailable or erroring) as opposed to a missing or undecodable
// entry. out may be partially written when found is false.
func (s *Server) getStoredJob(ctx context.Context, id string, out any) (found, transient bool) {
if s.kv == nil {
return false, true
}
entry, err := s.kv.Get(ctx, id)
if err != nil {
if !errors.Is(err, jetstream.ErrKeyNotFound) {
slog.Debug("KV get failed", "job_id", id, "error", err)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return false, false
}
return payload.QueuePayload{}, false
slog.Debug("KV get failed", "job_id", id, "error", err)
return false, true
}
var job payload.QueuePayload
if err := json.Unmarshal(entry.Value(), &job); err != nil {
if err := json.Unmarshal(entry.Value(), out); err != nil {
slog.Warn("Failed to unmarshal job payload", "job_id", id, "error", err)
return payload.QueuePayload{}, false
return false, false
}
return job, true
return true, false
}

func nonNil(m map[string]string) map[string]string {
Expand Down
20 changes: 12 additions & 8 deletions HadesAPI/dashboard/logstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ const logStreamBuffer = 64
// write deadline.
//
// All writes to the response happen in this one goroutine; the JetStream callback
// only hands parsed batches to it over a channel, so gin.ResponseWriter is never
// written concurrently. The consumer is torn down when the client disconnects.
// only hands batches to it over a channel, so gin.ResponseWriter is never written
// concurrently. The consumer is torn down when the client disconnects.
func (s *Server) handleJobLogStream(c *gin.Context) {
// Parse the id as a UUID so only a well-formed job id reaches the subject
// filter - no user-controlled data flows into NATS.
Expand Down Expand Up @@ -70,13 +70,18 @@ func (s *Server) handleJobLogStream(c *gin.Context) {
return
}

logs := make(chan buildlogs.Log, logStreamBuffer)
logs := make(chan json.RawMessage, logStreamBuffer)
consumeCtx, err := cons.Consume(func(msg jetstream.Msg) {
var l buildlogs.Log
if err := json.Unmarshal(msg.Data(), &l); err != nil {
slog.Debug("Failed to unmarshal streamed log", "job_id", parsedID, "error", err)
// The stored message is already a JSON-encoded buildlogs.Log, the exact
// shape the SPA expects, so it is forwarded without a decode/encode pass.
// Marshaling the event compacts it, so a stray newline cannot split the
// SSE frame; invalid JSON is dropped here because Marshal would reject
// the whole event.
if !json.Valid(msg.Data()) {
slog.Debug("Skipping malformed streamed log", "job_id", parsedID)
return
}
l := json.RawMessage(msg.Data())
// Block only until the client catches up or disconnects; a full buffer
// throttles the consumer rather than dropping logs.
select {
Expand Down Expand Up @@ -105,8 +110,7 @@ func (s *Server) handleJobLogStream(c *gin.Context) {
case <-ctx.Done():
return
case l := <-logs:
logCopy := l
writeEvent(w, event{Type: eventLog, Log: &logCopy})
writeEvent(w, event{Type: eventLog, Log: l})
w.Flush()
case <-heartbeat.C:
if _, err := w.WriteString(": ping\n\n"); err != nil {
Expand Down
14 changes: 8 additions & 6 deletions HadesAPI/dashboard/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ type Durations struct {

// metrics computes a fresh metrics snapshot.
func (s *Server) metrics(ctx context.Context) *Metrics {
stats := s.tracker.stats(throughputWindow)
m := &Metrics{
StatusCounts: s.tracker.counts(),
StatusCounts: stats.counts,
QueueDepth: s.queueDepth(ctx),
Durations: summarizeDurations(s.tracker.finishedDurations()),
ThroughputPerMin: s.tracker.finishedSince(throughputWindow),
Durations: summarizeDurations(stats.durations),
ThroughputPerMin: stats.finishedRecently,
StreamClients: s.hub.clientCount(),
Timestamp: time.Now().UTC(),
}
Expand All @@ -65,9 +66,10 @@ func (s *Server) queueDepth(ctx context.Context) QueueDepth {
slog.Debug("queue depth: consumer unavailable", "consumer", name, "error", err)
continue
}
info, err := cons.Info(ctx)
if err != nil {
slog.Debug("queue depth: consumer info failed", "consumer", name, "error", err)
// js.Consumer already fetched fresh info to bind the handle, so a
// second Info call would only repeat the round-trip.
info := cons.CachedInfo()
if info == nil {
continue
}
pending := int64(info.NumPending)
Expand Down
Loading
Loading