forked from moby/buildkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trace.go
94 lines (76 loc) · 1.86 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
package main
import (
"context"
"io"
"os"
"strings"
"github.com/moby/buildkit/util/appcontext"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/opentracing/opentracing-go/log"
jaeger "github.com/uber/jaeger-client-go"
"github.com/urfave/cli"
)
func getTracer() (opentracing.Tracer, io.Closer) {
if traceAddr := os.Getenv("JAEGER_TRACE"); traceAddr != "" {
tr, err := jaeger.NewUDPTransport(traceAddr, 0)
if err != nil {
panic(err)
}
// metricsFactory := prometheus.New()
return jaeger.NewTracer(
"buildctl",
jaeger.NewConstSampler(true),
jaeger.NewRemoteReporter(tr),
)
}
return opentracing.NoopTracer{}, &nopCloser{}
}
func attachAppContext(app *cli.App) {
ctx := appcontext.Context()
tracer, closer := getTracer()
var span opentracing.Span
for i, cmd := range app.Commands {
func(before cli.BeforeFunc) {
name := cmd.Name
app.Commands[i].Before = func(clicontext *cli.Context) error {
if before != nil {
if err := before(clicontext); err != nil {
return err
}
}
span = tracer.StartSpan(name)
span.LogFields(log.String("command", strings.Join(os.Args, " ")))
ctx = opentracing.ContextWithSpan(ctx, span)
clicontext.App.Metadata["context"] = ctx
return nil
}
}(cmd.Before)
}
app.ExitErrHandler = func(clicontext *cli.Context, err error) {
if span != nil {
ext.Error.Set(span, true)
}
cli.HandleExitCoder(err)
}
after := app.After
app.After = func(clicontext *cli.Context) error {
if after != nil {
if err := after(clicontext); err != nil {
return err
}
}
if span != nil {
span.Finish()
}
return closer.Close()
}
}
func commandContext(c *cli.Context) context.Context {
return c.App.Metadata["context"].(context.Context)
}
type nopCloser struct {
}
func (*nopCloser) Close() error {
return nil
}