-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
193 lines (158 loc) · 4.79 KB
/
main.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
package main
import (
"context"
"fmt"
"math/rand"
"net/http"
"os"
"time"
"google.golang.org/grpc"
"github.com/go-kit/kit/log"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp"
"go.opentelemetry.io/otel/exporters/otlp/otlpgrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/semconv"
"go.opentelemetry.io/otel/trace"
)
// global vars...gasp!
var addr = "127.0.0.1:8000"
var tracer trace.Tracer
var httpClient http.Client
var logger log.Logger
var metricRequestLatency = promauto.NewHistogram(prometheus.HistogramOpts{
Namespace: "demo",
Name: "request_latency_seconds",
Help: "Request Latency",
Buckets: prometheus.ExponentialBuckets(.0001, 2, 50),
})
func main() {
flush := initTracer()
defer flush()
// initiate globals
tracer = otel.Tracer("demo-app")
httpClient = http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
// create and start server
server := instrumentedServer(handler)
fmt.Println("listening...")
server.ListenAndServe()
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
longRunningProcess(ctx)
// check cache
if shouldExecute(40) {
url := "http://" + addr + "/"
resp, err := instrumentedGet(ctx, url)
defer resp.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// query database
if shouldExecute(40) {
url := "http://" + addr + "/"
resp, err := instrumentedGet(ctx, url)
defer resp.Body.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func shouldExecute(percent int) bool {
return rand.Int()%100 < percent
}
func longRunningProcess(ctx context.Context) {
ctx, sp := tracer.Start(ctx, "Long Running Process")
defer sp.End()
time.Sleep(time.Millisecond * 50)
sp.AddEvent("halfway done!")
time.Sleep(time.Millisecond * 50)
}
/***
Tracing
***/
// Initializes an OTLP exporter, and configures the trace provider
func initTracer() func() {
ctx := context.Background()
driver := otlpgrpc.NewDriver(
otlpgrpc.WithInsecure(),
otlpgrpc.WithEndpoint("tempo:55680"),
otlpgrpc.WithDialOption(grpc.WithBlock()), // useful for testing
)
exp, err := otlp.NewExporter(ctx, driver)
handleErr(err, "failed to create exporter")
res, err := resource.New(ctx,
resource.WithAttributes(
// the service name used to display traces in backends
semconv.ServiceNameKey.String("demo-service"),
),
)
handleErr(err, "failed to create resource")
bsp := sdktrace.NewBatchSpanProcessor(exp)
tracerProvider := sdktrace.NewTracerProvider(
sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),
sdktrace.WithResource(res),
sdktrace.WithSpanProcessor(bsp),
)
// set global propagator to tracecontext (the default is no-op).
otel.SetTextMapPropagator(propagation.TraceContext{})
otel.SetTracerProvider(tracerProvider)
return func() {
// Shutdown will flush any remaining spans.
handleErr(tracerProvider.Shutdown(ctx), "failed to shutdown TracerProvider")
}
}
/***
Server
***/
func instrumentedServer(handler http.HandlerFunc) *http.Server {
// OpenMetrics handler : metrics and exemplars
omHandleFunc := func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
handler.ServeHTTP(w, r)
ctx := r.Context()
traceID := trace.SpanContextFromContext(ctx).TraceID.String()
metricRequestLatency.(prometheus.ExemplarObserver).ObserveWithExemplar(
time.Since(start).Seconds(), prometheus.Labels{"traceID": traceID},
)
// log the trace id with other fields so we can discover traces through logs
logger.Log("msg", "http request", "traceID", traceID, "path", r.URL.Path, "latency", time.Since(start))
}
// OTel handler : traces
otelHandler := otelhttp.NewHandler(http.HandlerFunc(omHandleFunc), "http")
r := mux.NewRouter()
r.Handle("/", otelHandler)
r.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{
EnableOpenMetrics: true,
}))
return &http.Server{
Handler: r,
Addr: "0.0.0.0:8000",
}
}
/***
Client
***/
func instrumentedGet(ctx context.Context, url string) (*http.Response, error) {
// create http request
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
panic(err)
}
return httpClient.Do(req)
}
func handleErr(err error, message string) {
if err != nil {
panic(fmt.Sprintf("%s: %s", err, message))
}
}