internal/control/dashboard.go
505 lines · 16801 bytes
18 symbols in this file
1package control
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "strconv"
8 "strings"
9
10 "gitbay.org/gitbay/internal/buildinfo"
11 "gitbay.org/gitbay/internal/gitutil"
12 "gitbay.org/gitbay/internal/policy"
13 "gitbay.org/gitbay/internal/protocol"
14 "gitbay.org/gitbay/internal/store"
15)
16
17func init() {
18 register(Command{Path: []string{"dashboard"},
19 Summary: "one read for the account dashboard: review queue, assigned and open work, pins, activity, builds",
20 Usage: "dashboard",
21 Examples: []string{"dashboard"},
22 ReadOnly: true, Run: runDashboard})
23 register(Command{Path: []string{"feed"},
24 Summary: "activity on repositories you can reach",
25 Usage: "feed [--limit <n>] [--cursor <c>]",
26 Flags: []Flag{
27 {"--limit", "<n>", "rows per page", ""},
28 {"--cursor", "<c>", "continue from the previous page", ""},
29 },
30 Examples: []string{"feed --limit 20"},
31 ReadOnly: true, Run: runFeed})
32}
33
34// DashboardItem is one open issue or MR row, with its repo resolved so a
35// client renders the aggregate without further reads.
36type DashboardItem struct {
37 Repo string `json:"repo"`
38 Number int64 `json:"number"`
39 Title string `json:"title"`
40 Author string `json:"author"`
41 State string `json:"state"`
42 UpdatedAt string `json:"updated_at"`
43 // Queued marks a merge request with a queued merge.
44 Queued bool `json:"queued,omitempty"`
45}
46
47// PinnedOut is one pinned repository on the dashboard.
48type PinnedOut struct {
49 Path string `json:"path"`
50 Visibility string `json:"visibility"`
51 Description string `json:"description,omitempty"`
52 Archived bool `json:"archived,omitempty"`
53}
54
55// DashboardBuild is a build with its repository resolved, which is what
56// separates it from BuildOut: the dashboard spans repositories.
57type DashboardBuild struct {
58 Repo string `json:"repo"`
59 Number int64 `json:"number"`
60 Job string `json:"job"`
61 Status string `json:"status"`
62 SHA string `json:"sha"`
63 Ref string `json:"ref"`
64 CreatedAt string `json:"created_at"`
65 FinishedAt string `json:"finished_at,omitempty"`
66}
67
68// ServerOut is admin-only. The exact build a host is running narrows down
69// which known issues apply to it, so it is not everyone's to read; the
70// person who needs it is the operator.
71type ServerOut struct {
72 Commit string `json:"commit"`
73}
74
75// DashboardOut is what dashboard emits: the whole account aggregate in
76// one read.
77type DashboardOut struct {
78 Reviews []DashboardItem `json:"review_queue"`
79 Assigned []DashboardItem `json:"assigned_issues"`
80 MRs []DashboardItem `json:"open_mrs"`
81 Issues []DashboardItem `json:"open_issues"`
82 Pinned []PinnedOut `json:"pinned"`
83 Activity []FeedOut `json:"recent_activity"`
84 Builds []DashboardBuild `json:"builds"`
85 // Queries is each pinned saved query with its first rows.
86 Queries []DashboardQuery `json:"queries"`
87 // Unread is the notification inbox badge, so a client showing one
88 // does not need a second read to fill it.
89 Unread int `json:"unread"`
90 Server *ServerOut `json:"server,omitempty"`
91 // Queues is admin-only: every background worker's backlog and
92 // failures, the operator's view of what is stuck.
93 Queues *store.Queues `json:"queues,omitempty"`
94}
95
96// dashboardActivity is how many feed lines the dashboard shows at a
97// terminal.
98const dashboardActivity = 5
99
100func runDashboard(c *Ctx, args []string) int {
101 if len(args) != 0 {
102 return c.usage()
103 }
104 d, events, err := dashboardData(c)
105 if err != nil {
106 return c.fail(protocol.ExitFailure, "%v", err)
107 }
108 lines := FeedLines(events)
109 return c.emitView(d, func(w io.Writer) { writeDashboard(c, w, d, lines) },
110 func() screen { return dashboardScreen(c, d, lines) })
111}
112
113// dashboardData is the signed-in user's dashboard, with the events its
114// activity was made from.
115func dashboardData(c *Ctx) (DashboardOut, []store.FeedEvent, error) {
116 d := DashboardOut{
117 Reviews: []DashboardItem{}, Assigned: []DashboardItem{}, MRs: []DashboardItem{},
118 Issues: []DashboardItem{}, Pinned: []PinnedOut{}, Activity: []FeedOut{}, Builds: []DashboardBuild{},
119 }
120 var err error
121 if d.Pinned, err = pinnedOutputs(c); err != nil {
122 return d, nil, err
123 }
124 lists := []struct {
125 into *[]DashboardItem
126 fetch func(int64) ([]store.DashboardItem, error)
127 }{
128 {&d.MRs, c.Store.DashboardMRs},
129 {&d.Reviews, c.Store.ReviewQueue},
130 {&d.Assigned, c.Store.AssignedIssues},
131 {&d.Issues, c.Store.DashboardIssues},
132 }
133 for _, l := range lists {
134 items, err := l.fetch(c.User.ID)
135 if err != nil {
136 return d, nil, err
137 }
138 for _, m := range items {
139 *l.into = append(*l.into, DashboardItem{m.RepoPath, m.Number, m.Title, m.Author, m.State, m.UpdatedAt, m.Queued})
140 }
141 }
142
143 events, err := c.Store.RecentEvents(c.User.ID, 20, 0)
144 if err != nil {
145 return d, nil, err
146 }
147 d.Activity = feedOutputs(events)
148
149 builds, err := c.Store.RecentBuilds(c.User.ID, 20)
150 if err != nil {
151 return d, nil, err
152 }
153 for _, b := range builds {
154 d.Builds = append(d.Builds, DashboardBuild{b.RepoPath, b.Number, b.Job, b.Status, b.SHA, b.Ref, b.CreatedAt, b.FinishedAt})
155 }
156 if d.Queries, err = PinnedQueries(c.Store, c.User); err != nil {
157 return d, nil, err
158 }
159 d.Unread = c.Store.UnreadNotices(c.User.ID)
160 if c.User.IsAdmin {
161 d.Server = &ServerOut{Commit: buildinfo.String()}
162 q, err := c.Store.QueueStatus()
163 if err != nil {
164 return d, nil, err
165 }
166 d.Queues = &q
167 }
168 return d, events, nil
169}
170
171// pinnedOutputs is the user's pinned repositories they can still read.
172func pinnedOutputs(c *Ctx) ([]PinnedOut, error) {
173 pinned, err := c.Store.PinnedRepos(c.User.ID)
174 if err != nil {
175 return nil, err
176 }
177 out := []PinnedOut{}
178 for _, r := range pinned {
179 grant, err := c.Store.AccessRole(r.ID, c.User.ID)
180 if err != nil {
181 return nil, err
182 }
183 if !policy.CanRead(c.User, r, grant) {
184 continue
185 }
186 desc := gitutil.ReadDescription(RepoDir(c.Cfg.Server.Root, r.OwnerName, r.Name))
187 out = append(out, PinnedOut{r.Path(), r.Visibility, desc, r.Settings.Archived})
188 }
189 return out, nil
190}
191
192// writeDashboard is `dashboard` as text: one section per list, then the
193// server's build and queues for an admin.
194func writeDashboard(c *Ctx, w io.Writer, d DashboardOut, lines []FeedLine) {
195 section := func(title string, rows [][]cell) { writeDashboardSection(w, title, rows) }
196 itemRows := func(items []DashboardItem, marker string) [][]cell {
197 rows := make([][]cell, len(items))
198 for i, item := range items {
199 page := "issues"
200 if marker == "!" {
201 page = "mrs"
202 }
203 ref := cLink(fmt.Sprintf("%s%s%d", item.Repo, marker, item.Number), c.siteURL(item.Repo, page, strconv.FormatInt(item.Number, 10)))
204 rows[i] = []cell{ref, cFlex(item.Title), cText(item.Author)}
205 }
206 return rows
207 }
208
209 if d.Unread > 0 {
210 fmt.Fprintf(w, "unread notifications: %d\n", d.Unread)
211 }
212 section("waiting on your review:", itemRows(d.Reviews, "!"))
213 section("assigned to you:", itemRows(d.Assigned, "#"))
214 section("open merge requests:", itemRows(d.MRs, "!"))
215 section("open issues:", itemRows(d.Issues, "#"))
216 for _, q := range d.Queries {
217 rows := make([][]cell, 0, len(q.Items))
218 for _, it := range q.Items {
219 rows = append(rows, []cell{cRef(it.Ref()), cFlex(it.Title), cText(it.Author)})
220 }
221 title := fmt.Sprintf("query %s (%d):", q.Name, q.Count)
222 if q.Error != "" {
223 title = fmt.Sprintf("query %s: %s", q.Name, q.Error)
224 }
225 section(title, rows)
226 }
227
228 pinnedRows := make([][]cell, len(d.Pinned))
229 for i, p := range d.Pinned {
230 cells := []cell{cLink(p.Path, c.siteURL(p.Path)), cState(p.Visibility), cFlex(p.Description)}
231 if p.Archived {
232 cells = c.note(cells, 1, "[archived]", "archived")
233 }
234 pinnedRows[i] = cells
235 }
236 section("pinned:", pinnedRows)
237
238 activityRows := make([][]cell, len(lines))
239 for i, l := range lines {
240 activityRows[i] = []cell{cAge(l.When), cFlex(l.Sentence())}
241 }
242 section("recent activity:", activityRows)
243
244 buildRows := make([][]cell, len(d.Builds))
245 for i, b := range d.Builds {
246 buildRows[i] = []cell{cLink(b.Repo, c.siteURL(b.Repo, "builds", strconv.FormatInt(b.Number, 10))), cNum(b.Number), cText(b.Job), cState(b.Status), cRef(fmt.Sprintf("%.10s", b.SHA)), cText(b.Ref)}
247 }
248 section("builds:", buildRows)
249
250 if d.Server != nil {
251 fmt.Fprintln(w, "server:")
252 fmt.Fprintf(w, " build %s\n", d.Server.Commit)
253 }
254 if d.Queues != nil {
255 writeQueues(c, w, *d.Queues)
256 }
257}
258
259// writeDashboardSection is a titled list of tab-separated rows, or "none".
260func writeDashboardSection(w io.Writer, title string, rows [][]cell) {
261 fmt.Fprintln(w, title)
262 if len(rows) == 0 {
263 fmt.Fprintln(w, " none")
264 return
265 }
266 for _, r := range rows {
267 parts := make([]string, len(r))
268 for i, cl := range r {
269 parts[i] = cl.s
270 if cl.kind == kindAge {
271 parts[i] = stamp(cl.s)
272 }
273 }
274 fmt.Fprintf(w, " %s\n", strings.Join(parts, "\t"))
275 }
276}
277
278// writeQueues is each background queue's counts and stuck items.
279func writeQueues(c *Ctx, w io.Writer, q store.Queues) {
280 fmt.Fprintln(w, "queues:")
281
282 fmt.Fprintf(w, " webhooks\tpending %d\tretrying %d\tfailed %d\n", q.Webhooks.Pending, q.Webhooks.Retrying, q.Webhooks.Failed)
283 twh := c.table(w, "REPO", "URL", "ATTEMPTS", "ERROR")
284 for _, it := range q.Webhooks.Items {
285 twh.row(cRef(" "+it.Repo), cText(it.URL), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
286 }
287 twh.flush()
288
289 fmt.Fprintf(w, " mail\tpending %d\tretrying %d\tfailed %d\n", q.Mail.Pending, q.Mail.Retrying, q.Mail.Failed)
290 tma := c.table(w, "RECIPIENT", "SUBJECT", "ATTEMPTS", "ERROR")
291 for _, it := range q.Mail.Items {
292 tma.row(cRef(" "+it.Recipient), cText(it.Subject), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
293 }
294 tma.flush()
295
296 // The device id, not the token: a token is never echoed.
297 fmt.Fprintf(w, " push\tpending %d\tretrying %d\tfailed %d\n", q.Push.Pending, q.Push.Retrying, q.Push.Failed)
298 tpu := c.table(w, "DEVICE", "TITLE", "ATTEMPTS", "ERROR")
299 for _, it := range q.Push.Items {
300 tpu.row(cRef(fmt.Sprintf(" device %d", it.DeviceID)), cText(it.Title), cText(fmt.Sprintf("attempts %d", it.Attempts)), cText(it.LastError))
301 }
302 tpu.flush()
303
304 fmt.Fprintf(w, " mirrors\tdirty %d\terrors %d\n", q.Mirrors.Dirty, q.Mirrors.Errors)
305 tmi := c.table(w, "REPO", "DIRECTION", "URL", "ERROR")
306 for _, it := range q.Mirrors.Items {
307 tmi.row(cRef(" "+it.Repo), cText(it.Direction), cText(it.URL), cText(it.LastError))
308 }
309 tmi.flush()
310
311 fmt.Fprintf(w, " builds\tpending %d\trunning %d\n", q.Builds.Pending, q.Builds.Running)
312 tbq := c.table(w, "REPO", "#", "JOB", "STATUS")
313 for _, it := range q.Builds.Items {
314 since := it.StartedAt
315 if it.Status == "pending" {
316 since = it.CreatedAt
317 }
318 since = stamp(since)
319 tbq.row(cRef(" "+it.Repo), cNum(it.Number), cText(it.Job), cText(fmt.Sprintf("%s since %s", it.Status, since)))
320 }
321 tbq.flush()
322
323 fmt.Fprintf(w, " deps\terrors %d\n", q.Deps.Errors)
324 tde := c.table(w, "REPO", "ERROR")
325 for _, it := range q.Deps.Items {
326 tde.row(cRef(" "+it.Repo), cText(it.LastError))
327 }
328 tde.flush()
329}
330
331// feedDefaultLimit caps a bare `feed` call; pagination reaches further
332// back.
333const feedDefaultLimit = 50
334
335type FeedOut struct {
336 ID int64 `json:"id"`
337 Repo string `json:"repo"`
338 Actor string `json:"actor,omitempty"`
339 Kind string `json:"kind"`
340 Data json.RawMessage `json:"data,omitempty"`
341 CreatedAt string `json:"created_at"`
342}
343
344func feedOutputs(events []store.FeedEvent) []FeedOut {
345 ds := make([]FeedOut, 0, len(events))
346 for _, e := range events {
347 d := FeedOut{ID: e.ID, Repo: e.RepoPath, Actor: e.Actor, Kind: e.Kind, CreatedAt: e.CreatedAt}
348 if json.Valid([]byte(e.Data)) {
349 d.Data = json.RawMessage(e.Data)
350 }
351 ds = append(ds, d)
352 }
353 return ds
354}
355
356func runFeed(c *Ctx, args []string) int {
357 rest, p, code := parsePageFlags(c, args, "feed", true)
358 if code >= 0 {
359 return code
360 }
361 if len(rest) != 0 {
362 return c.usage()
363 }
364 if p.limit == 0 {
365 p.limit = feedDefaultLimit
366 }
367 events, err := c.Store.RecentEvents(c.User.ID, p.queryLimit(), p.keyInt())
368 if err != nil {
369 return c.fail(protocol.ExitFailure, "%v", err)
370 }
371 events, next := trimPage(p, events, "feed", func(e store.FeedEvent) string {
372 return strconv.FormatInt(e.ID, 10)
373 })
374 ds := feedOutputs(events)
375 lines := FeedLines(events)
376 return c.emitPageView(p, ds, next, func(w io.Writer) {
377 tb := c.table(w, "WHEN", "EVENT")
378 for _, l := range lines {
379 tb.row(cAge(l.When), cFlex(l.Sentence()))
380 }
381 tb.flush()
382 }, func() screen {
383 rows := make([]row, len(lines))
384 for i, l := range lines {
385 rows[i] = rowOf(l.termCells(c)...)
386 }
387 return listScreen("Activity", rows)
388 })
389}
390
391// dashboardScreen is dashboard at a terminal: what waits on the viewer
392// first, then open merge requests, failed builds, a few lines of
393// activity and the pinned repositories. The operator's queues are
394// admin stats'; a background failure shows as one header line.
395func dashboardScreen(c *Ctx, d DashboardOut, lines []FeedLine) screen {
396 var s screen
397 s.fields = append(s.fields, field{"User", []cell{cText(c.User.Username)}})
398 if host := c.Cfg.SiteHost(); host != "" {
399 s.fields = append(s.fields, field{"Instance", []cell{cText(host)}})
400 }
401 if q := d.Queues; q != nil {
402 if bad := q.Webhooks.Failed + q.Mail.Failed + q.Push.Failed + q.Mirrors.Errors + q.Deps.Errors; bad > 0 {
403 s.fields = append(s.fields, field{"Problems", []cell{cGlyph("failed"), cText(fmt.Sprintf("%d failing in the background", bad))}})
404 }
405 }
406 if d.Unread > 0 {
407 s.fields = append(s.fields, field{"Inbox", []cell{cYou(), cText(fmt.Sprintf("%d unread", d.Unread))}})
408 }
409
410 item := func(it DashboardItem, marker, page string, you bool) row {
411 lead := cell{kind: kindGlyph}
412 if you {
413 lead = cYou()
414 }
415 ref := cLink(fmt.Sprintf("%s%s%d", it.Repo, marker, it.Number), c.siteURL(it.Repo, page, strconv.FormatInt(it.Number, 10)))
416 return rowOf(ref, lead, cFlex(it.Title), cMeta(it.Author))
417 }
418 items := func(title string, its []DashboardItem, marker, page string, you bool) section {
419 sec := section{title: title, n: len(its)}
420 for _, it := range its {
421 sec.rows = append(sec.rows, item(it, marker, page, you))
422 }
423 return sec
424 }
425 s.sections = append(s.sections,
426 items("Review requested", d.Reviews, "!", "mrs", true),
427 items("Assigned issues", d.Assigned, "#", "issues", true),
428 items("Open merge requests", d.MRs, "!", "mrs", false),
429 )
430 for _, q := range d.Queries {
431 sec := section{title: q.Name, n: q.Count, more: []string{"query", "run", q.Name}}
432 if q.Error != "" {
433 sec.note, sec.empty = q.Error, true
434 }
435 for _, it := range q.Items {
436 sec.rows = append(sec.rows, rowOf(cRef(it.Ref()), cFlex(it.Title), cMeta(it.Author)))
437 }
438 s.sections = append(s.sections, sec)
439 }
440
441 // A job's latest build is the one that counts: a failure a later
442 // build of the same job and ref has replaced is not shown.
443 failed := section{title: "Failed builds"}
444 passed := 0
445 seen := map[string]bool{}
446 var firstFailed *DashboardBuild
447 for i, b := range d.Builds {
448 key := b.Repo + "\x00" + b.Job + "\x00" + b.Ref
449 if seen[key] {
450 continue
451 }
452 seen[key] = true
453 switch b.Status {
454 case "success":
455 passed++
456 case "failure", "error":
457 n := strconv.FormatInt(b.Number, 10)
458 failed.n++
459 failed.rows = append(failed.rows, rowOf(cLink(n, c.siteURL(b.Repo, "builds", n)), cGlyph(b.Status),
460 cFlex(b.Job+" "+b.Ref), cMeta(b.Repo, relAge(b.CreatedAt, termNow()))))
461 if firstFailed == nil {
462 firstFailed = &d.Builds[i]
463 }
464 }
465 }
466 s.sections = append(s.sections, failed)
467
468 activity := section{title: "Recent activity", n: len(lines), more: []string{"feed"}}
469 for _, l := range lines[:min(len(lines), dashboardActivity)] {
470 activity.rows = append(activity.rows, rowOf(l.termCells(c)...))
471 }
472 if passed > 0 {
473 word := "builds"
474 if passed == 1 {
475 word = "build"
476 }
477 activity.note, activity.empty = fmt.Sprintf("%d %s passed", passed, word), true
478 }
479 s.sections = append(s.sections, activity)
480
481 if len(d.Pinned) > 0 {
482 paths := make([]string, len(d.Pinned))
483 for i, p := range d.Pinned {
484 paths[i] = p.Path
485 }
486 s.sections = append(s.sections, section{title: "Pinned", n: len(d.Pinned), rows: []row{rowOf(cMeta(strings.Join(paths, " ")))}})
487 }
488
489 if len(d.Reviews) > 0 {
490 it := d.Reviews[0]
491 s.actions = append(s.actions, action{"Next", []string{"mr", "show", it.Repo, strconv.FormatInt(it.Number, 10)}})
492 }
493 if len(d.Assigned) > 0 {
494 it := d.Assigned[0]
495 s.actions = append(s.actions, action{"Next", []string{"issue", "show", it.Repo, strconv.FormatInt(it.Number, 10)}})
496 }
497 if firstFailed != nil {
498 s.actions = append(s.actions, action{"Next", []string{"build", "log", firstFailed.Repo, strconv.FormatInt(firstFailed.Number, 10)}})
499 }
500 s.actions = append(s.actions, action{"More", []string{"feed"}})
501 if c.User.IsAdmin {
502 s.actions = append(s.actions, action{"Instance", []string{"admin", "stats"}})
503 }
504 return s
505}