Debian Codegraph @

debian/go/src/golang.org/x/telemetry/cmd/gotelemetry/internal/view/view.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // The view command is a server intended to be run on a user's machine to
6 // display the local counters and time series charts of counters.
7 package view
8
9 import (
10 "bytes"
11 "encoding/json"
12 "fmt"
13 "html"
14 "html/template"
15 "io/fs"
16 "log"
17 "net"
18 "net/http"
19 "os"
20 "path"
21 "sort"
22 "strconv"
23 "strings"
24 "time"
25
26 "golang.org/x/telemetry/cmd/gotelemetry/internal/browser"
27 "golang.org/x/telemetry/internal/config"
28 "golang.org/x/telemetry/internal/configstore"
29 contentfs "golang.org/x/telemetry/internal/content"
30 tcounter "golang.org/x/telemetry/internal/counter"
31 "golang.org/x/telemetry/internal/telemetry"
32 "golang.org/x/telemetry/internal/unionfs"
33 )
34
35 type Server struct {
36 Addr string
37 Dev bool
38 FsConfig string
39 Open bool
40 }
41
42 // Serve starts the telemetry viewer and runs indefinitely.
43 func (s *Server) Serve() {
44 var fsys fs.FS = contentfs.FS
45 if s.Dev {
46 fsys = os.DirFS("internal/content")
47 contentfs.RunESBuild(true)
48 }
49
50 var err error
51 fsys, err = unionfs.Sub(fsys, "gotelemetryview", "shared")
52 if err != nil {
53 log.Fatal(err)
54 }
55
56 mux := http.NewServeMux()
57 mux.Handle("/", s.handleIndex(fsys))
58 listener, err := net.Listen("tcp", s.Addr)
59 if err != nil {
60 log.Fatal(err)
61 }
62 addr := fmt.Sprintf("http://%s", listener.Addr())
63 fmt.Printf("server listening at %s\n", addr)
64 if s.Open {
65 browser.Open(addr)
66 }
67 log.Fatal(http.Serve(listener, mux))
68 }
69
70 type page struct {
71 // Config is the config used to render the requested page.
72 Config *config.Config
73
74 // PrettyConfig is the Config struct formatted as indented JSON for display on the page.
75 PrettyConfig string
76
77 // ConfigVersion is used to render a dropdown list of config versions for a user to select.
78 ConfigVersions []string
79
80 // RequestedConfig is the URL query param value for config.
81 RequestedConfig string
82
83 // Files are the local counter files for display on the page.
84 Files []*counterFile
85
86 // Reports are the local reports for display on the page.
87 Reports []*telemetryReport
88
89 // Charts is the counter data from files and reports grouped by program and counter name.
90 Charts *chartdata
91 }
92
93 // TODO: filtering and pagination for date ranges
94 func (s *Server) handleIndex(fsys fs.FS) handlerFunc {
95 return func(w http.ResponseWriter, r *http.Request) error {
96 if r.URL.Path != "/" {
97 http.FileServer(http.FS(fsys)).ServeHTTP(w, r)
98 return nil
99 }
100 requestedConfig := r.URL.Query().Get("config")
101 if requestedConfig == "" {
102 requestedConfig = "latest"
103 }
104 cfg, err := s.configAt(requestedConfig)
105 if err != nil {
106 log.Printf("Falling back to empty config: %v", err)
107 cfg, _ = s.configAt("empty")
108 }
109 cfgVersionList, err := configVersions()
110 if err != nil {
111 return err
112 }
113 cfgJSON, err := json.MarshalIndent(cfg, "", "\t")
114 if err != nil {
115 return err
116 }
117 localDir := telemetry.Default.LocalDir()
118 if _, err := os.Stat(localDir); err != nil {
119 return fmt.Errorf(
120 `The telemetry dir %s does not exist.
121 There is nothing to report.`, telemetry.Default.LocalDir())
122 }
123 reports, err := reports(localDir, cfg)
124 if err != nil {
125 return err
126 }
127 files, err := files(localDir, cfg)
128 if err != nil {
129 return err
130 }
131 charts := charts(append(reports, pending(files, cfg)...), cfg)
132 data := page{
133 Config: cfg,
134 PrettyConfig: string(cfgJSON),
135 ConfigVersions: cfgVersionList,
136 Reports: reports,
137 Files: files,
138 Charts: charts,
139 RequestedConfig: requestedConfig,
140 }
141 return renderTemplate(w, fsys, "index.html", data, http.StatusOK)
142 }
143 }
144
145 // configAt gets the config at a given version.
146 func (s Server) configAt(version string) (ucfg *config.Config, err error) {
147 if version == "" || version == "empty" {
148 return config.NewConfig(&telemetry.UploadConfig{}), nil
149 }
150 if s.FsConfig != "" {
151 ucfg, err = config.ReadConfig(s.FsConfig)
152 if err != nil {
153 return nil, err
154 }
155 } else {
156 cfg, _, err := configstore.Download(version, nil)
157 if err != nil {
158 return nil, err
159 }
160 ucfg = config.NewConfig(cfg)
161 }
162 return ucfg, nil
163 }
164
165 // configVersions is the set of config versions the user may select from the UI.
166 // TODO: get the list of versions available from the proxy.
167 func configVersions() ([]string, error) {
168 v := []string{"latest"}
169 return v, nil
170 }
171
172 // reports reads the local report files from a directory.
173 func reports(dir string, cfg *config.Config) ([]*telemetryReport, error) {
174 fsys := os.DirFS(dir)
175 entries, err := fs.ReadDir(fsys, ".")
176 if err != nil {
177 return nil, err
178 }
179 var reports []*telemetryReport
180 for _, e := range entries {
181 if path.Ext(e.Name()) != ".json" {
182 continue
183 }
184 data, err := fs.ReadFile(fsys, e.Name())
185 if err != nil {
186 log.Printf("read report file failed: %v", err)
187 continue
188 }
189 var report *telemetry.Report
190 if err := json.Unmarshal(data, &report); err != nil {
191 log.Printf("unmarshal report file failed: %v", err)
192 continue
193 }
194 reports = append(reports, newTelemetryReport(report, cfg))
195 }
196 // sort the reports descending by week.
197 sort.Slice(reports, func(i, j int) bool {
198 return reports[j].Week < reports[i].Week
199 })
200 return reports, nil
201 }
202
203 // telemetryReport wraps telemetry report to add convenience fields for the UI.
204 type telemetryReport struct {
205 *telemetry.Report
206 ID string
207 Programs []*telemetryProgram
208 }
209
210 type telemetryProgram struct {
211 *telemetry.ProgramReport
212 ID string
213 Summary template.HTML
214 }
215
216 func newTelemetryReport(t *telemetry.Report, cfg *config.Config) *telemetryReport {
217 var prgms []*telemetryProgram
218 for _, p := range t.Programs {
219 meta := map[string]string{
220 "Program": p.Program,
221 "Version": p.Version,
222 "GOOS": p.GOOS,
223 "GOARCH": p.GOARCH,
224 "GoVersion": p.GoVersion,
225 }
226 counters := make(map[string]uint64)
227 for k, v := range p.Counters {
228 counters[k] = uint64(v)
229 }
230 prgms = append(prgms, &telemetryProgram{
231 ProgramReport: p,
232 ID: strings.Join([]string{"reports", t.Week, p.Program, p.Version, p.GOOS, p.GOARCH, p.GoVersion}, ":"),
233 Summary: summary(cfg, meta, counters),
234 })
235 }
236 return &telemetryReport{
237 Report: t,
238 ID: "reports:" + t.Week,
239 Programs: prgms,
240 }
241 }
242
243 // files reads the local counter files from a directory.
244 func files(dir string, cfg *config.Config) ([]*counterFile, error) {
245 fsys := os.DirFS(dir)
246 entries, err := fs.ReadDir(fsys, ".")
247 if err != nil {
248 return nil, err
249 }
250 var files []*counterFile
251 for _, e := range entries {
252 if e.IsDir() || path.Ext(e.Name()) != ".count" {
253 continue
254 }
255 data, err := fs.ReadFile(fsys, e.Name())
256 if err != nil {
257 log.Printf("read counter file failed: %v", err)
258 continue
259 }
260
261 file, err := tcounter.Parse(e.Name(), data)
262 if err != nil {
263 log.Printf("parse counter file failed: %v", err)
264 continue
265 }
266 files = append(files, newCounterFile(e.Name(), file, cfg))
267 }
268 return files, nil
269 }
270
271 // counterFile wraps counter file to add convenience fields for the UI.
272 type counterFile struct {
273 *tcounter.File
274 ID string
275 Summary template.HTML
276 ActiveMeta map[string]bool
277 Counts []*count
278 Stacks []*stack
279 }
280
281 type count struct {
282 Name string
283 Value uint64
284 Active bool
285 }
286
287 type stack struct {
288 Name string
289 Trace string
290 Value uint64
291 Active bool
292 }
293
294 func newCounterFile(name string, c *tcounter.File, cfg *config.Config) *counterFile {
295 activeMeta := map[string]bool{
296 "Program": cfg.HasProgram(c.Meta["Program"]),
297 "Version": cfg.HasVersion(c.Meta["Program"], c.Meta["Version"]),
298 "GOOS": cfg.HasGOOS(c.Meta["GOOS"]),
299 "GOARCH": cfg.HasGOARCH(c.Meta["GOARCH"]),
300 "GoVersion": cfg.HasGoVersion(c.Meta["GoVersion"]),
301 }
302 var counts []*count
303 var stacks []*stack
304 for k, v := range c.Count {
305 if summary, details, ok := strings.Cut(k, "\n"); ok {
306 active := cfg.HasStack(c.Meta["Program"], k)
307 stacks = append(stacks, &stack{summary, details, v, active})
308 } else {
309 active := cfg.HasCounter(c.Meta["Program"], k)
310 counts = append(counts, &count{k, v, active})
311 }
312 }
313 sort.Slice(counts, func(i, j int) bool {
314 return counts[i].Name < counts[j].Name
315 })
316 sort.Slice(stacks, func(i, j int) bool {
317 return stacks[i].Name < stacks[j].Name
318 })
319 return &counterFile{
320 File: c,
321 ID: name,
322 ActiveMeta: activeMeta,
323 Counts: counts,
324 Stacks: stacks,
325 Summary: summary(cfg, c.Meta, c.Count),
326 }
327 }
328
329 // summary generates a summary of a set of telemetry data. It describes what data is
330 // located in the set is not allowed given a config and how the data would be handled
331 // in the event of a telemetry upload event.
332 func summary(cfg *config.Config, meta map[string]string, counts map[string]uint64) template.HTML {
333 msg := " is unregistered. No data from this set would be uploaded to the Go team."
334 if prog := meta["Program"]; !(cfg.HasProgram(prog)) {
335 return template.HTML(fmt.Sprintf(
336 "The program <code>%s</code>"+msg,
337 html.EscapeString(prog),
338 ))
339 }
340 var result strings.Builder
341 if !(cfg.HasGOOS(meta["GOOS"])) || !(cfg.HasGOARCH(meta["GOARCH"])) {
342 return template.HTML(fmt.Sprintf(
343 "The GOOS/GOARCH combination <code>%s/%s</code> "+msg,
344 html.EscapeString(meta["GOOS"]),
345 html.EscapeString(meta["GOARCH"]),
346 ))
347 }
348 goVersion := meta["GoVersion"]
349 if !(cfg.HasGoVersion(goVersion)) {
350 return template.HTML(fmt.Sprintf(
351 "The go version <code>%s</code> "+msg,
352 html.EscapeString(goVersion),
353 ))
354 }
355 version := meta["Version"]
356 if !(cfg.HasVersion(meta["Program"], version)) {
357 return template.HTML(fmt.Sprintf(
358 "The version <code>%s</code> "+msg,
359 html.EscapeString(version),
360 ))
361 }
362 var counters []string
363 for c := range counts {
364 summary, _, ok := strings.Cut(c, "\n")
365 if ok && !cfg.HasStack(meta["Program"], c) {
366 counters = append(counters, fmt.Sprintf("<code>%s</code>", html.EscapeString(summary)))
367 }
368 if !ok && !(cfg.HasCounter(meta["Program"], c)) {
369 counters = append(counters, fmt.Sprintf("<code>%s</code>", html.EscapeString(c)))
370 }
371 }
372 if len(counters) > 0 {
373 result.WriteString("Unregistered counter(s) ")
374 result.WriteString(strings.Join(counters, ", "))
375 result.WriteString(" would be excluded from a report. ")
376 }
377 return template.HTML(result.String())
378 }
379
380 type chartdata struct {
381 Programs []*program
382 // DateRange is used to align the week intervals for each of the charts.
383 DateRange [2]string
384 }
385
386 type program struct {
387 ID string
388 Name string
389 Counters []*counter
390 Active bool
391 }
392
393 type counter struct {
394 ID string
395 Name string
396 Data []*datum
397 Active bool
398 }
399
400 type datum struct {
401 Week string
402 Program string
403 Version string
404 GOARCH string
405 GOOS string
406 GoVersion string
407 Key string
408 Value int64
409 }
410
411 // charts returns chartdata for a set of telemetry reports. It uses the config
412 // to determine if the programs and counters are active.
413 func charts(reports []*telemetryReport, cfg *config.Config) *chartdata {
414 data := grouped(reports)
415 result := &chartdata{DateRange: reportsDomain(reports)}
416 for pg, pgdata := range data {
417 prog := &program{ID: "charts:" + pg.Name, Name: pg.Name, Active: cfg.HasProgram(pg.Name)}
418 result.Programs = append(result.Programs, prog)
419 for c, cdata := range pgdata {
420 count := &counter{
421 ID: "charts:" + pg.Name + ":" + c.Name,
422 Name: c.Name,
423 Data: cdata,
424 Active: cfg.HasCounter(pg.Name, c.Name) || cfg.HasCounterPrefix(pg.Name, c.Name),
425 }
426 prog.Counters = append(prog.Counters, count)
427 sort.Slice(count.Data, func(i, j int) bool {
428 a, err1 := strconv.ParseFloat(count.Data[i].Key, 32)
429 b, err2 := strconv.ParseFloat(count.Data[j].Key, 32)
430 if err1 == nil && err2 == nil {
431 return a < b
432 }
433 return count.Data[i].Key < count.Data[j].Key
434 })
435 }
436 sort.Slice(prog.Counters, func(i, j int) bool {
437 return prog.Counters[i].Name < prog.Counters[j].Name
438 })
439 }
440 sort.Slice(result.Programs, func(i, j int) bool {
441 return result.Programs[i].Name < result.Programs[j].Name
442 })
443 return result
444 }
445
446 // reportsDomain computes a common reportsDomain to use for all reports, assuming a week
447 // centered around sunday (the default bin behavior in the observablehq
448 // plotting library).
449 //
450 // TODO(rfindley): use the actual weekday file to compute better bins
451 // right-aligned to the upload date, or figure something else out.
452 func reportsDomain(reports []*telemetryReport) [2]string {
453 var weeks []string
454 for _, r := range reports {
455 weeks = append(weeks, r.Week)
456 }
457 sort.Strings(weeks)
458 return domain(weeks)
459 }
460
461 func domain(weeks []string) [2]string {
462 start := weeks[0]
463 const timeFormat = "2006-01-02"
464 if st, err := time.Parse(timeFormat, start); err == nil {
465 st = st.AddDate(0, 0, -int(st.Weekday()-time.Sunday)) // adjust to preceding Sunday
466 start = st.Format(timeFormat)
467 }
468 end := weeks[len(weeks)-1]
469 if et, err := time.Parse(timeFormat, end); err == nil {
470 et = et.AddDate(0, 0, int(time.Sunday+7-et.Weekday()))
471 end = et.Format(timeFormat) // adjust to next Saturday
472 }
473 return [2]string{start, end}
474 }
475
476 type programKey struct {
477 Name string
478 }
479
480 type counterKey struct {
481 Name string
482 }
483
484 // grouped returns normalized counter data grouped by program and counter.
485 func grouped(reports []*telemetryReport) map[programKey]map[counterKey][]*datum {
486 result := make(map[programKey]map[counterKey][]*datum)
487 for _, r := range reports {
488 for _, e := range r.Programs {
489 pgkey := programKey{e.Program}
490 if _, ok := result[pgkey]; !ok {
491 result[pgkey] = make(map[counterKey][]*datum)
492 }
493 for counter, value := range e.Counters {
494 name, bucket, found := strings.Cut(counter, ":")
495 key := name
496 if found {
497 key = bucket
498 }
499 element := &datum{
500 Week: r.Week,
501 Program: e.Program,
502 Version: e.Version,
503 GOARCH: e.GOARCH,
504 GOOS: e.GOOS,
505 GoVersion: e.GoVersion,
506 Key: key,
507 Value: value,
508 }
509 ckey := counterKey{name}
510 result[pgkey][ckey] = append(result[pgkey][ckey], element)
511 }
512 for counter, value := range e.Stacks {
513 summary, _, _ := strings.Cut(counter, "\n")
514 element := &datum{
515 Week: r.Week,
516 Program: e.Program,
517 Version: e.Version,
518 GOARCH: e.GOARCH,
519 GOOS: e.GOOS,
520 GoVersion: e.GoVersion,
521 Key: summary,
522 Value: value,
523 }
524 ckey := counterKey{summary}
525 result[pgkey][ckey] = append(result[pgkey][ckey], element)
526 }
527 }
528 }
529 return result
530 }
531
532 // pending transforms the active counter files into a report. Used to add
533 // the data they contain to the charts in the UI.
534 func pending(files []*counterFile, cfg *config.Config) []*telemetryReport {
535 reports := make(map[string]*telemetry.Report)
536 for _, f := range files {
537 tb, _ := time.Parse(time.RFC3339, f.Meta["TimeEnd"])
538 week := tb.Format("2006-01-02")
539 if _, ok := reports[week]; !ok {
540 reports[week] = &telemetry.Report{Week: week}
541 }
542 program := &telemetry.ProgramReport{
543 Program: f.Meta["Program"],
544 GOOS: f.Meta["GOOS"],
545 GOARCH: f.Meta["GOARCH"],
546 GoVersion: f.Meta["GoVersion"],
547 Version: f.Meta["Version"],
548 }
549 program.Counters = make(map[string]int64)
550 program.Stacks = make(map[string]int64)
551 for k, v := range f.Count {
552 if tcounter.IsStackCounter(k) {
553 program.Stacks[k] = int64(v)
554 } else {
555 program.Counters[k] = int64(v)
556 }
557 }
558 reports[week].Programs = append(reports[week].Programs, program)
559 }
560 var result []*telemetryReport
561 for _, r := range reports {
562 result = append(result, newTelemetryReport(r, cfg))
563 }
564 return result
565 }
566
567 type handlerFunc func(http.ResponseWriter, *http.Request) error
568
569 func (f handlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
570 if err := f(w, r); err != nil {
571 http.Error(w, err.Error(), http.StatusInternalServerError)
572 }
573 }
574
575 // renderTemplate executes a template response.
576 func renderTemplate(w http.ResponseWriter, fsys fs.FS, tmplPath string, data any, code int) error {
577 patterns, err := tmplPatterns(fsys, tmplPath)
578 if err != nil {
579 return err
580 }
581 patterns = append(patterns, tmplPath)
582 tmpl, err := template.ParseFS(fsys, patterns...)
583 if err != nil {
584 return err
585 }
586 name := path.Base(tmplPath)
587 var buf bytes.Buffer
588 if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
589 return err
590 }
591 if code != 0 {
592 w.WriteHeader(code)
593 }
594 w.Header().Set("Content-Type", "text/html")
595 w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
596 if _, err := w.Write(buf.Bytes()); err != nil {
597 return err
598 }
599 return nil
600 }
601
602 // tmplPatterns generates a slice of file patterns to use in template.ParseFS.
603 func tmplPatterns(fsys fs.FS, tmplPath string) ([]string, error) {
604 var patterns []string
605 globs := []string{"*.tmpl", path.Join(path.Dir(tmplPath), "*.tmpl")}
606 for _, g := range globs {
607 matches, err := fs.Glob(fsys, g)
608 if err != nil {
609 return nil, err
610 }
611 patterns = append(patterns, matches...)
612 }
613 return patterns, nil
614 }