-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
283 lines (227 loc) · 8.1 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
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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httptrace"
"os"
"time"
"github.com/emanuelef/go-fiber-honeycomb/otel_instrumentation"
protos "github.com/emanuelef/go-fiber-honeycomb/proto"
_ "github.com/joho/godotenv/autoload"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/go-resty/resty/v2"
"github.com/gofiber/contrib/otelfiber"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
const (
externalURL = "https://pokeapi.co/api/v2/pokemon/ditto"
)
var tracer trace.Tracer
var (
secondaryHost = getEnv("SECONDARY_HOST", "localhost")
secondaryAddress = fmt.Sprintf("http://%s:8082", secondaryHost)
secondaryHelloUrl = fmt.Sprintf("%s/hello", secondaryAddress)
)
func init() {
tracer = otel.Tracer("github.com/emanuelef/go-fiber-honeycomb")
}
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
// The context will carry the traceid and span id
// so once is passed it can be used access to the current span
// or create a child one, the function below will work if placed anywhere
// even in other packages
func exampleChildSpan(ctx context.Context) {
// Get the current span from context
// this can be needed to add an attribute or an event
// but not necessary if the intention is then just to create a child span
span := trace.SpanFromContext(ctx)
span.SetAttributes(attribute.String("stringAttr", "Ciao"))
// Create a child span
_, anotherSpan := tracer.Start(ctx, "child-operation")
anotherSpan.AddEvent("ciao")
time.Sleep(10 * time.Millisecond)
anotherSpan.End()
}
func main() {
ctx := context.Background()
tp, exp, err := otel_instrumentation.InitializeGlobalTracerProvider(ctx)
// Handle shutdown to ensure all sub processes are closed correctly and telemetry is exported
defer func() {
_ = exp.Shutdown(ctx)
_ = tp.Shutdown(ctx)
}()
if err != nil {
log.Fatalf("failed to initialize OpenTelemetry: %e", err)
}
app := fiber.New()
app.Use(otelfiber.Middleware(otelfiber.WithNext(func(c *fiber.Ctx) bool {
return c.Path() == "/health"
})))
app.Use(recover.New())
app.Use(cors.New())
app.Use(compress.New())
// Just to check health and an example of a very frequent request
// that we might not want to generate traces
app.Get("/health", func(c *fiber.Ctx) error {
return c.Send(nil)
})
// Basic GET API to show the OtelFiber middleware is taking
// care of creating the span when called
app.Get("/hello", func(c *fiber.Ctx) error {
return c.Send(nil)
})
// Creates a child span
app.Get("/hello-child", func(c *fiber.Ctx) error {
_, childSpan := tracer.Start(c.UserContext(), "custom-child-span")
time.Sleep(10 * time.Millisecond) // simulate some work
childSpan.End()
return c.Send(nil)
})
// Runs HTTP requests to a public URL and to the secondary app
app.Get("/hello-otelhttp", func(c *fiber.Ctx) error {
resp, err := otelhttp.Get(c.UserContext(), externalURL)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
_, _ = io.ReadAll(resp.Body) // This is needed to close the span
// make sure secondary app is running
resp, err = otelhttp.Get(c.UserContext(), secondaryHelloUrl)
if err != nil {
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
_, _ = io.ReadAll(resp.Body) // This is needed to close the span
// Get current span and add new attributes
span := trace.SpanFromContext(c.UserContext())
span.SetAttributes(attribute.Bool("isTrue", true), attribute.String("stringAttr", "Ciao"))
// Create a child span
ctx, childSpan := tracer.Start(c.UserContext(), "custom-span")
time.Sleep(10 * time.Millisecond)
resp, _ = otelhttp.Get(ctx, externalURL)
_, _ = io.ReadAll(resp.Body)
defer childSpan.End()
time.Sleep(20 * time.Millisecond)
// Add an event to the current span
span.AddEvent("Done Activity")
exampleChildSpan(ctx)
return c.SendString(resp.Status)
})
app.Get("/hello-http-client", func(c *fiber.Ctx) error {
client := http.Client{
Transport: otelhttp.NewTransport(
http.DefaultTransport,
otelhttp.WithClientTrace(func(ctx context.Context) *httptrace.ClientTrace {
return otelhttptrace.NewClientTrace(ctx)
})),
}
req, err := http.NewRequestWithContext(c.UserContext(), "GET", externalURL, nil)
if err != nil {
return err
}
// Needed to propagate the traceparent remotely if not setting the otelhttp.NewTransport
// otel.GetTextMapPropagator().Inject(c.UserContext(), propagation.HeaderCarrier(req.Header))
resp, _ := client.Do(req)
_, _ = io.ReadAll(resp.Body)
req, err = http.NewRequestWithContext(c.UserContext(), "GET", secondaryHelloUrl, nil)
if err != nil {
return err
}
resp, _ = client.Do(req)
body, _ := io.ReadAll(resp.Body)
result := []map[string]any{}
_ = json.Unmarshal([]byte(body), &result)
return c.SendString(resp.Status)
})
app.Get("/hello-resty", func(c *fiber.Ctx) error {
// get current span
span := trace.SpanFromContext(c.UserContext())
// add events to span
time.Sleep(70 * time.Millisecond)
span.AddEvent("Done first fake long running task")
time.Sleep(90 * time.Millisecond)
span.AddEvent("Done second fake long running task")
span.AddEvent("log", trace.WithAttributes(
attribute.String("log.severity", "warning"),
attribute.String("log.message", "Example log"),
))
client := resty.NewWithClient(
&http.Client{
Transport: otelhttp.NewTransport(http.DefaultTransport,
otelhttp.WithClientTrace(func(ctx context.Context) *httptrace.ClientTrace {
return otelhttptrace.NewClientTrace(ctx)
})),
},
)
restyReq := client.R()
restyReq.SetContext(c.UserContext()) // makes it possible to use the HTTP request trace_id
// Needed to propagate the traceparent remotely if not setting the otelhttp.NewTransport
// otel.GetTextMapPropagator().Inject(c.UserContext(), propagation.HeaderCarrier(restyReq.Header))
// run HTTP request first time
resp, _ := restyReq.Get(externalURL)
// run second time and notice http.getconn time compared to first one
_, _ = restyReq.Get(externalURL)
_, _ = restyReq.Get(secondaryHelloUrl)
// simulate some post processing
span.AddEvent("Start post processing")
time.Sleep(50 * time.Millisecond)
return c.SendString(resp.Status())
})
app.Get("/hello-grpc", func(c *fiber.Ctx) error {
grpcHost := getEnv("GRPC_TARGET", "localhost")
grpcTarget := fmt.Sprintf("%s:7070", grpcHost)
conn, err := grpc.NewClient(grpcTarget,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
)
if err != nil {
log.Printf("Did not connect: %v", err)
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
defer conn.Close()
cli := protos.NewGreeterClient(conn)
r, err := cli.SayHello(c.UserContext(), &protos.HelloRequest{Greeting: "ciao"})
if err != nil {
log.Printf("Error: %v", err)
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
}
log.Printf("Greeting: %s", r.GetReply())
return c.Send(nil)
})
// This is to generate a new span that is not a descendand of an existing one
go func() {
// in a real app it is better to use time.NewTicker so that the tivker will be
// recovered by garbage collector
for range time.Tick(time.Minute) {
ctx, span := tracer.Start(context.Background(), "timed-operation")
resp, _ := otelhttp.Get(ctx, externalURL)
_, _ = io.ReadAll(resp.Body)
span.End()
}
}()
host := getEnv("HOST", "localhost")
port := getEnv("PORT", "8080")
hostAddress := fmt.Sprintf("%s:%s", host, port)
err = app.Listen(hostAddress)
if err != nil {
log.Panic(err)
}
}