/
trace.go
327 lines (272 loc) 路 8.92 KB
/
trace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmdutil
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/url"
"os"
"runtime"
"strings"
"time"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
jaeger "github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/transport/zipkin"
"sourcegraph.com/sourcegraph/appdash"
appdash_opentracing "sourcegraph.com/sourcegraph/appdash/opentracing"
)
// TracingEndpoint is the Zipkin-compatible tracing endpoint where tracing data will be sent.
var TracingEndpoint string
// Deprecated. TracingToFile=true if pulumi was called with a file://
// scheme URL (--tracing=file:///...). Even in this case
// TracingEndpoint will now have the tcp:// scheme and will point to a
// proxy server that will append traces to the user-specified file.
// Plugins should respect TracingEndpoint and ignore TracingToFile.
var TracingToFile bool
var TracingRootSpan opentracing.Span
var traceCloser io.Closer
type localStore struct {
path string
store *appdash.MemoryStore
}
func (s *localStore) Close() error {
f, err := os.Create(s.path)
if err != nil {
return err
}
defer contract.IgnoreClose(f)
return s.store.Write(f)
}
func IsTracingEnabled() bool {
return TracingEndpoint != ""
}
// InitTracing initializes tracing
func InitTracing(name, rootSpanName, tracingEndpoint string) {
// If no tracing endpoint was provided, just return. The default global tracer is already a no-op tracer.
if tracingEndpoint == "" {
return
}
endpointURL, err := url.Parse(tracingEndpoint)
if err != nil {
log.Fatalf("invalid tracing endpoint: %v", err)
}
var tracer opentracing.Tracer
switch {
case endpointURL.Scheme == "file":
// If the endpoint is a file:// URL, use a local tracer.
TracingToFile = true
path := endpointURL.Path
if path == "" {
path = endpointURL.Opaque
}
if path == "" {
log.Fatalf("invalid tracing endpoint: %v", err)
}
store := &localStore{
path: path,
store: appdash.NewMemoryStore(),
}
traceCloser = store
collector := appdash.NewLocalCollector(store.store)
tracer = appdash_opentracing.NewTracer(collector)
proxyEndpoint, err := startProxyAppDashServer(collector)
if err != nil {
log.Fatal(err)
}
// Instead of storing the original endpoint, store the
// proxy endpoint. The TracingEndpoint global var is
// consumed by code forking off sub-processes, and we
// want those sending data to the proxy endpoint, so
// it cleanly lands in the file managed by the parent
// process.
TracingEndpoint = proxyEndpoint
case endpointURL.Scheme == "tcp":
// Store the tracing endpoint
TracingEndpoint = tracingEndpoint
// If the endpoint scheme is tcp, use an Appdash endpoint.
collector := appdash.NewRemoteCollector(endpointURL.Host)
traceCloser = collector
tracer = appdash_opentracing.NewTracer(collector)
default:
// Store the tracing endpoint
TracingEndpoint = tracingEndpoint
// Jaeger tracer can be initialized with a transport that will
// report tracing Spans to a Zipkin backend
transport, err := zipkin.NewHTTPTransport(
tracingEndpoint,
zipkin.HTTPBatchSize(1),
zipkin.HTTPLogger(jaeger.StdLogger),
)
if err != nil {
log.Fatalf("Cannot initialize HTTP transport: %v", err)
}
// create Jaeger tracer
t, closer := jaeger.NewTracer(
name,
jaeger.NewConstSampler(true), // sample all traces
jaeger.NewRemoteReporter(transport))
tracer, traceCloser = t, closer
}
// Set the ambient tracer
opentracing.SetGlobalTracer(tracer)
// If a root span was requested, start it now.
if rootSpanName != "" {
var options []opentracing.StartSpanOption
for _, tag := range rootSpanTags() {
options = append(options, tag)
}
TracingRootSpan = tracer.StartSpan(rootSpanName, options...)
go collectMemStats(rootSpanName)
}
}
// CloseTracing ensures that all pending spans have been flushed. It should be called before process exit.
func CloseTracing() {
if !IsTracingEnabled() {
return
}
if TracingRootSpan != nil {
TracingRootSpan.Finish()
}
contract.IgnoreClose(traceCloser)
}
// Starts an AppDash server listening on any available TCP port
// locally and sends the spans and annotations to the given collector.
// Returns a Pulumi-formatted tracing endpoint pointing to this
// server.
//
// See https://github.com/sourcegraph/appdash/blob/master/cmd/appdash/example_app.go
func startProxyAppDashServer(collector appdash.Collector) (string, error) {
l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0})
if err != nil {
return "", err
}
collectorPort := l.Addr().(*net.TCPAddr).Port
cs := appdash.NewServer(l, collector)
cs.Debug = true
cs.Trace = true
go cs.Start()
// The default sends to stderr, which is unfortunate for
// end-users. Discard for now.
cs.Log = log.New(ioutil.Discard, "appdash", 0)
return fmt.Sprintf("tcp://127.0.0.1:%d", collectorPort), nil
}
// Computes initial tags to write to the `TracingRootSpan`, which can
// be useful for aggregating trace data in benchmarks.
func rootSpanTags() []opentracing.Tag {
tags := []opentracing.Tag{
{
Key: "os.Args",
Value: os.Args,
},
{
Key: "runtime.GOOS",
Value: runtime.GOOS,
},
{
Key: "runtime.GOARCH",
Value: runtime.GOARCH,
},
{
Key: "runtime.NumCPU",
Value: runtime.NumCPU(),
},
}
// Promote all env vars `pulumi_tracing_tag_foo=bar` into tags `foo: bar`.
envPrefix := "pulumi_tracing_tag_"
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
envVarName := strings.ToLower(pair[0])
envVarValue := pair[1]
if strings.HasPrefix(envVarName, envPrefix) {
tags = append(tags, opentracing.Tag{
Key: strings.TrimPrefix(envVarName, envPrefix),
Value: envVarValue,
})
}
}
return tags
}
// Samples memory stats in the background at 1s intervals, and creates
// spans for the data. This is currently opt-in via
// `PULUMI_TRACING_MEMSTATS_POLL_INTERVAL=1s` or similar. Consider
// collecting this by default later whenever tracing is enabled as we
// calibrate that the overhead is low enough.
func collectMemStats(spanPrefix string) {
memStats := runtime.MemStats{}
maxStats := runtime.MemStats{}
poll := func() {
if TracingRootSpan == nil {
return
}
runtime.ReadMemStats(&memStats)
// report cumulative metrics as is
TracingRootSpan.SetTag("runtime.NumCgoCall", runtime.NumCgoCall())
TracingRootSpan.SetTag("MemStats.TotalAlloc", memStats.TotalAlloc)
TracingRootSpan.SetTag("MemStats.Mallocs", memStats.Mallocs)
TracingRootSpan.SetTag("MemStats.Frees", memStats.Frees)
TracingRootSpan.SetTag("MemStats.PauseTotalNs", memStats.PauseTotalNs)
TracingRootSpan.SetTag("MemStats.NumGC", memStats.NumGC)
// for other metrics report the max
if memStats.Sys > maxStats.Sys {
maxStats.Sys = memStats.Sys
TracingRootSpan.SetTag("MemStats.Sys.Max", maxStats.Sys)
}
if memStats.HeapAlloc > maxStats.HeapAlloc {
maxStats.HeapAlloc = memStats.HeapAlloc
TracingRootSpan.SetTag("MemStats.HeapAlloc.Max", maxStats.HeapAlloc)
}
if memStats.HeapSys > maxStats.HeapSys {
maxStats.HeapSys = memStats.HeapSys
TracingRootSpan.SetTag("MemStats.HeapSys.Max", maxStats.HeapSys)
}
if memStats.HeapIdle > maxStats.HeapIdle {
maxStats.HeapIdle = memStats.HeapIdle
TracingRootSpan.SetTag("MemStats.HeapIdle.Max", maxStats.HeapIdle)
}
if memStats.HeapInuse > maxStats.HeapInuse {
maxStats.HeapInuse = memStats.HeapInuse
TracingRootSpan.SetTag("MemStats.HeapInuse.Max", maxStats.HeapInuse)
}
if memStats.HeapReleased > maxStats.HeapReleased {
maxStats.HeapReleased = memStats.HeapReleased
TracingRootSpan.SetTag("MemStats.HeapReleased.Max", maxStats.HeapReleased)
}
if memStats.HeapObjects > maxStats.HeapObjects {
maxStats.HeapObjects = memStats.HeapObjects
TracingRootSpan.SetTag("MemStats.HeapObjects.Max", maxStats.HeapObjects)
}
if memStats.StackInuse > maxStats.StackInuse {
maxStats.StackInuse = memStats.StackInuse
TracingRootSpan.SetTag("MemStats.StackInuse.Max", maxStats.StackInuse)
}
if memStats.StackSys > maxStats.StackSys {
maxStats.StackSys = memStats.StackSys
TracingRootSpan.SetTag("MemStats.StackSys.Max", maxStats.StackSys)
}
}
interval := os.Getenv("PULUMI_TRACING_MEMSTATS_POLL_INTERVAL")
if interval != "" {
intervalDuration, err := time.ParseDuration(interval)
if err == nil {
for {
poll()
time.Sleep(intervalDuration)
}
}
}
}