Debian Codegraph @

zpages/tracez.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Copyright 2017, OpenCensus Authors
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17
18 package zpages // import "go.opentelemetry.io/contrib/zpages"
19
20 import (
21 "fmt"
22 "log"
23 "net/http"
24 "sort"
25 "strconv"
26 "strings"
27 "time"
28
29 "go.opentelemetry.io/otel/attribute"
30 sdktrace "go.opentelemetry.io/otel/sdk/trace"
31 "go.opentelemetry.io/otel/trace"
32 )
33
34 const (
35 // spanNameQueryField is the header for span name.
36 spanNameQueryField = "zspanname"
37 // spanTypeQueryField is the header for type (running = 0, latency = 1, error = 2) to display.
38 spanTypeQueryField = "ztype"
39 // spanLatencyBucketQueryField is the header for latency based samples.
40 // Default is [0, 8] representing the latency buckets, where 0 is the first one.
41 spanLatencyBucketQueryField = "zlatencybucket"
42 // maxTraceMessageLength is the maximum length of a message in tracez output.
43 maxTraceMessageLength = 1024
44
45 maxRequestBodySize = 1 << 20 // 1MB
46 )
47
48 type summaryTableData struct {
49 Header []string
50 LatencyBucketNames []string
51 Links bool
52 TracesEndpoint string
53 Rows []summaryTableRowData
54 }
55
56 type summaryTableRowData struct {
57 Name string
58 Active int
59 Latency []int
60 Errors int
61 }
62
63 // traceTableData contains data for the trace data template.
64 type traceTableData struct {
65 Name string
66 Num int
67 Rows []spanRow
68 }
69
70 var _ http.Handler = (*tracezHandler)(nil)
71
72 type tracezHandler struct {
73 sp *SpanProcessor
74 }
75
76 // NewTracezHandler returns an http.Handler that can be used to serve HTTP requests for trace zpages.
77 func NewTracezHandler(sp *SpanProcessor) http.Handler {
78 return &tracezHandler{sp: sp}
79 }
80
81 // ServeHTTP implements the http.Handler and is capable of serving "tracez" HTTP requests.
82 func (th *tracezHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
83 w.Header().Set("Content-Type", "text/html; charset=utf-8")
84
85 r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
86 if err := r.ParseForm(); err != nil {
87 w.WriteHeader(http.StatusBadRequest)
88 return
89 }
90 spanName := r.Form.Get(spanNameQueryField)
91 spanType, _ := strconv.Atoi(r.Form.Get(spanTypeQueryField))
92 spanSubtype, _ := strconv.Atoi(r.Form.Get(spanLatencyBucketQueryField))
93
94 if err := headerTemplate.Execute(w, headerData{Title: "Trace Spans"}); err != nil {
95 log.Printf("zpages: executing template: %v", err)
96 }
97 if err := summaryTableTemplate.Execute(w, th.getSummaryTableData()); err != nil {
98 log.Printf("zpages: executing template: %v", err)
99 }
100 if spanName != "" {
101 if err := tracesTableTemplate.Execute(w, th.getTraceTableData(spanName, spanType, spanSubtype)); err != nil {
102 log.Printf("zpages: executing template: %v", err)
103 }
104 }
105 if err := footerTemplate.Execute(w, nil); err != nil {
106 log.Printf("zpages: executing template: %v", err)
107 }
108 }
109
110 func (th *tracezHandler) getTraceTableData(spanName string, spanType, latencyBucket int) traceTableData {
111 var spans []sdktrace.ReadOnlySpan
112 switch spanType {
113 case 0: // active
114 spans = th.sp.activeSpans(spanName)
115 case 1: // latency
116 spans = th.sp.spansByLatency(spanName, latencyBucket)
117 case 2: // error
118 spans = th.sp.errorSpans(spanName)
119 }
120
121 data := traceTableData{
122 Name: spanName,
123 Num: len(spans),
124 }
125 for _, s := range spans {
126 data.Rows = append(data.Rows, spanRows(s)...)
127 }
128 return data
129 }
130
131 func (th *tracezHandler) getSummaryTableData() summaryTableData {
132 data := summaryTableData{
133 Links: true,
134 TracesEndpoint: "tracez",
135 }
136 data.Header = []string{"Name", "active"}
137 // An implicit 0 lower bound latency bucket is always present.
138 latencyBuckets := append([]time.Duration{0}, defaultBoundaries.durations...)
139 for _, l := range latencyBuckets {
140 s := fmt.Sprintf(">%v", l)
141 data.Header = append(data.Header, s)
142 data.LatencyBucketNames = append(data.LatencyBucketNames, s)
143 }
144 data.Header = append(data.Header, "Errors")
145 for name, s := range th.sp.spansPerMethod() {
146 row := summaryTableRowData{Name: name, Active: s.activeSpans, Errors: s.errorSpans, Latency: s.latencySpans}
147 data.Rows = append(data.Rows, row)
148 }
149 sort.Slice(data.Rows, func(i, j int) bool {
150 return data.Rows[i].Name < data.Rows[j].Name
151 })
152 return data
153 }
154
155 type spanRow struct {
156 Fields [3]string
157 trace.SpanContext
158 ParentSpanContext trace.SpanContext
159 }
160
161 type events []sdktrace.Event
162
163 func (e events) Len() int { return len(e) }
164 func (e events) Less(i, j int) bool {
165 return e[i].Time.Before(e[j].Time)
166 }
167 func (e events) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
168
169 type attributes []attribute.KeyValue
170
171 func (e attributes) Len() int { return len(e) }
172 func (e attributes) Less(i, j int) bool {
173 return string(e[i].Key) < string(e[j].Key)
174 }
175 func (e attributes) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
176
177 func spanRows(s sdktrace.ReadOnlySpan) []spanRow {
178 start := s.StartTime()
179
180 lasty, lastm, lastd := start.Date()
181 wholeTime := func(t time.Time) string {
182 return t.Format("2006/01/02-15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
183 }
184 formatTime := func(t time.Time) string {
185 y, m, d := t.Date()
186 if y == lasty && m == lastm && d == lastd {
187 return t.Format(" 15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
188 }
189 lasty, lastm, lastd = y, m, d
190 return wholeTime(t)
191 }
192
193 lastTime := start
194 formatElapsed := func(t time.Time) string {
195 d := t.Sub(lastTime)
196 lastTime = t
197 u := int64(d / 1000)
198 // There are five cases for duration printing:
199 // -1234567890s
200 // -1234.123456
201 // .123456
202 // 12345.123456
203 // 12345678901s
204 switch {
205 case u < -9999999999:
206 return fmt.Sprintf("%11ds", u/1e6)
207 case u < 0:
208 sec := u / 1e6
209 u -= sec * 1e6
210 return fmt.Sprintf("%5d.%06d", sec, -u)
211 case u < 1e6:
212 return fmt.Sprintf(" .%6d", u)
213 case u <= 99999999999:
214 sec := u / 1e6
215 u -= sec * 1e6
216 return fmt.Sprintf("%5d.%06d", sec, u)
217 default:
218 return fmt.Sprintf("%11ds", u/1e6)
219 }
220 }
221
222 firstRow := spanRow{Fields: [3]string{wholeTime(start), "", ""}, SpanContext: s.SpanContext(), ParentSpanContext: s.Parent()}
223 if s.EndTime().IsZero() {
224 firstRow.Fields[1] = " "
225 } else {
226 firstRow.Fields[1] = formatElapsed(s.EndTime())
227 lastTime = start
228 }
229 out := []spanRow{firstRow}
230
231 formatAttributes := func(a attributes) string {
232 sort.Sort(a)
233 var s []string
234 for i := range a {
235 s = append(s, fmt.Sprintf("%s=%v", a[i].Key, a[i].Value.Emit()))
236 }
237 return "Attributes:{" + strings.Join(s, ", ") + "}"
238 }
239
240 msg := fmt.Sprintf("Status{Code=%s, description=%q}", s.Status().Code.String(), s.Status().Description)
241 out = append(out, spanRow{Fields: [3]string{"", "", msg}})
242
243 if len(s.Attributes()) != 0 {
244 out = append(out, spanRow{Fields: [3]string{"", "", formatAttributes(s.Attributes())}})
245 }
246
247 es := events(s.Events())
248 sort.Sort(es)
249 for _, e := range es {
250 msg := e.Name
251 if len(e.Attributes) != 0 {
252 msg = msg + " " + formatAttributes(e.Attributes)
253 }
254 row := spanRow{Fields: [3]string{
255 formatTime(e.Time),
256 formatElapsed(e.Time),
257 msg,
258 }}
259 out = append(out, row)
260 }
261 for i := range out {
262 if len(out[i].Fields[2]) > maxTraceMessageLength {
263 out[i].Fields[2] = out[i].Fields[2][:maxTraceMessageLength]
264 }
265 }
266 return out
267 }