Debian Codegraph @

gopls/internal/debug/serve.go

raw symbols SCIP
1 // Copyright 2019 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 package debug
6
7 import (
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "html/template"
13 "io"
14 stdlog "log"
15 "net"
16 "net/http"
17 "net/http/pprof"
18 "os"
19 "path"
20 "path/filepath"
21 "runtime"
22 "strconv"
23 "strings"
24 "sync"
25 "time"
26
27 "golang.org/x/tools/gopls/internal/cache"
28 "golang.org/x/tools/gopls/internal/cache/metadata"
29 "golang.org/x/tools/gopls/internal/debug/log"
30 "golang.org/x/tools/gopls/internal/file"
31 label1 "golang.org/x/tools/gopls/internal/label"
32 "golang.org/x/tools/gopls/internal/protocol"
33 "golang.org/x/tools/gopls/internal/util/bug"
34 versionpkg "golang.org/x/tools/gopls/internal/version"
35 "golang.org/x/tools/internal/event"
36 "golang.org/x/tools/internal/event/core"
37 "golang.org/x/tools/internal/event/export"
38 "golang.org/x/tools/internal/event/export/metric"
39 "golang.org/x/tools/internal/event/export/otel"
40 "golang.org/x/tools/internal/event/export/prometheus"
41 "golang.org/x/tools/internal/event/keys"
42 "golang.org/x/tools/internal/event/label"
43 )
44
45 type contextKeyType int
46
47 const (
48 instanceKey contextKeyType = iota
49 traceKey
50 )
51
52 // An Instance holds all debug information associated with a gopls instance.
53 type Instance struct {
54 Logfile string
55 StartTime time.Time
56 ServerAddress string
57
58 LogWriter io.Writer
59
60 exporter event.Exporter
61
62 prometheus *prometheus.Exporter
63 rpcs *Rpcs
64 traces *traces
65 otel *otel.Exporter
66 State *State
67
68 serveMu sync.Mutex
69 debugAddress string
70 listenedDebugAddress string
71 }
72
73 // State holds debugging information related to the server state.
74 type State struct {
75 mu sync.Mutex
76 clients []*Client
77 servers []*Server
78 }
79
80 func (st *State) Bugs() []bug.Bug {
81 return bug.List()
82 }
83
84 // Caches returns the set of Cache objects currently being served.
85 func (st *State) Caches() []*cache.Cache {
86 var caches []*cache.Cache
87 seen := make(map[string]struct{})
88 for _, client := range st.Clients() {
89 cache := client.Session.Cache()
90 if _, found := seen[cache.ID()]; found {
91 continue
92 }
93 seen[cache.ID()] = struct{}{}
94 caches = append(caches, cache)
95 }
96 return caches
97 }
98
99 // Cache returns the Cache that matches the supplied id.
100 func (st *State) Cache(id string) *cache.Cache {
101 for _, c := range st.Caches() {
102 if c.ID() == id {
103 return c
104 }
105 }
106 return nil
107 }
108
109 // Analysis returns the global Analysis template value.
110 func (st *State) Analysis() (_ analysisTmpl) { return }
111
112 type analysisTmpl struct{}
113
114 func (analysisTmpl) AnalyzerRunTimes() []cache.LabelDuration { return cache.AnalyzerRunTimes() }
115
116 // Sessions returns the set of Session objects currently being served.
117 func (st *State) Sessions() []*cache.Session {
118 var sessions []*cache.Session
119 for _, client := range st.Clients() {
120 sessions = append(sessions, client.Session)
121 }
122 return sessions
123 }
124
125 // Session returns the Session that matches the supplied id.
126 func (st *State) Session(id string) *cache.Session {
127 for _, s := range st.Sessions() {
128 if s.ID() == id {
129 return s
130 }
131 }
132 return nil
133 }
134
135 // Views returns the set of View objects currently being served.
136 func (st *State) Views() []*cache.View {
137 var views []*cache.View
138 for _, s := range st.Sessions() {
139 views = append(views, s.Views()...)
140 }
141 return views
142 }
143
144 // View returns the View that matches the supplied id.
145 func (st *State) View(id string) *cache.View {
146 for _, s := range st.Sessions() {
147 if v, err := s.View(id); err == nil {
148 return v
149 }
150 }
151 return nil // not found
152 }
153
154 // Clients returns the set of Clients currently being served.
155 func (st *State) Clients() []*Client {
156 st.mu.Lock()
157 defer st.mu.Unlock()
158 clients := make([]*Client, len(st.clients))
159 copy(clients, st.clients)
160 return clients
161 }
162
163 // Client returns the Client matching the supplied id.
164 func (st *State) Client(id string) *Client {
165 for _, c := range st.Clients() {
166 if c.Session.ID() == id {
167 return c
168 }
169 }
170 return nil
171 }
172
173 // Servers returns the set of Servers the instance is currently connected to.
174 func (st *State) Servers() []*Server {
175 st.mu.Lock()
176 defer st.mu.Unlock()
177 servers := make([]*Server, len(st.servers))
178 copy(servers, st.servers)
179 return servers
180 }
181
182 // A Client is an incoming connection from a remote client.
183 type Client struct {
184 Session *cache.Session
185 DebugAddress string
186 Logfile string
187 GoplsPath string
188 ServerID string
189 Service protocol.Server
190 }
191
192 // A Server is an outgoing connection to a remote LSP server.
193 type Server struct {
194 ID string
195 DebugAddress string
196 Logfile string
197 GoplsPath string
198 ClientID string
199 }
200
201 // addClient adds a client to the set being served.
202 func (st *State) addClient(session *cache.Session) {
203 st.mu.Lock()
204 defer st.mu.Unlock()
205 st.clients = append(st.clients, &Client{Session: session})
206 }
207
208 // dropClient removes a client from the set being served.
209 func (st *State) dropClient(session *cache.Session) {
210 st.mu.Lock()
211 defer st.mu.Unlock()
212 for i, c := range st.clients {
213 if c.Session == session {
214 copy(st.clients[i:], st.clients[i+1:])
215 st.clients[len(st.clients)-1] = nil
216 st.clients = st.clients[:len(st.clients)-1]
217 return
218 }
219 }
220 }
221
222 // updateServer updates a server to the set being queried. In practice, there should
223 // be at most one remote server.
224 func (st *State) updateServer(server *Server) {
225 st.mu.Lock()
226 defer st.mu.Unlock()
227 for i, existing := range st.servers {
228 if existing.ID == server.ID {
229 // Replace, rather than mutate, to avoid a race.
230 newServers := make([]*Server, len(st.servers))
231 copy(newServers, st.servers[:i])
232 newServers[i] = server
233 copy(newServers[i+1:], st.servers[i+1:])
234 st.servers = newServers
235 return
236 }
237 }
238 st.servers = append(st.servers, server)
239 }
240
241 // dropServer drops a server from the set being queried.
242 func (st *State) dropServer(id string) {
243 st.mu.Lock()
244 defer st.mu.Unlock()
245 for i, s := range st.servers {
246 if s.ID == id {
247 copy(st.servers[i:], st.servers[i+1:])
248 st.servers[len(st.servers)-1] = nil
249 st.servers = st.servers[:len(st.servers)-1]
250 return
251 }
252 }
253 }
254
255 // an http.ResponseWriter that filters writes
256 type filterResponse struct {
257 w http.ResponseWriter
258 edit func([]byte) []byte
259 }
260
261 func (c filterResponse) Header() http.Header {
262 return c.w.Header()
263 }
264
265 func (c filterResponse) Write(buf []byte) (int, error) {
266 ans := c.edit(buf)
267 return c.w.Write(ans)
268 }
269
270 func (c filterResponse) WriteHeader(n int) {
271 c.w.WriteHeader(n)
272 }
273
274 // replace annoying nuls by spaces
275 func cmdline(w http.ResponseWriter, r *http.Request) {
276 fake := filterResponse{
277 w: w,
278 edit: func(buf []byte) []byte {
279 return bytes.ReplaceAll(buf, []byte{0}, []byte{' '})
280 },
281 }
282 pprof.Cmdline(fake, r)
283 }
284
285 func (i *Instance) getCache(r *http.Request) any {
286 return i.State.Cache(path.Base(r.URL.Path))
287 }
288
289 func (i *Instance) getAnalysis(r *http.Request) any {
290 return i.State.Analysis()
291 }
292
293 func (i *Instance) getSession(r *http.Request) any {
294 return i.State.Session(path.Base(r.URL.Path))
295 }
296
297 func (i *Instance) getClient(r *http.Request) any {
298 return i.State.Client(path.Base(r.URL.Path))
299 }
300
301 func (i *Instance) getServer(r *http.Request) any {
302 i.State.mu.Lock()
303 defer i.State.mu.Unlock()
304 id := path.Base(r.URL.Path)
305 for _, s := range i.State.servers {
306 if s.ID == id {
307 return s
308 }
309 }
310 return nil
311 }
312
313 type FileWithKind interface {
314 file.Handle
315 Kind() file.Kind // (overlay files only)
316 }
317
318 // /file/{session}/{identifier}. Returns a [FileWithKind].
319 func (i *Instance) getFile(r *http.Request) any {
320 s := i.State.Session(r.PathValue("session"))
321 if s == nil {
322 return nil
323 }
324 identifier := r.PathValue("identifier")
325 for _, o := range s.Overlays() {
326 // TODO(adonovan): understand and document this comparison.
327 if o.Identity().Hash.String() == identifier {
328 return o
329 }
330 }
331 return nil
332 }
333
334 type MetadataInfo struct {
335 SessionID string
336 ViewID string
337 Graph *metadata.Graph
338 }
339
340 // /metadata/{session}/{view}. Returns a [*MetadataInfo].
341 func (i *Instance) getMetadata(r *http.Request) any {
342 session := i.State.Session(r.PathValue("session"))
343 if session == nil {
344 return nil
345 }
346
347 v, err := session.View(r.PathValue("view"))
348 if err != nil {
349 stdlog.Printf("/metadata: %v", err)
350 return nil // no found
351 }
352
353 snapshot, release, err := v.Snapshot()
354 if err != nil {
355 stdlog.Printf("/metadata: failed to get latest snapshot: %v", err)
356 return nil
357 }
358 defer release()
359 return &MetadataInfo{
360 SessionID: session.ID(),
361 ViewID: v.ID(),
362 Graph: snapshot.MetadataGraph(),
363 }
364 }
365
366 type PackageInfo struct {
367 SessionID string
368 ViewID string
369 Package *cache.Package
370 Diagnostics map[protocol.DocumentURI][]*cache.Diagnostic
371 }
372
373 // /package/{session}/{view}/{id...}. Returns a [*PackageInfo].
374 func (i *Instance) getPackage(r *http.Request) any {
375 // TODO(adonovan): shouldn't we report an HTTP error in all
376 // these early returns? Same for getMetadata.
377 session := i.State.Session(r.PathValue("session"))
378 if session == nil {
379 return nil // not found
380 }
381
382 v, err := session.View(r.PathValue("view"))
383 if err != nil {
384 stdlog.Printf("/package: %v", err)
385 return nil // not found
386 }
387
388 id := r.PathValue("id")
389
390 snapshot, release, err := v.Snapshot()
391 if err != nil {
392 stdlog.Printf("/package: failed to get latest snapshot: %v", err)
393 return nil
394 }
395 defer release()
396
397 pkgs, err := snapshot.TypeCheck(r.Context(), cache.PackageID(id))
398 if err != nil {
399 stdlog.Printf("/package: failed to typecheck package %q: %v", id, err)
400 return nil
401 }
402
403 // (PackageDiagnostics is redundant w.r.t. TypeCheck but it's
404 // the only way to access type errors in cache.Diagnostic form.)
405 diags, err := snapshot.PackageDiagnostics(r.Context(), cache.PackageID(id))
406 if err != nil {
407 stdlog.Printf("/package: failed to typecheck package %q: %v", id, err)
408 return nil
409 }
410
411 return &PackageInfo{
412 SessionID: session.ID(),
413 ViewID: v.ID(),
414 Package: pkgs[0],
415 Diagnostics: diags,
416 }
417 }
418
419 func (i *Instance) getInfo(r *http.Request) any {
420 buf := &bytes.Buffer{}
421 i.writeServerInfo(buf)
422 return template.HTML(buf.String())
423 }
424
425 func (i *Instance) AddService(s protocol.Server, session *cache.Session) {
426 for _, c := range i.State.clients {
427 if c.Session == session {
428 c.Service = s
429 return
430 }
431 }
432 stdlog.Printf("unable to find a Client to add the protocol.Server to")
433 }
434
435 func getMemory(_ *http.Request) any {
436 var m runtime.MemStats
437 runtime.ReadMemStats(&m)
438 return m
439 }
440
441 func init() {
442 event.SetExporter(makeGlobalExporter(os.Stderr))
443 }
444
445 func GetInstance(ctx context.Context) *Instance {
446 if ctx == nil {
447 return nil
448 }
449 v := ctx.Value(instanceKey)
450 if v == nil {
451 return nil
452 }
453 return v.(*Instance)
454 }
455
456 // WithInstance creates debug instance ready for use using the supplied
457 // configuration and stores it in the returned context.
458 func WithInstance(ctx context.Context, otelEndpoint string) context.Context {
459 i := &Instance{
460 StartTime: time.Now(),
461 }
462 i.LogWriter = os.Stderr
463 i.prometheus = prometheus.New()
464 i.rpcs = &Rpcs{}
465 i.traces = &traces{}
466 i.State = &State{}
467 if otelEndpoint != "" {
468 i.otel = otel.NewExporter(ctx,
469 otel.WithEndpoint(otelEndpoint),
470 otel.WithServiceName("gopls"),
471 otel.WithServiceVersion(versionpkg.Version()))
472 }
473 i.exporter = makeInstanceExporter(i)
474 return context.WithValue(ctx, instanceKey, i)
475 }
476
477 // SetLogFile sets the logfile for use with this instance.
478 func (i *Instance) SetLogFile(logfile string, isDaemon bool) (func(), error) {
479 // TODO: probably a better solution for deferring closure to the caller would
480 // be for the debug instance to itself be closed, but this fixes the
481 // immediate bug of logs not being captured.
482 closeLog := func() {}
483 if logfile != "" {
484 if logfile == "auto" {
485 if isDaemon {
486 logfile = filepath.Join(os.TempDir(), fmt.Sprintf("gopls-daemon-%d.log", os.Getpid()))
487 } else {
488 logfile = filepath.Join(os.TempDir(), fmt.Sprintf("gopls-%d.log", os.Getpid()))
489 }
490 }
491 f, err := os.Create(logfile)
492 if err != nil {
493 return nil, fmt.Errorf("unable to create log file: %w", err)
494 }
495 closeLog = func() {
496 defer f.Close()
497 }
498 stdlog.SetOutput(io.MultiWriter(os.Stderr, f))
499 i.LogWriter = f
500 }
501 i.Logfile = logfile
502 return closeLog, nil
503 }
504
505 // Serve starts and runs a debug server in the background on the given addr.
506 // It also logs the port the server starts on, to allow for :0 auto assigned
507 // ports.
508 func (i *Instance) Serve(ctx context.Context, addr string) (string, error) {
509 stdlog.SetFlags(stdlog.Lshortfile)
510 if addr == "" {
511 return "", nil
512 }
513 i.serveMu.Lock()
514 defer i.serveMu.Unlock()
515
516 if i.listenedDebugAddress != "" {
517 // Already serving. Return the bound address.
518 return i.listenedDebugAddress, nil
519 }
520
521 i.debugAddress = addr
522 listener, err := net.Listen("tcp", i.debugAddress)
523 if err != nil {
524 return "", err
525 }
526 i.listenedDebugAddress = listener.Addr().String()
527
528 port := listener.Addr().(*net.TCPAddr).Port
529 if strings.HasSuffix(i.debugAddress, ":0") {
530 stdlog.Printf("debug server listening at http://localhost:%d", port)
531 }
532 event.Log(ctx, "Debug serving", label1.Port.Of(port))
533 go func() {
534 mux := http.NewServeMux()
535 mux.HandleFunc("/", render(MainTmpl, func(*http.Request) any { return i }))
536 mux.HandleFunc("/debug/", render(DebugTmpl, nil))
537 mux.HandleFunc("/debug/pprof/", pprof.Index)
538 mux.HandleFunc("/debug/pprof/cmdline", cmdline)
539 mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
540 mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
541 mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
542
543 if h, err := startFlightRecorder(); err != nil {
544 stdlog.Printf("failed to start flight recorder: %v", err) // e.g. go1.24
545 } else {
546 mux.HandleFunc("/flightrecorder", h)
547 }
548
549 if i.prometheus != nil {
550 mux.HandleFunc("/metrics/", i.prometheus.Serve)
551 }
552 if i.rpcs != nil {
553 mux.HandleFunc("/rpc/", render(RPCTmpl, i.rpcs.getData))
554 }
555 if i.traces != nil {
556 mux.HandleFunc("/trace/", render(TraceTmpl, i.traces.getData))
557 }
558 mux.HandleFunc("/analysis/", render(AnalysisTmpl, i.getAnalysis))
559 mux.HandleFunc("/cache/", render(CacheTmpl, i.getCache))
560 mux.HandleFunc("/session/", render(SessionTmpl, i.getSession))
561 mux.HandleFunc("/client/", render(ClientTmpl, i.getClient))
562 mux.HandleFunc("/server/", render(ServerTmpl, i.getServer))
563 mux.HandleFunc("/file/{session}/{identifier}", render(FileTmpl, i.getFile))
564 mux.HandleFunc("/metadata/{session}/{view}/", render(MetadataTmpl, i.getMetadata))
565 mux.HandleFunc("/package/{session}/{view}/{id...}", render(PackageTmpl, i.getPackage))
566 mux.HandleFunc("/info", render(InfoTmpl, i.getInfo))
567 mux.HandleFunc("/memory", render(MemoryTmpl, getMemory))
568
569 // Internal debugging helpers.
570 mux.HandleFunc("/gc", func(w http.ResponseWriter, r *http.Request) {
571 runtime.GC()
572 runtime.GC()
573 runtime.GC()
574 http.Redirect(w, r, "/memory", http.StatusTemporaryRedirect)
575 })
576 mux.HandleFunc("/_makeabug", func(w http.ResponseWriter, r *http.Request) {
577 bug.Report("bug here")
578 http.Error(w, "made a bug", http.StatusOK)
579 })
580
581 err := http.Serve(listener, mux) // always non-nil
582 event.Error(ctx, "Debug server failed", err)
583 }()
584 return i.listenedDebugAddress, nil
585 }
586
587 func (i *Instance) DebugAddress() string {
588 i.serveMu.Lock()
589 defer i.serveMu.Unlock()
590 return i.debugAddress
591 }
592
593 func (i *Instance) ListenedDebugAddress() string {
594 i.serveMu.Lock()
595 defer i.serveMu.Unlock()
596 return i.listenedDebugAddress
597 }
598
599 func makeGlobalExporter(stderr io.Writer) event.Exporter {
600 var (
601 pMu sync.Mutex
602 p export.Printer
603 )
604 return func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
605 i := GetInstance(ctx)
606
607 if event.IsLog(ev) {
608 // Don't log context cancellation errors.
609 if err := keys.Err.Get(ev); errors.Is(err, context.Canceled) {
610 return ctx
611 }
612 // Make sure any log messages without an instance go to stderr.
613 if i == nil {
614 pMu.Lock()
615 p.WriteEvent(stderr, ev, lm)
616 pMu.Unlock()
617 }
618 level := log.LabeledLevel(lm)
619 // Exclude trace logs from LSP logs.
620 if level < log.Trace {
621 ctx = protocol.LogEvent(ctx, ev, lm, messageType(level))
622 }
623 }
624 if i == nil {
625 return ctx
626 }
627 return i.exporter(ctx, ev, lm)
628 }
629 }
630
631 func messageType(l log.Level) protocol.MessageType {
632 switch l {
633 case log.Error:
634 return protocol.Error
635 case log.Warning:
636 return protocol.Warning
637 case log.Debug:
638 return protocol.Log
639 }
640 return protocol.Info
641 }
642
643 func makeInstanceExporter(i *Instance) event.Exporter {
644 exporter := func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
645 if i.prometheus != nil {
646 ctx = i.prometheus.ProcessEvent(ctx, ev, lm)
647 }
648 if i.rpcs != nil {
649 ctx = i.rpcs.ProcessEvent(ctx, ev, lm)
650 }
651 if i.traces != nil {
652 ctx = i.traces.ProcessEvent(ctx, ev, lm)
653 }
654 if i.otel != nil {
655 ctx = i.otel.ProcessEvent(ctx, ev, lm)
656 }
657 if event.IsLog(ev) {
658 if s := cache.KeyCreateSession.Get(ev); s != nil {
659 i.State.addClient(s)
660 }
661 if sid := label1.NewServer.Get(ev); sid != "" {
662 i.State.updateServer(&Server{
663 ID: sid,
664 Logfile: label1.Logfile.Get(ev),
665 DebugAddress: label1.DebugAddress.Get(ev),
666 GoplsPath: label1.GoplsPath.Get(ev),
667 ClientID: label1.ClientID.Get(ev),
668 })
669 }
670 if s := cache.KeyShutdownSession.Get(ev); s != nil {
671 i.State.dropClient(s)
672 }
673 if sid := label1.EndServer.Get(ev); sid != "" {
674 i.State.dropServer(sid)
675 }
676 if s := cache.KeyUpdateSession.Get(ev); s != nil {
677 if c := i.State.Client(s.ID()); c != nil {
678 c.DebugAddress = label1.DebugAddress.Get(ev)
679 c.Logfile = label1.Logfile.Get(ev)
680 c.ServerID = label1.ServerID.Get(ev)
681 c.GoplsPath = label1.GoplsPath.Get(ev)
682 }
683 }
684 }
685 return ctx
686 }
687 // StdTrace must be above export.Spans below (by convention, export
688 // middleware applies its wrapped exporter last).
689 exporter = StdTrace(exporter)
690 metrics := metric.Config{}
691 registerMetrics(&metrics)
692 exporter = metrics.Exporter(exporter)
693 exporter = export.Spans(exporter)
694 exporter = export.Labels(exporter)
695 return exporter
696 }
697
698 type dataFunc func(*http.Request) any
699
700 func render(tmpl *template.Template, fun dataFunc) func(http.ResponseWriter, *http.Request) {
701 return func(w http.ResponseWriter, r *http.Request) {
702 var data any
703 if fun != nil {
704 data = fun(r)
705 }
706 if err := tmpl.Execute(w, data); err != nil {
707 event.Error(context.Background(), "", err)
708 http.Error(w, err.Error(), http.StatusInternalServerError)
709 }
710 }
711 }
712
713 func commas(s string) string {
714 for i := len(s); i > 3; {
715 i -= 3
716 s = s[:i] + "," + s[i:]
717 }
718 return s
719 }
720
721 func fuint64(v uint64) string {
722 return commas(strconv.FormatUint(v, 10))
723 }
724
725 func fuint32(v uint32) string {
726 return commas(strconv.FormatUint(uint64(v), 10))
727 }
728
729 func fcontent(v []byte) string {
730 return string(v)
731 }
732
733 var BaseTemplate = template.Must(template.New("").Parse(`
734 <html>
735 <head>
736 <title>{{template "title" .}}</title>
737 <style>
738 .profile-name{
739 display:inline-block;
740 width:6rem;
741 }
742 td.value {
743 text-align: right;
744 }
745 ul.spans {
746 font-family: monospace;
747 font-size: 85%;
748 }
749 body {
750 font-family: sans-serif;
751 font-size: 1rem;
752 line-height: normal;
753 }
754 </style>
755 {{block "head" .}}{{end}}
756 </head>
757 <body>
758 <a href="/">Main</a>
759 <a href="/info">Info</a>
760 <a href="/memory">Memory</a>
761 <a href="/debug/pprof">Profiling</a>
762 <a href="/metrics">Metrics</a>
763 <a href="/rpc">RPC</a>
764 <a href="/trace">Trace</a>
765 <a href="/flightrecorder">Flight recorder</a>
766 <a href="/analysis">Analysis</a>
767 <hr>
768 <h1>{{template "title" .}}</h1>
769 {{block "body" .}}
770 Unknown page
771 {{end}}
772 </body>
773 </html>
774
775 {{define "cachelink"}}<a href="/cache/{{.}}">Cache {{.}}</a>{{end}}
776 {{define "clientlink"}}<a href="/client/{{.}}">Client {{.}}</a>{{end}}
777 {{define "serverlink"}}<a href="/server/{{.}}">Server {{.}}</a>{{end}}
778 {{define "sessionlink"}}<a href="/session/{{.}}">Session {{.}}</a>{{end}}
779 `)).Funcs(template.FuncMap{
780 "fuint64": fuint64,
781 "fuint32": fuint32,
782 "fcontent": fcontent,
783 "localAddress": func(s string) string {
784 // Try to translate loopback addresses to localhost, both for cosmetics and
785 // because unspecified ipv6 addresses can break links on Windows.
786 //
787 // TODO(rfindley): In the future, it would be better not to assume the
788 // server is running on localhost, and instead construct this address using
789 // the remote host.
790 host, port, err := net.SplitHostPort(s)
791 if err != nil {
792 return s
793 }
794 ip := net.ParseIP(host)
795 if ip == nil {
796 return s
797 }
798 if ip.IsLoopback() || ip.IsUnspecified() {
799 return "localhost:" + port
800 }
801 return s
802 },
803 // TODO(rfindley): re-enable option inspection.
804 // "options": func(s *cache.Session) []sessionOption {
805 // return showOptions(s.Options())
806 // },
807 })
808
809 var MainTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
810 {{define "title"}}Gopls server information{{end}}
811 {{define "body"}}
812 <h2>Caches</h2>
813 <ul>{{range .State.Caches}}<li>{{template "cachelink" .ID}}</li>{{end}}</ul>
814 <h2>Sessions</h2>
815 <ul>{{range .State.Sessions}}<li>{{template "sessionlink" .ID}} from {{template "cachelink" .Cache.ID}}</li>{{end}}</ul>
816 <h2>Clients</h2>
817 <ul>{{range .State.Clients}}<li>{{template "clientlink" .Session.ID}}</li>{{end}}</ul>
818 <h2>Servers</h2>
819 <ul>{{range .State.Servers}}<li>{{template "serverlink" .ID}}</li>{{end}}</ul>
820 <h2>Bug reports</h2>
821 <dl>{{range .State.Bugs}}<dt>{{.Key}}</dt><dd>{{.Description}}</dd>{{end}}</dl>
822 {{end}}
823 `))
824
825 var InfoTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
826 {{define "title"}}Gopls version information{{end}}
827 {{define "body"}}
828 {{.}}
829 {{end}}
830 `))
831
832 var MemoryTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
833 {{define "title"}}Gopls memory usage{{end}}
834 {{define "head"}}<meta http-equiv="refresh" content="5">{{end}}
835 {{define "body"}}
836 <form action="/gc"><input type="submit" value="Run garbage collector"/></form>
837 <h2>Stats</h2>
838 <table>
839 <tr><td class="label">Allocated bytes</td><td class="value">{{fuint64 .HeapAlloc}}</td></tr>
840 <tr><td class="label">Total allocated bytes</td><td class="value">{{fuint64 .TotalAlloc}}</td></tr>
841 <tr><td class="label">System bytes</td><td class="value">{{fuint64 .Sys}}</td></tr>
842 <tr><td class="label">Heap system bytes</td><td class="value">{{fuint64 .HeapSys}}</td></tr>
843 <tr><td class="label">Malloc calls</td><td class="value">{{fuint64 .Mallocs}}</td></tr>
844 <tr><td class="label">Frees</td><td class="value">{{fuint64 .Frees}}</td></tr>
845 <tr><td class="label">Idle heap bytes</td><td class="value">{{fuint64 .HeapIdle}}</td></tr>
846 <tr><td class="label">In use bytes</td><td class="value">{{fuint64 .HeapInuse}}</td></tr>
847 <tr><td class="label">Released to system bytes</td><td class="value">{{fuint64 .HeapReleased}}</td></tr>
848 <tr><td class="label">Heap object count</td><td class="value">{{fuint64 .HeapObjects}}</td></tr>
849 <tr><td class="label">Stack in use bytes</td><td class="value">{{fuint64 .StackInuse}}</td></tr>
850 <tr><td class="label">Stack from system bytes</td><td class="value">{{fuint64 .StackSys}}</td></tr>
851 <tr><td class="label">Bucket hash bytes</td><td class="value">{{fuint64 .BuckHashSys}}</td></tr>
852 <tr><td class="label">GC metadata bytes</td><td class="value">{{fuint64 .GCSys}}</td></tr>
853 <tr><td class="label">Off heap bytes</td><td class="value">{{fuint64 .OtherSys}}</td></tr>
854 </table>
855 <h2>By size</h2>
856 <table>
857 <tr><th>Size</th><th>Mallocs</th><th>Frees</th></tr>
858 {{range .BySize}}<tr><td class="value">{{fuint32 .Size}}</td><td class="value">{{fuint64 .Mallocs}}</td><td class="value">{{fuint64 .Frees}}</td></tr>{{end}}
859 </table>
860 {{end}}
861 `))
862
863 var DebugTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
864 {{define "title"}}GoPls Debug pages{{end}}
865 {{define "body"}}
866 <a href="/debug/pprof">Profiling</a>
867 {{end}}
868 `))
869
870 var CacheTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
871 {{define "title"}}Cache {{.ID}}{{end}}
872 {{define "body"}}
873 <h2>memoize.Store entries</h2>
874 <ul>{{range $k,$v := .MemStats}}<li>{{$k}} - {{$v}}</li>{{end}}</ul>
875 <h2>File stats</h2>
876 <p>
877 {{- $stats := .FileStats -}}
878 Total: <b>{{$stats.Total}}</b><br>
879 Largest: <b>{{$stats.Largest}}</b><br>
880 Errors: <b>{{$stats.Errs}}</b><br>
881 </p>
882 {{end}}
883 `))
884
885 var AnalysisTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
886 {{define "title"}}Analysis{{end}}
887 {{define "body"}}
888 <h2>Analyzer.Run times</h2>
889 <ul>{{range .AnalyzerRunTimes}}<li>{{.Duration}} {{.Label}}</li>{{end}}</ul>
890 {{end}}
891 `))
892
893 var ClientTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
894 {{define "title"}}Client {{.Session.ID}}{{end}}
895 {{define "body"}}
896 Using session: <b>{{template "sessionlink" .Session.ID}}</b><br>
897 {{if .DebugAddress}}Debug this client at: <a href="http://{{localAddress .DebugAddress}}">{{localAddress .DebugAddress}}</a><br>{{end}}
898 Logfile: {{.Logfile}}<br>
899 Gopls Path: {{.GoplsPath}}<br>
900 {{end}}
901 `))
902
903 var ServerTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
904 {{define "title"}}Server {{.ID}}{{end}}
905 {{define "body"}}
906 {{if .DebugAddress}}Debug this server at: <a href="http://{{localAddress .DebugAddress}}">{{localAddress .DebugAddress}}</a><br>{{end}}
907 Logfile: {{.Logfile}}<br>
908 Gopls Path: {{.GoplsPath}}<br>
909 {{end}}
910 `))
911
912 var SessionTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
913 {{define "title"}}Session {{.ID}}{{end}}
914 {{define "body"}}
915 From: <b>{{template "cachelink" .Cache.ID}}</b><br>
916 {{- $session := . -}}
917
918 <h2>Views</h2>
919 <ul>{{range .Views}}
920 {{- $envOverlay := .EnvOverlay -}}
921 <li>ID: <b>{{.ID}}</b><br>
922 Type: <b>{{.Type}}</b><br>
923 Root: <b>{{.Root}}</b><br>
924 {{- if $envOverlay}}
925 Env overlay: <b>{{$envOverlay}})</b><br>
926 {{end -}}
927 Folder.Name: <b>{{.Folder.Name}}</b><br>
928 Folder.Dir: <b>{{.Folder.Dir}}</b><br/>
929 <a href="/metadata/{{$session.ID}}/{{.ID}}">Latest metadata</a><br/>
930
931 Settings:<br/>
932 <ul>
933 {{range .Folder.Options.Debug}}<li>{{.}}</li>
934 {{end}}
935 </ul>
936 {{end}}</ul>
937
938 <h2>Overlays</h2>
939 {{$session := .}}
940 <ul>{{range .Overlays}}
941 <li>
942 <a href="/file/{{$session.ID}}/{{.Identity.Hash}}">{{.Identity.URI}}</a>
943 </li>{{end}}</ul>
944 {{end}}
945 `))
946
947 // For /file endpoint; operand is [FileWithKind].
948 var FileTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
949 {{define "title"}}Overlay {{.Identity.Hash}}{{end}}
950 {{define "body"}}
951 {{with .}}
952 URI: <b>{{.URI}}</b><br>
953 Identifier: <b>{{.Identity.Hash}}</b><br>
954 Version: <b>{{.Version}}</b><br>
955 Kind: <b>{{.Kind}}</b><br>
956 {{end}}
957 <h3>Contents</h3>
958 <pre>{{fcontent .Content}}</pre>
959 {{end}}
960 `))
961
962 // For /metadata endpoint; operand is [*MetadataInfo].
963 var MetadataTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
964 {{define "title"}}Metadata graph{{end}}
965 {{define "body"}}
966
967 <p><a href='#hdr-Files'>↓ Index by file</a></p>
968
969 <h3>Packages ({{len .Graph.Packages}})</h3>
970 <ul>
971 {{range $id, $pkg := .Graph.Packages}}
972 <li id='{{$id}}'><b>{{$id}}</b>
973 {{with $pkg}}
974 <ul>
975 <li>Name: {{.Name}}</li>
976 <li>PkgPath: {{printf "%q" .PkgPath}}</li>
977 {{if .Module}}<li>Module: {{printf "%#v" .Module}}</li>{{end}}
978 <li><a href="/package/{{$.SessionID}}/{{$.ViewID}}/{{$id}}">Type information</a></li>
979 {{if .ForTest}}<li>ForTest: {{.ForTest}}</li>{{end}}
980 {{if .Standalone}}<li>Standalone</li>{{end}}
981 {{if .Errors}}<li>Errors: {{.Errors}}</li>{{end}}
982 {{if .DepsErrors}}<li>DepsErrors: {{.DepsErrors}}</li>{{end}}
983 <li>LoadDir: {{.LoadDir}}</li>
984 <li>DepsByImpPath
985 <ul>
986 {{range $path, $id := .DepsByImpPath}}
987 <li>{{if $id}}<a href='#{{$id}}'>{{printf "%q" $path}}</a>{{else}}⚠️ {{printf "%q" $path}} missing{{end}}</li>
988 {{end}}
989 </ul>
990 </li>
991 {{if .GoFiles}}<li>GoFiles: <ul>{{range .GoFiles}}<li>{{.}}</li>{{end}}</ul></li>{{end}}
992 {{if .CompiledGoFiles}}<li>CompiledGoFiles: <ul>{{range .CompiledGoFiles}}<li>{{.}}</li>{{end}}</ul></li>{{end}}
993 {{if .IgnoredFiles}}<li>IgnoredFiles: <ul>{{range .IgnoredFiles}}<li>{{.}}</li>{{end}}</ul></li>{{end}}
994 {{if .OtherFiles}}<li>OtherFiles: <ul>{{range .OtherFiles}}<li>{{.}}</li>{{end}}</ul></li>{{end}}
995 <!-- skip DepsByPkgPath, ImportedBy (redundant indexes) -->
996 </ul>
997 {{end}}
998 </li>
999 {{end}}
1000 </ul>
1001
1002 <h3 id='hdr-Files'>Files</h3>
1003 <ul>
1004 {{range $uri, $pkgs := .Graph.ForFile}}<li>{{$uri}} →{{range $pkgs}} <a href='#{{.ID}}'>{{.ID}}</a>{{end}}</li>{{end}}
1005 </ul>
1006
1007 {{end}}
1008 `))
1009
1010 // For /package endpoint; operand is [*PackageInfo].
1011 var PackageTmpl = template.Must(template.Must(BaseTemplate.Clone()).Parse(`
1012 {{define "title"}}Package {{.Package.Metadata.ID}}{{end}}
1013 {{define "body"}}
1014
1015 <ul>
1016 <li><a href="/metadata/{{.SessionID}}/{{.ViewID}}#{{.Package.Metadata.ID}}">Metadata</a></li>
1017 </ul>
1018
1019 <h2>Diagnostics for syntax and type (but not analysis) errors</h2>
1020 <ul>
1021 {{range $url, $diags := .Diagnostics}}
1022 <li>{{$url}}
1023 <ul>
1024 {{range $diag := $diags}}
1025 <li>{{$diag.Range}}: [{{$diag.Severity}}] {{$diag.Message}}<br/>
1026 <ul>
1027 <li>code {{$diag.Code}}</li>
1028 <li>code href {{$diag.CodeHref}}</li>
1029 <li>source {{$diag.Source}}</li>
1030 <li>tags {{$diag.Tags}}</li>
1031 <li>related {{$diag.Related}}</li> {{/*TODO: improve*/}}
1032 <li>bundled fixes {{$diag.BundledFixes}}</li> {{/*TODO: improve*/}}
1033 <li>fixes {{$diag.SuggestedFixes}}</li> {{/*TODO: improve*/}}
1034 </ul>
1035 {{end}}
1036 </ul>
1037 {{end}}
1038 </ul>
1039
1040 {{end}}
1041 {{/*
1042 TODO:
1043 - link to godoc (tricky: in server package)
1044 - show Object inventory of types.Package.Scope
1045 - show index info (xrefs, methodsets, tests)
1046 - call DiagnoseFile on each file?
1047 */}}
1048 `))