package runnerapi import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "fmt" "hash/crc32" "hash/fnv" "io" "log" "mime/multipart" "net/http" "net/url" "strconv" "strings" "sync" "time" "tangled.org/dracoblue.de/shuttle/internal/queue" ) type VerifyFunc func(*http.Request, string) (bool, error) type completedFunc func(queue.Job, string, int, string, string) type Config struct { Queue queue.Queue Verify VerifyFunc Logger *log.Logger Token func() (string, error) Completed completedFunc Started func(queue.Job, time.Time) TimeoutSeconds int GraceSeconds int ArtifactMax int64 UploadArtifact func(context.Context, queue.Job, ArtifactMeta, io.Reader) (int64, error) DownloadArtifact func(context.Context, int64, io.Writer) error // Runner looks up the tags stored for a runner token. Nil means the runner // has no tags and run_untagged is true. Tags sent by the client are ignored: // gitlab-runner's verify request carries only token and system_id. Runner func(ctx context.Context, token string) (tags []string, runUntagged bool, err error) } type ArtifactMeta struct{ Name, Type, Format, ExpireIn string } type activeJob struct { job queue.Job token string trace []byte done bool } type API struct { cfg Config mu sync.Mutex jobs map[int64]*activeJob } func New(cfg Config) *API { if cfg.Token == nil { cfg.Token = randomToken } if cfg.Logger == nil { cfg.Logger = log.Default() } if cfg.TimeoutSeconds == 0 { cfg.TimeoutSeconds = 1800 } if cfg.GraceSeconds == 0 { cfg.GraceSeconds = 60 } return &API{cfg: cfg, jobs: make(map[int64]*activeJob)} } func (a *API) Handler() http.Handler { m := http.NewServeMux() m.HandleFunc("POST /api/v4/runners/verify", a.verify) m.HandleFunc("POST /api/v4/jobs/request", a.request) m.HandleFunc("PUT /api/v4/jobs/{id}", a.update) m.HandleFunc("PATCH /api/v4/jobs/{id}/trace", a.patchTrace) m.HandleFunc("POST /api/v4/jobs/{id}/artifacts", a.uploadArtifact) m.HandleFunc("GET /api/v4/jobs/{id}/artifacts", a.downloadArtifact) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { lw := &statusWriter{ResponseWriter: w, status: 200} m.ServeHTTP(lw, r) a.cfg.Logger.Printf("runner_api method=%s path=%s status=%d", r.Method, r.URL.Path, lw.status) }) } type statusWriter struct { http.ResponseWriter status int } func (w *statusWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) } func (a *API) runnerAuthorized(r *http.Request, token string) bool { ok, err := a.cfg.Verify(r, token) return err == nil && ok } func decodeToken(r *http.Request) string { var v struct { Token string `json:"token"` } _ = json.NewDecoder(r.Body).Decode(&v) return v.Token } func (a *API) verify(w http.ResponseWriter, r *http.Request) { if !a.runnerAuthorized(r, decodeToken(r)) { http.Error(w, "forbidden", http.StatusForbidden) return } w.Header().Set("Content-Type", "application/json") io.WriteString(w, "{\"id\":1}\n") } func (a *API) request(w http.ResponseWriter, r *http.Request) { runnerToken := decodeToken(r) if !a.runnerAuthorized(r, runnerToken) { http.Error(w, "forbidden", http.StatusForbidden) return } tags, runUntagged := []string(nil), true if a.cfg.Runner != nil { var err error tags, runUntagged, err = a.cfg.Runner(r.Context(), runnerToken) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } j, err := a.cfg.Queue.ClaimMatching(r.Context(), func(job queue.Job) bool { return queue.RunnerCanRun(job.Tags, tags, runUntagged) }) if err == queue.ErrEmpty { w.WriteHeader(http.StatusNoContent) return } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } j.StartedAt = time.Now().UTC().Format(time.RFC3339Nano) token, err := a.cfg.Token() if err != nil { _ = a.cfg.Queue.Requeue(r.Context(), j.ID) http.Error(w, err.Error(), 500) return } a.mu.Lock() a.jobs[j.ID] = &activeJob{job: j, token: token} a.mu.Unlock() timeout := a.cfg.TimeoutSeconds if j.TimeoutSeconds > 0 { timeout = j.TimeoutSeconds } deadline := time.Now().Add(time.Duration(timeout+a.cfg.GraceSeconds) * time.Second) if a.cfg.Started != nil { a.cfg.Started(j, deadline) } go a.watchdog(j.ID, deadline) body := JobResponseWithTimeout(j, token, timeout) deps := make([]queue.Dependency, len(j.Dependencies)) copy(deps, j.Dependencies) for i := range deps { deps[i].Token = token } if len(deps) > 0 { body["dependencies"] = deps } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) _ = json.NewEncoder(w).Encode(body) } func (a *API) watchdog(id int64, deadline time.Time) { t := time.NewTimer(time.Until(deadline)) defer t.Stop() <-t.C a.mu.Lock() j, ok := a.jobs[id] if !ok || j.done { a.mu.Unlock() return } j.done = true trace := append([]byte(nil), j.trace...) job := j.job a.mu.Unlock() _ = a.cfg.Queue.Ack(context.Background(), id) a.cfg.Logger.Printf("job=%d state=lost trace_bytes=%d", id, len(trace)) if a.cfg.Completed != nil { a.cfg.Completed(job, "lost", -1, string(trace), "") } } func JobResponse(j queue.Job, token string) map[string]any { return JobResponseWithTimeout(j, token, 1800) } func JobResponseWithTimeout(j queue.Job, token string, timeout int) map[string]any { repoURL := j.RepoURL if u, err := url.Parse(repoURL); err == nil { u.User = nil repoURL = u.String() } refspec := "+" + j.Ref + ":refs/remotes/origin/" + strings.TrimPrefix(j.Ref, "refs/heads/") variables := j.Variables if variables == nil { variables = []queue.Variable{} } services := j.Services if services == nil { services = []queue.Image{} } steps := []any{map[string]any{"name": "script", "script": append(append([]string{}, j.BeforeScript...), j.Script...), "timeout": timeout, "when": "on_success", "allow_failure": false}} if j.AfterScript != nil { steps = append(steps, map[string]any{"name": "after_script", "script": j.AfterScript, "timeout": timeout, "when": "always", "allow_failure": true}) } body := map[string]any{ "id": j.ID, "token": token, "git_info": map[string]any{"repo_url": repoURL, "sha": j.SHA, "before_sha": fallbackSHA(j.BeforeSHA), "ref": j.Ref, "ref_type": refType(j.Ref), "refspecs": []string{refspec}, "repo_object_format": "sha1"}, "runner_info": map[string]any{"timeout": timeout}, "variables": variables, "steps": steps, "image": j.Image, "services": services, } if j.Cache != nil { body["cache"] = j.Cache } if j.Artifacts != nil { body["artifacts"] = j.Artifacts } if len(j.Hooks) > 0 { body["hooks"] = j.Hooks } if j.RepoDID != "" { // gitlab-runner keys its local cache volumes and build directories on // job_info.project_id. Without it every repository is project 0, and two // repositories with the same cache key share one cache on a runner. body["job_info"] = map[string]any{ "name": j.JobName, "stage": j.Stage, "project_id": ProjectID(j.RepoDID), "project_name": j.RepoDID, } } return body } func (a *API) uploadArtifact(w http.ResponseWriter, r *http.Request) { j, ok := a.find(r) if !ok { http.Error(w, "forbidden", http.StatusForbidden) return } if a.cfg.UploadArtifact == nil { http.Error(w, "artifact storage unavailable", http.StatusServiceUnavailable) return } max := a.cfg.ArtifactMax if max <= 0 { max = 100 * 1024 * 1024 } r.Body = http.MaxBytesReader(w, r.Body, max+1024*1024) mr, err := r.MultipartReader() if err != nil { http.Error(w, "invalid artifact multipart", http.StatusBadRequest) return } var file *multipart.Part for { p, e := mr.NextPart() if e == io.EOF { break } if e != nil { http.Error(w, e.Error(), http.StatusBadRequest) return } if p.FormName() == "file" { file = p break } p.Close() } if file == nil { http.Error(w, "missing artifact file", http.StatusBadRequest) return } defer file.Close() meta := ArtifactMeta{Name: file.FileName(), Type: r.URL.Query().Get("artifact_type"), Format: r.URL.Query().Get("artifact_format"), ExpireIn: r.URL.Query().Get("expire_in")} if meta.Type == "" { meta.Type = "archive" } if meta.Format == "" { meta.Format = "zip" } size, err := a.cfg.UploadArtifact(r.Context(), j.job, meta, io.LimitReader(file, max+1)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if size > max { http.Error(w, fmt.Sprintf("artifact exceeds SHUTTLE_ARTIFACT_MAX (%d bytes)", max), http.StatusRequestEntityTooLarge) return } w.WriteHeader(http.StatusCreated) } func (a *API) downloadArtifact(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) return } token := r.Header.Get("JOB-TOKEN") a.mu.Lock() authorized := false for _, j := range a.jobs { if !j.done && j.token == token { for _, d := range j.job.Dependencies { if d.ID == id { authorized = true break } } } } a.mu.Unlock() if !authorized { http.Error(w, "forbidden", http.StatusForbidden) return } if a.cfg.DownloadArtifact == nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "application/zip") if err := a.cfg.DownloadArtifact(r.Context(), id, w); err != nil { http.Error(w, err.Error(), http.StatusNotFound) } } // ProjectID maps a repository DID to a stable positive int64 for the runner. // Collisions between two DIDs are possible in theory (64-bit FNV-1a) and would // only make them share a cache again. func ProjectID(repoDID string) int64 { h := fnv.New64a() h.Write([]byte(repoDID)) return int64(h.Sum64()&(1<<62-1)) + 1 } func fallbackSHA(s string) string { if s == "" { return strings.Repeat("0", 40) } return s } func refType(ref string) string { if strings.HasPrefix(ref, "refs/tags/") { return "tag" } return "branch" } func (a *API) find(r *http.Request) (*activeJob, bool) { id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { return nil, false } a.mu.Lock() defer a.mu.Unlock() j, ok := a.jobs[id] if !ok || j.done || r.Header.Get("JOB-TOKEN") != j.token { return nil, false } return j, true } func (a *API) patchTrace(w http.ResponseWriter, r *http.Request) { j, ok := a.find(r) if !ok { http.Error(w, "forbidden", 403) return } var start, end int if _, err := fmt.Sscanf(r.Header.Get("Content-Range"), "%d-%d", &start, &end); err != nil || start != len(j.trace) { w.Header().Set("Range", fmt.Sprintf("0-%d", len(j.trace)-1)) w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) return } b, err := io.ReadAll(r.Body) if err != nil || end != start+len(b)-1 { w.Header().Set("Range", fmt.Sprintf("0-%d", len(j.trace)-1)) w.WriteHeader(416) return } a.mu.Lock() j.trace = append(j.trace, b...) a.mu.Unlock() w.WriteHeader(http.StatusAccepted) } func (a *API) update(w http.ResponseWriter, r *http.Request) { var req struct { State string `json:"state"` ExitCode int `json:"exit_code"` FailureReason string `json:"failure_reason"` Output struct { Checksum string `json:"checksum"` Bytesize int `json:"bytesize"` } `json:"output"` } if json.NewDecoder(r.Body).Decode(&req) != nil { http.Error(w, "bad JSON", 400) return } if req.State != "running" && req.State != "success" && req.State != "failed" && req.State != "canceled" { http.Error(w, "invalid state", http.StatusBadRequest) return } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.Error(w, "forbidden", http.StatusForbidden) return } a.mu.Lock() j, ok := a.jobs[id] if !ok || j.done || r.Header.Get("JOB-TOKEN") != j.token { a.mu.Unlock() http.Error(w, "forbidden", http.StatusForbidden) return } expected := fmt.Sprintf("crc32:%08x", crc32.ChecksumIEEE(j.trace)) if req.Output.Bytesize != len(j.trace) || req.Output.Checksum != expected { a.mu.Unlock() w.WriteHeader(http.StatusPreconditionFailed) return } if req.State == "running" { a.mu.Unlock() w.WriteHeader(http.StatusOK) return } j.done = true job := j.job trace := append([]byte(nil), j.trace...) a.mu.Unlock() _ = a.cfg.Queue.Ack(r.Context(), job.ID) a.cfg.Logger.Printf("job=%d state=%s exit_code=%d failure_reason=%s trace_bytes=%d", job.ID, req.State, req.ExitCode, req.FailureReason, len(trace)) if a.cfg.Completed != nil { a.cfg.Completed(job, req.State, req.ExitCode, string(trace), req.FailureReason) } w.WriteHeader(http.StatusOK) } func randomToken() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } return hex.EncodeToString(b), nil }