package api
import (
"context"
"fmt"
"sort"
"strings"
"time"
"craftdesign.group/quarry/internal/ci"
"craftdesign.group/quarry/internal/ops"
)
// Runner liveness and queue visibility (#507): a queued run that has no
// firstStepAt yet used to read identically whether a runner was busy on
// another job, no runner was connected, or a connected runner was idle
// and wedged. ci.runners.list exposes live runners and in-flight/queued
// runs for a repository, and queueHintFor turns that same snapshot into
// one honest sentence for ci.run.get and landing.get's waiting field.
const runnerWedgedAfter = 2 * time.Minute
type ciRunnersIn struct {
Repo string `json:"repo" validate:"required,max=64"`
}
type ciRunnerInfo struct {
WorkerID string `json:"workerId"`
Online bool `json:"online"`
LastSeen string `json:"lastSeen,omitempty"`
MaxTasks int `json:"maxTasks"`
TaskTypes []string `json:"taskTypes"`
Hostname string `json:"hostname,omitempty"`
Version string `json:"version,omitempty"`
WorkerGroups []string `json:"workerGroups,omitempty"`
}
type ciQueueRun struct {
RunID string `json:"runId"`
Checkin string `json:"checkin"`
Branch string `json:"branch,omitempty"`
Pipeline string `json:"pipeline,omitempty"`
Workflow string `json:"workflow,omitempty"`
Started string `json:"started,omitempty"`
FirstStepAt string `json:"firstStepAt,omitempty"`
RanSeconds *int64 `json:"ranSeconds,omitempty"`
QueuedSeconds *int64 `json:"queuedSeconds,omitempty"`
}
type ciRunnersOut struct {
Runners []ciRunnerInfo `json:"runners"`
OnlineRunners int `json:"onlineRunners"`
TotalSlots int `json:"totalSlots"`
UngroupedRunners int `json:"ungroupedRunners,omitempty"`
Active []ciQueueRun `json:"active"`
Queued []ciQueueRun `json:"queued"`
}
// ciQueueHint summarizes why a still-going run is executing or waiting
// in the queue. State is "running", "queued", "no_runner", or "wedged".
type ciQueueHint struct {
State string `json:"state"`
Say string `json:"say,omitempty"`
OnlineRunners int `json:"onlineRunners"`
Ahead int `json:"ahead,omitempty"`
ActiveRunID string `json:"activeRunId,omitempty"`
ActiveBranch string `json:"activeBranch,omitempty"`
ActiveSeconds *int64 `json:"activeSeconds,omitempty"`
QueuedSeconds *int64 `json:"queuedSeconds,omitempty"`
RanSeconds *int64 `json:"ranSeconds,omitempty"`
}
func groupBelongsToRepo(group, g string) bool {
if g == group {
return true
}
_, ok := ci.PoolOfGroup(group, g)
return ok
}
func taskTypeBelongsToRepo(group, taskType string) bool {
if taskType == group || strings.HasPrefix(taskType, group+".") {
return true
}
_, ok := ci.PoolOfTaskType(group, taskType)
return ok
}
func filterRepoGroups(group string, groups []string) []string {
var out []string
for _, g := range groups {
if groupBelongsToRepo(group, g) {
out = append(out, g)
}
}
return out
}
func filterRepoTaskTypes(group string, taskTypes []string) []string {
out := []string{}
for _, tt := range taskTypes {
if taskTypeBelongsToRepo(group, tt) {
out = append(out, tt)
}
}
return out
}
func (d Deps) nowTime() time.Time {
if d.Now != nil {
return d.Now()
}
return time.Now()
}
func parseRunTime(s string) (time.Time, bool) {
if s == "" {
return time.Time{}, false
}
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return t, true
}
if t, err := time.Parse("2006-01-02T15:04:05.999999999", s); err == nil {
return t.UTC(), true
}
return time.Time{}, false
}
func elapsedSeconds(since string, now time.Time) *int64 {
t, ok := parseRunTime(since)
if !ok {
return nil
}
sec := int64(now.Sub(t).Seconds())
if sec < 0 {
sec = 0
}
return &sec
}
func formatWaitDuration(sec int64) string {
if sec < 60 {
return fmt.Sprintf("%ds", sec)
}
return fmt.Sprintf("%dm", sec/60)
}
func (d Deps) repoRunnersSnapshot(ctx context.Context, repoName string, now time.Time) (out ciRunnersOut, hasWorkers bool, err error) {
out = ciRunnersOut{
Runners: []ciRunnerInfo{},
Active: []ciQueueRun{},
Queued: []ciQueueRun{},
}
if d.CIWorkers != nil {
ws, werr := d.CIWorkers()
if werr != nil {
return out, false, werr
}
hasWorkers = true
group := ci.GroupFor(repoName)
for _, w := range ws {
online := w.Alive(now)
matchedGroups := filterRepoGroups(group, w.WorkerGroups)
if len(matchedGroups) > 0 {
out.Runners = append(out.Runners, ciRunnerInfo{
WorkerID: w.WorkerID,
Online: online,
LastSeen: w.LastSeen,
MaxTasks: w.MaxTasks,
TaskTypes: filterRepoTaskTypes(group, w.TaskTypes),
Hostname: w.Hostname,
Version: w.Version,
WorkerGroups: matchedGroups,
})
if online {
out.OnlineRunners++
if w.MaxTasks > 0 {
out.TotalSlots += w.MaxTasks
} else {
out.TotalSlots++
}
}
} else if len(w.WorkerGroups) == 0 && online {
out.UngroupedRunners++
}
}
sort.Slice(out.Runners, func(i, j int) bool {
if out.Runners[i].Online != out.Runners[j].Online {
return out.Runners[i].Online
}
return out.Runners[i].WorkerID < out.Runners[j].WorkerID
})
}
if d.CI == nil {
return out, hasWorkers, nil
}
runs, rerr := d.CI.CIRunsPage(repoName, 50, 0)
if rerr != nil {
return out, hasWorkers, rerr
}
var going []CIRun
var lookupHashes []string
for _, r := range runs {
if classifyStatus(r.Status) != checkGoing || r.Status == "deferred" {
continue
}
going = append(going, r)
h := r.Checkin
if tip, _, ok := parsePair(h); ok {
h = tip
}
if h != "" {
lookupHashes = append(lookupHashes, h)
}
}
branches := map[string]string{}
if len(lookupHashes) > 0 {
if repo, rerr := d.repoFor(ctx, repoName); rerr == nil && repo.Index != nil {
if meta, merr := repo.Index.CheckinsMeta(lookupHashes); merr == nil {
for h, e := range meta {
branches[h] = e.Branch
}
}
}
}
for _, r := range going {
br := r.Branch
if br == "" {
h := r.Checkin
if tip, _, ok := parsePair(h); ok {
h = tip
}
br = branches[h]
}
qr := ciQueueRun{
RunID: r.RunID,
Checkin: r.Checkin,
Branch: br,
Pipeline: r.Pipeline,
Workflow: r.Workflow,
Started: r.Started,
FirstStepAt: r.FirstStepAt,
}
if r.FirstStepAt != "" {
if r.RanSeconds != nil {
v := *r.RanSeconds
qr.RanSeconds = &v
} else {
qr.RanSeconds = elapsedSeconds(r.FirstStepAt, now)
}
out.Active = append(out.Active, qr)
} else {
qr.QueuedSeconds = elapsedSeconds(r.Started, now)
out.Queued = append(out.Queued, qr)
}
}
// Oldest first for queue order.
sort.SliceStable(out.Queued, func(i, j int) bool {
return out.Queued[i].Started < out.Queued[j].Started
})
sort.SliceStable(out.Active, func(i, j int) bool {
return out.Active[i].FirstStepAt < out.Active[j].FirstStepAt
})
return out, hasWorkers, nil
}
func (d Deps) queueHintFor(ctx context.Context, repoName string, run CIRun) *ciQueueHint {
if classifyStatus(run.Status) != checkGoing || run.Status == "deferred" {
return nil
}
now := d.nowTime()
if run.FirstStepAt != "" {
ran := run.RanSeconds
if ran == nil {
ran = elapsedSeconds(run.FirstStepAt, now)
}
say := "is running."
if ran != nil {
say = fmt.Sprintf("is running (%s).", formatWaitDuration(*ran))
}
return &ciQueueHint{State: "running", Say: say, RanSeconds: ran}
}
snap, hasWorkers, err := d.repoRunnersSnapshot(ctx, repoName, now)
qsec := elapsedSeconds(run.Started, now)
if err != nil || !hasWorkers {
return &ciQueueHint{State: "queued", Say: "is queued.", QueuedSeconds: qsec}
}
hint := &ciQueueHint{
OnlineRunners: snap.OnlineRunners,
QueuedSeconds: qsec,
}
for _, q := range snap.Queued {
if q.RunID == run.RunID {
break
}
if run.Started == "" || q.Started <= run.Started {
hint.Ahead++
}
}
if len(snap.Active) > 0 {
a := snap.Active[0]
hint.State = "queued"
hint.ActiveRunID = a.RunID
hint.ActiveBranch = a.Branch
hint.ActiveSeconds = a.RanSeconds
shortID := a.RunID
if len(shortID) > 8 {
shortID = shortID[:8]
}
var details []string
if a.Branch != "" {
details = append(details, a.Branch)
}
if a.RanSeconds != nil {
details = append(details, "running "+formatWaitDuration(*a.RanSeconds))
}
if len(details) > 0 {
hint.Say = fmt.Sprintf("is queued behind run %s (%s).", shortID, strings.Join(details, ", "))
} else {
hint.Say = fmt.Sprintf("is queued behind run %s.", shortID)
}
return hint
}
if snap.OnlineRunners == 0 && snap.UngroupedRunners == 0 {
hint.State = "no_runner"
hint.Say = "is queued; no online runner for this repository."
return hint
}
if qsec != nil && time.Duration(*qsec)*time.Second >= runnerWedgedAfter {
hint.State = "wedged"
n := snap.OnlineRunners
if n == 0 {
n = snap.UngroupedRunners
}
word := "runner"
if n != 1 {
word = "runners"
}
hint.Say = fmt.Sprintf("has been queued for %s with %d online %s idle (runner may be wedged).", formatWaitDuration(*qsec), n, word)
return hint
}
hint.State = "queued"
hint.Say = "is queued for an online runner."
return hint
}
func registerCIRunners(r *ops.Registry, d Deps) error {
return ops.Register(r, ops.Op[ciRunnersIn, ciRunnersOut]{
Name: "ci.runners.list",
Caps: "8",
Doc: "Connected runners for a repository, with liveness, slot capacity, currently executing runs, and queued runs. " +
"Distinguishes a run waiting behind an active job from one with no online runner or an idle runner.",
Kind: ops.Query,
Auth: ops.Anonymous,
Route: "GET /api/v1/r/{repo}/ci/runners",
Run: func(ctx context.Context, in ciRunnersIn) (ciRunnersOut, error) {
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return ciRunnersOut{}, err
}
out, _, err := d.repoRunnersSnapshot(ctx, in.Repo, d.nowTime())
if err != nil {
return ciRunnersOut{}, err
}
return out, nil
},
})
}