BlueGit

timfa bluegit

Files

bluegit / internal / server / pipeline_page.go

pipeline_page.go

pipeline_page.go 20.9 KiB Download Raw
1package server
2
3import (
4 "bytes"
5 "encoding/json"
6 "net/http"
7 "net/url"
8 "strconv"
9 "strings"
10 "time"
11
12 "gitlab.com/Timfa/bluegit/internal/access"
13 "gitlab.com/Timfa/bluegit/internal/ci"
14 "gitlab.com/Timfa/bluegit/internal/i18n"
15 "gitlab.com/Timfa/bluegit/internal/store"
16)
17
18// PipeRow is één rij in het pipeline-overzicht.
19type PipeRow struct {
20 ID int64
21 Status string
22 Label string
23 Duration string
24 When string
25 Title string
26 SHA string
27 Short string
28 Ref string
29 RefKind string
30 Source string
31 SourceLabel string
32 MRNumber int64
33 Actor string
34 ActorURL string
35 Avatar string
36 Initial string
37 Stages []StageView
38 Failed bool
39 Live bool
40}
41
42// StageView is één bolletje in de stages-kolom.
43type StageView struct {
44 Name string
45 Status string
46 Label string
47 Tip string
48 Jobs []JobLink
49}
50
51// JobLink is een job in een stage-popover of in de zijbalk.
52type JobLink struct {
53 ID int64
54 Name string
55 Status string
56 Label string
57 Queue string
58 Current bool
59 Stage string
60}
61
62// JobPage is de console van één job.
63type JobPage struct {
64 Job store.Job
65 Runner string
66 Pipe store.Pipeline
67 Name string
68 Status string
69 Label string
70 Actor string
71 ActorURL string
72 Avatar string
73 Initial string
74 When string
75 Duration string
76 Finished string
77 Queued string
78 Timeout string
79 Source string
80 Ref string
81 RefKind string
82 Short string
83 Title string
84 Stage string
85 PipeStatus string
86 PipeLabel string
87 Stages []string
88 Related []JobLink
89 Blocks []LogBlock
90 Running bool
91 LogBytes int
92 CanPlay bool
93 Environment string
94 EnvironmentURL string
95 EnvironmentLink string
96 Queue string
97}
98
99// LogBlock is een losse regel of een inklapbare sectie.
100type LogBlock struct {
101 Section bool
102 Title string
103 Duration string
104 Open bool
105 Lines []LogLine
106}
107
108// LogLine is één regel in de console.
109type LogLine struct {
110 N int
111 Time string
112 Text string
113 Spans []LogSpan
114}
115
116func (s *Server) fillPipelines(r *http.Request, v *View, repo store.Repo) {
117 lang := s.langOf(r)
118 list, _ := s.Store.ListPipelines(r.Context(), repo.ID)
119 q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
120 v.Query = r.URL.Query().Get("q")
121 ranks := s.queueRanks(r.Context())
122 users := map[string]store.User{}
123 for _, p := range list {
124 row := s.pipeRow(r, lang, repo, p, users, ranks)
125 if q != "" && !pipeMatches(row, q) {
126 continue
127 }
128 if rowLive(row) {
129 v.Live = true
130 }
131 v.PipeRows = append(v.PipeRows, row)
132 }
133 v.LiveURL = repoURL(repo) + "/-/pipelines"
134 if raw := strings.TrimSpace(r.URL.Query().Get("q")); raw != "" {
135 v.LiveURL += "?q=" + url.QueryEscape(raw)
136 }
137}
138
139func rowLive(row PipeRow) bool {
140 if row.Status == "pending" || row.Status == "running" {
141 return true
142 }
143 for _, st := range row.Stages {
144 if st.Status == "pending" || st.Status == "running" {
145 return true
146 }
147 for _, j := range st.Jobs {
148 if j.Status == "pending" || j.Status == "running" {
149 return true
150 }
151 }
152 }
153 return false
154}
155
156func (s *Server) pipeRow(r *http.Request, lang i18n.Lang, repo store.Repo, p store.Pipeline, users map[string]store.User, ranks map[int64]int) PipeRow {
157 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
158 name, kind := ci.SplitRef(p.Ref)
159 status := displayStatus(s.pipeStatusFor(p), jobs)
160 actor, avatar, actorURL := s.actorOf(r, p.Actor, users)
161 initial := ""
162 if actor != "" {
163 initial = strings.ToUpper(actor[:1])
164 }
165 sourceLabel, mrNumber := s.pipelineSourceLabel(r, repo, p)
166 row := PipeRow{
167 ID: p.ID, Status: status, Label: s.tr(r, "pipe."+status),
168 Duration: pipelineClock(p), When: i18n.Ago(lang, p.CreatedAt.Unix()),
169 Title: p.CommitTitle, SHA: p.CommitSHA, Short: shortSHA(p.CommitSHA),
170 Ref: name, RefKind: kind, Source: p.Source, SourceLabel: sourceLabel, MRNumber: mrNumber,
171 Actor: actor, ActorURL: actorURL, Avatar: avatar, Initial: initial,
172 Stages: stageViews(jobs, ranks, func(key string, args ...any) string { return s.tr(r, key, args...) }),
173 Failed: jobsFailed(jobs),
174 }
175 row.Live = rowLive(row)
176 return row
177}
178
179func jobsFailed(jobs []store.Job) bool {
180 for _, j := range jobs {
181 if j.Status == "failed" {
182 return true
183 }
184 }
185 return false
186}
187
188// pipelineSourceLabel benoemt een pipeline die bij een merge request hoort,
189// ook wanneer de rij als push is gestart en daarna gekoppeld is.
190// Een gewone push zonder merge request krijgt geen extra label.
191func (s *Server) pipelineSourceLabel(r *http.Request, repo store.Repo, p store.Pipeline) (string, int64) {
192 if p.MRID != 0 {
193 var number int64
194 if mr, err := s.Store.MergeRequest(r.Context(), repo.ID, p.MRID); err == nil {
195 number = mr.Number
196 }
197 return s.tr(r, "pipe.src.merge_request_event"), number
198 }
199 if p.Source == "" || p.Source == "push" {
200 return "", 0
201 }
202 key := "pipe.src." + p.Source
203 label := s.tr(r, key)
204 if label == key {
205 label = p.Source
206 }
207 return label, 0
208}
209
210func (s *Server) pipelineSourceText(r *http.Request, repo store.Repo, p store.Pipeline) string {
211 label, number := s.pipelineSourceLabel(r, repo, p)
212 if label == "" {
213 return ""
214 }
215 if number == 0 {
216 return label
217 }
218 return label + " !" + strconv.FormatInt(number, 10)
219}
220
221func (s *Server) actorOf(r *http.Request, name string, cache map[string]store.User) (string, string, string) {
222 name = strings.TrimSpace(name)
223 if name == "" {
224 return "", "", ""
225 }
226 u, ok := cache[name]
227 if !ok {
228 found, err := s.Store.UserByUsername(r.Context(), name)
229 if err == nil {
230 u = found
231 }
232 cache[name] = u
233 }
234 if u.ID == 0 {
235 return name, "", ""
236 }
237 return u.Username, u.AvatarURL, "/users/" + u.Username
238}
239
240func pipeMatches(row PipeRow, q string) bool {
241 bits := []string{row.Label, row.Title, row.SHA, row.Short, row.Ref, row.Actor, row.SourceLabel, strconv.FormatInt(row.ID, 10), row.Status}
242 for _, st := range row.Stages {
243 bits = append(bits, st.Name)
244 for _, j := range st.Jobs {
245 bits = append(bits, j.Name)
246 }
247 }
248 for _, b := range bits {
249 if strings.Contains(strings.ToLower(b), q) {
250 return true
251 }
252 }
253 return false
254}
255
256func displayStatus(pipe string, jobs []store.Job) string {
257 switch pipe {
258 case "failed":
259 return "failed"
260 case "running":
261 return "running"
262 case "manual":
263 return "manual"
264 case "queued":
265 return "pending"
266 case "canceled":
267 return "canceled"
268 case "waiting_for_update":
269 return "waiting_for_update"
270 }
271 warn := false
272 for _, j := range jobs {
273 if j.Status == "failed" && j.AllowFailure {
274 warn = true
275 }
276 }
277 if warn {
278 return "warning"
279 }
280 if pipe == "success" {
281 return "passed"
282 }
283 if pipe == "" {
284 return "pending"
285 }
286 return pipe
287}
288
289func stageViews(jobs []store.Job, ranks map[int64]int, tr func(string, ...any) string) []StageView {
290 var order []string
291 by := map[string][]store.Job{}
292 for _, j := range jobs {
293 if _, ok := by[j.Stage]; !ok {
294 order = append(order, j.Stage)
295 }
296 by[j.Stage] = append(by[j.Stage], j)
297 }
298 var out []StageView
299 for _, name := range order {
300 group := by[name]
301 status := stageStatus(group)
302 label := tr("pipe." + status)
303 var links []JobLink
304 for _, j := range group {
305 st := jobDisplay(j)
306 links = append(links, JobLink{
307 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Stage: j.Stage,
308 Queue: queueText(tr, ranks, j.ID),
309 })
310 }
311 out = append(out, StageView{Name: name, Status: status, Label: label, Tip: name + ": " + strings.ToLower(label), Jobs: links})
312 }
313 return out
314}
315
316func stageStatus(jobs []store.Job) string {
317 pending, failed, warning, running, canceled := false, false, false, false, false
318 seen := false
319 for _, j := range jobs {
320 seen = true
321 switch {
322 case j.Status == "running":
323 running = true
324 case j.Status == "failed" && !j.AllowFailure:
325 failed = true
326 case j.Status == "canceled" && !j.AllowFailure:
327 canceled = true
328 case j.Status == "failed" && j.AllowFailure:
329 warning = true
330 case j.Status == "queued" || j.Status == "manual":
331 pending = true
332 }
333 }
334 if !seen {
335 return "skipped"
336 }
337 if running {
338 return "running"
339 }
340 if failed {
341 return "failed"
342 }
343 if canceled {
344 return "canceled"
345 }
346 if warning {
347 return "warning"
348 }
349 if pending {
350 return "pending"
351 }
352 allSkip := true
353 for _, j := range jobs {
354 if j.Status != "skipped" {
355 allSkip = false
356 }
357 }
358 if allSkip {
359 return "skipped"
360 }
361 return "passed"
362}
363
364func jobDisplay(j store.Job) string {
365 if j.Status == "failed" && j.AllowFailure {
366 return "warning"
367 }
368 switch j.Status {
369 case "success":
370 return "passed"
371 case "queued":
372 return "pending"
373 case "":
374 return "pending"
375 default:
376 return j.Status
377 }
378}
379
380func pipelineClock(p store.Pipeline) string {
381 end := p.FinishedAt
382 if end.IsZero() {
383 end = time.Now()
384 }
385 start := p.StartedAt
386 if start.IsZero() {
387 start = p.CreatedAt
388 }
389 if start.IsZero() {
390 return ""
391 }
392 return formatClock(end.Sub(start))
393}
394
395func formatClock(d time.Duration) string {
396 if d < 0 {
397 d = 0
398 }
399 s := int(d.Seconds())
400 return pad2(s/3600) + ":" + pad2((s%3600)/60) + ":" + pad2(s%60)
401}
402
403func pad2(n int) string {
404 if n < 10 {
405 return "0" + strconv.Itoa(n)
406 }
407 return strconv.Itoa(n)
408}
409
410func shortSHA(sha string) string {
411 if len(sha) > 8 {
412 return sha[:8]
413 }
414 return sha
415}
416
417func (s *Server) showJob(w http.ResponseWriter, r *http.Request) {
418 _, repo, role, ok := s.guard(w, r, access.RoleReadonly)
419 if !ok {
420 return
421 }
422 p, job, ok := s.jobFromRequest(w, r, repo)
423 if !ok {
424 return
425 }
426 v := s.repoView(w, r, repo, role, job.Name)
427 v.Wide = true
428 v.Page = "pipelines"
429 v.Pipe = &p
430 v.JobPage = s.jobPage(r, repo, p, job, role)
431 s.render(w, "job", v)
432}
433
434func (s *Server) jobLog(w http.ResponseWriter, r *http.Request) {
435 _, repo, _, ok := s.guard(w, r, access.RoleReadonly)
436 if !ok {
437 return
438 }
439 _, job, ok := s.jobFromRequest(w, r, repo)
440 if !ok {
441 return
442 }
443 if r.URL.Query().Get("raw") == "1" {
444 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
445 _, _ = w.Write([]byte(job.Log))
446 return
447 }
448 offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
449 if offset < 0 || offset > len(job.Log) {
450 offset = 0
451 }
452 queue := ""
453 if job.Status == "queued" {
454 tr := func(key string, args ...any) string { return s.tr(r, key, args...) }
455 queue = queueText(tr, s.queueRanks(r.Context()), job.ID)
456 }
457 w.Header().Set("Content-Type", "application/json")
458 w.Header().Set("Cache-Control", "no-store")
459 _ = json.NewEncoder(w).Encode(map[string]any{
460 "offset": len(job.Log),
461 "status": job.Status,
462 "text": job.Log[offset:],
463 "queue": queue,
464 })
465}
466
467func (s *Server) retryPipeline(w http.ResponseWriter, r *http.Request) {
468 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
469 if !ok || !s.csrfOK(w, r) {
470 return
471 }
472 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
473 if err != nil {
474 http.NotFound(w, r)
475 return
476 }
477 back := safeRepoBack(repo, r.FormValue("back"))
478 if back == "" {
479 back = repoURL(repo) + "/-/pipelines/" + strconv.FormatInt(id, 10)
480 }
481 newID, err := s.opRetryPipeline(r.Context(), u, repo, id, r.FormValue("mode"))
482 if !s.uiOK(w, r, back, err) {
483 return
484 }
485 dest := back
486 if r.FormValue("mode") == "all" {
487 dest = repoURL(repo) + "/-/pipelines/" + strconv.FormatInt(newID, 10)
488 }
489 s.redirect(w, r, dest, s.tr(r, "flash.pipeRetry"), "")
490}
491
492func safeRepoBack(repo store.Repo, back string) string {
493 back = strings.TrimSpace(back)
494 prefix := "/" + repo.FullPath()
495 if back != prefix && !strings.HasPrefix(back, prefix+"/") {
496 return ""
497 }
498 if strings.Contains(back, "..") || strings.Contains(back, "\\") || strings.Contains(back, "\n") || strings.Contains(back, "?") {
499 return ""
500 }
501 return back
502}
503
504func (s *Server) playJob(w http.ResponseWriter, r *http.Request) {
505 u, repo, _, ok := s.guard(w, r, access.RoleDeveloper)
506 if !ok || !s.csrfOK(w, r) {
507 return
508 }
509 p, job, ok := s.jobFromRequest(w, r, repo)
510 if !ok {
511 return
512 }
513 _, _ = s.opJobAction(r.Context(), u, repo, p.ID, job.ID, "play")
514 s.redirect(w, r, repoURL(repo)+"/-/pipelines/"+strconv.FormatInt(p.ID, 10)+"/jobs/"+strconv.FormatInt(job.ID, 10), s.tr(r, "flash.pipeline"), "")
515}
516
517func (s *Server) jobFromRequest(w http.ResponseWriter, r *http.Request, repo store.Repo) (store.Pipeline, store.Job, bool) {
518 pid, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
519 if err != nil {
520 http.NotFound(w, r)
521 return store.Pipeline{}, store.Job{}, false
522 }
523 jid, err := strconv.ParseInt(r.PathValue("job"), 10, 64)
524 if err != nil {
525 http.NotFound(w, r)
526 return store.Pipeline{}, store.Job{}, false
527 }
528 p, err := s.Store.PipelineByID(r.Context(), repo.ID, pid)
529 if err != nil {
530 http.NotFound(w, r)
531 return store.Pipeline{}, store.Job{}, false
532 }
533 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
534 for _, j := range jobs {
535 if j.ID == jid {
536 return p, j, true
537 }
538 }
539 http.NotFound(w, r)
540 return store.Pipeline{}, store.Job{}, false
541}
542
543func (s *Server) jobPage(r *http.Request, repo store.Repo, p store.Pipeline, job store.Job, role access.Role) *JobPage {
544 lang := s.langOf(r)
545 jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
546 users := map[string]store.User{}
547 actor, avatar, actorURL := s.actorOf(r, p.Actor, users)
548 initial := ""
549 if actor != "" {
550 initial = strings.ToUpper(actor[:1])
551 }
552 name, kind := ci.SplitRef(p.Ref)
553 status := jobDisplay(job)
554 pipeStatus := displayStatus(s.pipeStatusFor(p), jobs)
555 end := job.FinishedAt
556 if end.IsZero() && (job.Status == "success" || job.Status == "failed" || job.Status == "skipped") {
557 end = p.FinishedAt
558 }
559 start := job.StartedAt
560 dur := ""
561 if !start.IsZero() {
562 until := end
563 if until.IsZero() {
564 until = time.Now()
565 }
566 dur = formatClock(until.Sub(start))
567 }
568 queued := ""
569 if !start.IsZero() && !p.CreatedAt.IsZero() {
570 queued = formatClock(start.Sub(p.CreatedAt))
571 }
572 timeout := formatClock(job.Timeout)
573 if job.Timeout == 0 && s.Cfg.CI.TimeoutSec > 0 {
574 timeout = formatClock(time.Duration(s.Cfg.CI.TimeoutSec) * time.Second)
575 }
576 finished := ""
577 if !end.IsZero() {
578 finished = i18n.Ago(lang, end.Unix())
579 }
580 ranks := s.queueRanks(r.Context())
581 tr := func(key string, args ...any) string { return s.tr(r, key, args...) }
582 var stages []string
583 seen := map[string]bool{}
584 var related []JobLink
585 for _, j := range jobs {
586 if !seen[j.Stage] {
587 seen[j.Stage] = true
588 stages = append(stages, j.Stage)
589 }
590 st := jobDisplay(j)
591 related = append(related, JobLink{
592 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Current: j.ID == job.ID, Stage: j.Stage,
593 Queue: queueText(tr, ranks, j.ID),
594 })
595 }
596 sourceKey := "pipe.src." + p.Source
597 source := s.tr(r, sourceKey)
598 if source == sourceKey {
599 source = p.Source
600 }
601 return &JobPage{
602 Runner: s.Store.JobRun(r.Context(), job.ID).RunnerName,
603 Job: job, Pipe: p, Name: job.Name, Status: status, Label: s.tr(r, "pipe."+status),
604 Actor: actor, ActorURL: actorURL, Avatar: avatar, Initial: initial, When: i18n.Ago(lang, p.CreatedAt.Unix()),
605 Duration: dur, Finished: finished, Queued: queued, Timeout: timeout, Source: source,
606 Ref: name, RefKind: kind, Short: shortSHA(p.CommitSHA), Title: p.CommitTitle, Stage: job.Stage,
607 PipeStatus: pipeStatus, PipeLabel: s.tr(r, "pipe."+pipeStatus),
608 Stages: stages, Related: related, Blocks: parseLog(job.Log), Running: job.Status == "running" || job.Status == "queued",
609 LogBytes: len(job.Log), CanPlay: job.Status == "manual" && role.CanWriteCode(),
610 Queue: queueText(tr, ranks, job.ID),
611 Environment: job.Environment, EnvironmentURL: job.EnvironmentURL, EnvironmentLink: safeEnvironmentURL(job.EnvironmentURL),
612 }
613}
614
615func safeEnvironmentURL(raw string) string {
616 if strings.Contains(raw, "$") {
617 return ""
618 }
619 if strings.HasPrefix(raw, "https://") || strings.HasPrefix(raw, "http://") {
620 return raw
621 }
622 return ""
623}
624
625func parseLog(raw string) []LogBlock {
626 var blocks []LogBlock
627 var cur *LogBlock
628 n := 0
629 flush := func() {
630 if cur == nil {
631 return
632 }
633 blocks = append(blocks, *cur)
634 cur = nil
635 }
636 for _, row := range strings.Split(raw, "\n") {
637 if row == "" {
638 continue
639 }
640 ts, text := row, row
641 if i := strings.IndexByte(row, '\t'); i >= 0 {
642 ts, text = row[:i], row[i+1:]
643 }
644 if strings.HasPrefix(text, "section_start:") {
645 flush()
646 body := strings.TrimPrefix(text, "section_start:")
647 title := body
648 if i := strings.IndexByte(body, ':'); i >= 0 {
649 title = body[i+1:]
650 }
651 cur = &LogBlock{Section: true, Title: title, Open: true}
652 continue
653 }
654 if strings.HasPrefix(text, "section_end:") {
655 dur := ""
656 body := strings.TrimPrefix(text, "section_end:")
657 if i := strings.IndexByte(body, '\t'); i >= 0 {
658 dur = body[i+1:]
659 }
660 if cur != nil {
661 cur.Duration = dur
662 flush()
663 }
664 continue
665 }
666 n++
667 line := LogLine{N: n, Time: clockOf(ts), Text: text, Spans: ansiSpans(text)}
668 if cur != nil {
669 cur.Lines = append(cur.Lines, line)
670 continue
671 }
672 blocks = append(blocks, LogBlock{Lines: []LogLine{line}})
673 }
674 if cur != nil {
675 flush()
676 }
677 return blocks
678}
679
680func wantsJSON(r *http.Request) bool {
681 return strings.Contains(r.Header.Get("Accept"), "application/json")
682}
683
684func jobsLive(pipe string, jobs []store.Job) bool {
685 if pipe == "queued" || pipe == "running" {
686 return true
687 }
688 for _, j := range jobs {
689 if j.Status == "queued" || j.Status == "running" {
690 return true
691 }
692 }
693 return false
694}
695
696func linksFor(jobs []store.Job, ranks map[int64]int, tr func(string, ...any) string) []JobLink {
697 out := make([]JobLink, 0, len(jobs))
698 for _, j := range jobs {
699 st := jobDisplay(j)
700 out = append(out, JobLink{
701 ID: j.ID, Name: j.Name, Status: st, Label: tr("pipe." + st), Stage: j.Stage,
702 Queue: queueText(tr, ranks, j.ID),
703 })
704 }
705 return out
706}
707
708func (s *Server) partial(name string, v View) string {
709 var buf bytes.Buffer
710 tmpl := s.byLang[v.Lang]
711 if tmpl == nil {
712 tmpl = s.tmpl
713 }
714 if tmpl == nil {
715 return ""
716 }
717 if err := tmpl.ExecuteTemplate(&buf, name, v); err != nil && s.Log != nil {
718 s.Log.Error("sjabloon", "name", name, "err", err)
719 }
720 return buf.String()
721}
722
723func (s *Server) writePipeList(w http.ResponseWriter, v View) {
724 type job struct {
725 ID int64 `json:"id"`
726 Name string `json:"name"`
727 Status string `json:"status"`
728 Label string `json:"label"`
729 Queue string `json:"queue"`
730 }
731 type stage struct {
732 Name string `json:"name"`
733 Status string `json:"status"`
734 Tip string `json:"tip"`
735 Jobs []job `json:"jobs"`
736 }
737 type row struct {
738 ID int64 `json:"id"`
739 Status string `json:"status"`
740 Label string `json:"label"`
741 Duration string `json:"duration"`
742 When string `json:"when"`
743 Stages []stage `json:"stages"`
744 HTML string `json:"html"`
745 }
746 rows := make([]row, 0, len(v.PipeRows))
747 for _, pr := range v.PipeRows {
748 one := v
749 one.PipeRows = []PipeRow{pr}
750 item := row{
751 ID: pr.ID, Status: pr.Status, Label: pr.Label, Duration: pr.Duration, When: pr.When,
752 HTML: s.partial("pipe-rows", one),
753 }
754 for _, st := range pr.Stages {
755 jobs := make([]job, 0, len(st.Jobs))
756 for _, j := range st.Jobs {
757 jobs = append(jobs, job{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Queue: j.Queue})
758 }
759 item.Stages = append(item.Stages, stage{Name: st.Name, Status: st.Status, Tip: st.Tip, Jobs: jobs})
760 }
761 rows = append(rows, item)
762 }
763 w.Header().Set("Content-Type", "application/json")
764 w.Header().Set("Cache-Control", "no-store")
765 _ = json.NewEncoder(w).Encode(map[string]any{"active": v.Live, "rows": rows})
766}
767
768func (s *Server) writePipeDetail(w http.ResponseWriter, v View) {
769 type job struct {
770 ID int64 `json:"id"`
771 Name string `json:"name"`
772 Status string `json:"status"`
773 Label string `json:"label"`
774 Stage string `json:"stage"`
775 Queue string `json:"queue"`
776 }
777 type stageJob struct {
778 ID int64 `json:"id"`
779 Name string `json:"name"`
780 Status string `json:"status"`
781 Label string `json:"label"`
782 Queue string `json:"queue"`
783 }
784 type stage struct {
785 Name string `json:"name"`
786 Status string `json:"status"`
787 Tip string `json:"tip"`
788 Jobs []stageJob `json:"jobs"`
789 }
790 jobs := make([]job, 0, len(v.PipeJobs))
791 for _, j := range v.PipeJobs {
792 jobs = append(jobs, job{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Stage: j.Stage, Queue: j.Queue})
793 }
794 stages := make([]stage, 0, len(v.PipeStages))
795 for _, st := range v.PipeStages {
796 item := stage{Name: st.Name, Status: st.Status, Tip: st.Tip, Jobs: make([]stageJob, 0, len(st.Jobs))}
797 for _, j := range st.Jobs {
798 item.Jobs = append(item.Jobs, stageJob{ID: j.ID, Name: j.Name, Status: j.Status, Label: j.Label, Queue: j.Queue})
799 }
800 stages = append(stages, item)
801 }
802 dur := ""
803 html := ""
804 if v.Pipe != nil {
805 dur = pipelineClock(*v.Pipe)
806 if v.Repo != nil {
807 head := CommitRow{PipeID: v.Pipe.ID, PipeStages: v.PipeStages}
808 html = s.partial("stage-dots", View{Lang: v.Lang, Repo: v.Repo, Head: &head})
809 }
810 }
811 w.Header().Set("Content-Type", "application/json")
812 w.Header().Set("Cache-Control", "no-store")
813 _ = json.NewEncoder(w).Encode(map[string]any{
814 "active": v.Live, "status": v.PipeStatus, "label": v.PipeLabel,
815 "duration": dur, "jobs": jobs, "stages": stages, "html": html,
816 })
817}
818
819func clockOf(ts string) string {
820 if t, err := time.Parse(time.RFC3339, ts); err == nil {
821 return t.UTC().Format("15:04:05")
822 }
823 if len(ts) >= 19 && strings.Contains(ts, "T") {
824 return ts[11:19]
825 }
826 return ""
827}