BlueGit

timfa bluegit

Files

bluegit / internal / server / pipeline_page.go

pipeline_page.go

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