Files

92 lines
2.3 KiB
Go

package daemon
import (
"context"
"errors"
"sort"
"sync"
)
// RunningTask identifies a task the daemon is currently executing.
type RunningTask struct {
ID int64
Identity string
}
// runningTasks tracks executing tasks so they can be cancelled.
type runningTasks struct {
mu sync.Mutex
entries map[int64]*runningEntry
}
type runningEntry struct {
identity string
cancel context.CancelCauseFunc
}
// errTaskStopped is the cancellation cause when an operator stops a task.
var errTaskStopped = errors.New("task stopped")
// stoppingOnly reports whether ctx ended only because the daemon is shutting
// down. Such a task is left running: the next daemon's startup re-queues it.
func stoppingOnly(ctx context.Context) bool {
return ctx.Err() != nil && errors.Is(context.Cause(ctx), context.Canceled)
}
// begin registers a task as running and returns a context that [stop] can
// cancel, together with the function that retires it.
func (r *runningTasks) begin(ctx context.Context, id int64, identity string) (context.Context, func()) {
taskCtx, cancel := context.WithCancelCause(ctx)
r.mu.Lock()
if r.entries == nil {
r.entries = make(map[int64]*runningEntry)
}
r.entries[id] = &runningEntry{identity: identity, cancel: cancel}
r.mu.Unlock()
return taskCtx, func() {
r.mu.Lock()
delete(r.entries, id)
r.mu.Unlock()
cancel(nil)
}
}
// stop cancels one running task, reporting whether it was running.
func (r *runningTasks) stop(id int64) bool {
r.mu.Lock()
entry, ok := r.entries[id]
r.mu.Unlock()
if !ok {
return false
}
entry.cancel(errTaskStopped)
return true
}
// list returns the tasks currently running, for reporting.
func (r *runningTasks) list() []RunningTask {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]RunningTask, 0, len(r.entries))
for id, entry := range r.entries {
out = append(out, RunningTask{ID: id, Identity: entry.identity})
}
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
return out
}
// CancelTask stops a task that is currently executing, reporting whether
// it was running. A task that is not running is not an error here: the
// caller decides what a miss means.
func (d *Daemon) CancelTask(id int64) bool {
return d.running.stop(id)
}
// RunningTasks lists the tasks currently executing.
func (d *Daemon) RunningTasks() []RunningTask {
return d.running.list()
}