Skip to content
quarry Artifact [d86e3ca7ad]
Login

Artifact [d86e3ca7ad]

Artifact d86e3ca7ad76566fcace7507257620d28539719dc3d8727088a3967880053621:


// maintenance.go — one lane for routine store upkeep.
//
// Cache warms, the file-history index, line counts and the search check
// are all work nobody is waiting for. Each used to start itself — at
// boot, on a moved tip, after a round — in a goroutine of its own, so a
// restart or a busy hour put all of them next to the requests they
// exist to speed up. They now ask this scheduler, which runs one at a
// time and starts a task only when the machine can spare it.
//
// Admission is by load, not by clock: a task waits while the store
// gate is crowded, memory is short, or a deploy or backup is running,
// and says which. It checks again every poll interval.
package main

import (
	"context"
	"log"
	"sort"
	"sync"
	"time"

	"craftdesign.group/quarry/internal/obs"
	"craftdesign.group/quarry/internal/work"
	"craftdesign.group/quarry/internal/zitcli"
)

const (
	// maintPoll is how often a waiting task re-reads the load.
	maintPoll = 15 * time.Second
	// maintOverdue is how long a task may wait before the page says so.
	maintOverdue = 24 * time.Hour
	// maintQueue bounds the lane's queue. Requests coalesce per store
	// and task, so the true bound is stores times tasks; this is above it.
	maintQueue = 4096
)

type maintKey struct{ store, task string }

// maintEntry is one store's task: what is asked of it now and how it
// last ended. It stays after the run so the page can show the result.
type maintEntry struct {
	key maintKey
	// pending: requested and not yet started. A second request while
	// pending is the same work.
	pending   bool
	queuedAt  time.Time
	waitingOn []string // non-nil while admitted to the lane but held by load
	waitSince time.Time
	running   bool
	startedAt time.Time
	last      *maintDone
}

type maintDone struct {
	at       time.Time
	duration time.Duration
	err      string
}

// maintenance owns the lane. A nil *maintenance runs requests at once,
// unadmitted, which is what a registrar built without one expects.
type maintenance struct {
	ctx  context.Context
	lane *work.Lane
	// load returns what the task must wait on; empty means go.
	load func() []string
	poll time.Duration
	now  func() time.Time

	mu      sync.Mutex
	entries map[maintKey]*maintEntry
	queue   []maintJob
	stopped bool
	wake    chan struct{}
	wg      sync.WaitGroup
}

type maintJob struct {
	e   *maintEntry
	run func(context.Context) error
}

// newMaintenance builds the scheduler. ctx ends it: waiting and queued
// tasks are dropped, a running one is cancelled.
func newMaintenance(ctx context.Context, load func() []string) *maintenance {
	m := &maintenance{
		ctx: ctx, lane: work.NewLane("maintenance", 1, maintQueue), load: load,
		poll: maintPoll, now: time.Now, entries: map[maintKey]*maintEntry{},
		wake: make(chan struct{}, 1),
	}
	go m.loop()
	return m
}

// Request asks for task on store. It reports false when the same task
// is already queued for that store (the request coalesces into it) or
// the scheduler has stopped. It never blocks.
func (m *maintenance) Request(store, task string, run func(context.Context) error) bool {
	if m == nil {
		go func() { _ = run(obs.WithReason(context.Background(), obs.ReasonMaint)) }()
		return true
	}
	key := maintKey{store, task}
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.stopped {
		return false
	}
	e := m.entries[key]
	if e == nil {
		e = &maintEntry{key: key}
		m.entries[key] = e
	}
	if e.pending {
		return false
	}
	e.pending, e.queuedAt = true, m.now()
	m.queue = append(m.queue, maintJob{e, run})
	m.wg.Add(1)
	select {
	case m.wake <- struct{}{}:
	default:
	}
	return true
}

// loop is the lane's one worker: it takes requests in the order they
// came, so the lane's width is the whole of the concurrency.
func (m *maintenance) loop() {
	for {
		m.mu.Lock()
		if len(m.queue) == 0 {
			if m.ctx.Err() != nil {
				m.stopped = true
				m.mu.Unlock()
				return
			}
			m.mu.Unlock()
			select {
			case <-m.wake:
			case <-m.ctx.Done():
			}
			continue
		}
		job := m.queue[0]
		m.queue = m.queue[1:]
		m.mu.Unlock()
		err := m.lane.DoNamed(m.ctx, job.e.key.task, job.e.key.store, func() error { return m.execute(job.e, job.run) })
		if err != nil {
			// Never started: stopped, or the lane refused. Whatever was
			// pending was this request, so release it.
			if m.ctx.Err() == nil {
				log.Printf("maintenance: %s %s: %v", job.e.key.store, job.e.key.task, err)
			}
			m.mu.Lock()
			job.e.pending, job.e.waitingOn = false, nil
			m.mu.Unlock()
		}
		m.wg.Done()
	}
}

// execute holds the lane's slot: it waits for the load to clear, then
// runs the task.
func (m *maintenance) execute(e *maintEntry, run func(context.Context) error) error {
	for {
		if err := m.ctx.Err(); err != nil {
			return err
		}
		reasons := m.load()
		if len(reasons) == 0 {
			break
		}
		m.mu.Lock()
		if e.waitingOn == nil {
			e.waitSince = m.now()
		}
		e.waitingOn = reasons
		m.mu.Unlock()
		if !sleepCtx(m.ctx, m.poll) {
			return m.ctx.Err()
		}
	}
	start := m.now()
	m.mu.Lock()
	e.pending, e.waitingOn, e.running, e.startedAt = false, nil, true, start
	m.mu.Unlock()
	err := run(obs.WithReason(m.ctx, obs.ReasonMaint))
	done := &maintDone{at: m.now(), duration: m.now().Sub(start)}
	if err != nil {
		done.err = err.Error()
	}
	m.mu.Lock()
	e.running, e.last = false, done
	m.mu.Unlock()
	return nil
}

// Wait returns once every requested task has run or been dropped.
func (m *maintenance) Wait() {
	if m != nil {
		m.wg.Wait()
	}
}

// Snapshot is every task the scheduler knows, for the ops page: running
// first, then waiting, then queued, then idle ones by store.
func (m *maintenance) Snapshot() []zitcli.MaintTask {
	if m == nil {
		return nil
	}
	now := m.now()
	m.mu.Lock()
	out := make([]zitcli.MaintTask, 0, len(m.entries))
	for _, e := range m.entries {
		t := zitcli.MaintTask{Store: e.key.store, Task: e.key.task, State: "idle"}
		switch {
		case e.running:
			t.State, t.AgeMs = "running", now.Sub(e.startedAt).Milliseconds()
		case e.waitingOn != nil:
			t.State, t.WaitingOn = "waiting", append([]string(nil), e.waitingOn...)
			t.AgeMs = now.Sub(e.queuedAt).Milliseconds()
		case e.pending:
			t.State, t.AgeMs = "queued", now.Sub(e.queuedAt).Milliseconds()
		}
		if e.pending && !e.running && now.Sub(e.queuedAt) > maintOverdue {
			t.Overdue = true
		}
		if e.last != nil {
			t.Last = &zitcli.MaintLast{AgoMs: now.Sub(e.last.at).Milliseconds(),
				DurationMs: e.last.duration.Milliseconds(), Error: e.last.err}
		}
		out = append(out, t)
	}
	m.mu.Unlock()
	rank := map[string]int{"running": 0, "waiting": 1, "queued": 2, "idle": 3}
	sort.Slice(out, func(i, j int) bool {
		if rank[out[i].State] != rank[out[j].State] {
			return rank[out[i].State] < rank[out[j].State]
		}
		if out[i].Store != out[j].Store {
			return out[i].Store < out[j].Store
		}
		return out[i].Task < out[j].Task
	})
	return out
}

// Lane is the scheduler's lane, for the ops page's lane list.
func (m *maintenance) Lane() *work.Lane {
	if m == nil {
		return nil
	}
	return m.lane
}