forked from sw-samuraj/observability-mff-uk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
154 lines (144 loc) · 4.54 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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"log"
"math/rand"
"net/http"
"os"
"runtime"
"time"
)
const (
defaultAppName = "my-app"
defaultAppPort = "4040"
defaultTracingUrl = "http://localhost:14268/api/traces"
hdrCorrelationId = "X-Correlation-ID"
hdrRequestId = "X-Request-ID"
hdrTracingId = "X-Tracing-ID"
hdrUserAgent = "User-Agent"
logFile = "_logs/observability.log"
logFilePattern = "_logs/%s.log"
// tracingUrl = "http://grafana.edu.dobias.info:14268/api/traces"
)
var (
appAddr string
appName string
appPort string
downstreamUrl string
tracingUrl string
goVersion = runtime.Version()
)
func init() {
// parse command line arguments
flag.StringVar(&appName, "n", defaultAppName, "Application name.")
flag.StringVar(&appPort, "p", defaultAppPort, "Application port.")
flag.StringVar(&downstreamUrl, "d", "", "Downstream URL. Empty string triggers no call to downstream service.")
flag.StringVar(&tracingUrl, "t", defaultTracingUrl, "Tracing URL.")
printHelp := flag.Bool("h", false, "Print help.")
flag.Parse()
if *printHelp {
fmt.Fprintf(flag.CommandLine.Output(), "Options:\n")
flag.PrintDefaults()
os.Exit(0)
}
appAddr = fmt.Sprintf("0.0.0.0:%s", appPort)
// Set logging
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
logrus.SetLevel(logrus.DebugLevel)
// Set JSON formatter.
logrus.SetFormatter(&logrus.JSONFormatter{})
// Set logging to a file.
f := getLogFile()
logrus.SetOutput(f)
// Register Prometheus metrics
prometheus.Register(totalRequests)
prometheus.Register(responseStatus)
prometheus.Register(httpDuration)
// Set tracing provider
tp, err := tracerProvider(tracingUrl)
if err != nil {
log.Fatal(err)
}
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.TraceContext{})
}
func main() {
log := funcLog("main")
r := mux.NewRouter()
r.HandleFunc("/", homeHandler)
r.Handle("/metrics", promhttp.Handler())
r.Use(tracingMiddleware)
r.Use(metricsMiddleware)
r.Use(loggingMiddleware)
log.Infof("starting observability app on: %s", appAddr)
http.ListenAndServe(appAddr, r)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
spanCtx, span := otel.Tracer(appName).Start(r.Context(), "homeHandler")
defer span.End()
log := requestLog("homeHandler", r)
if downstreamUrl != "" {
callDownstream(r, spanCtx, downstreamUrl)
}
randomizeLatency()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
resp := make(map[string]string)
resp["message"] = "Observability check: 👌"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Errorf("can't marshal json: %v", err)
}
log.Infof("writing response with status: %d", http.StatusOK)
w.Write(jsonResp)
return
}
func randomizeLatency() {
rand.Seed(time.Now().UnixNano())
n := rand.Intn(1000)
time.Sleep(time.Duration(n) * time.Millisecond)
}
func callDownstream(r *http.Request, ctx context.Context, url string) {
spanCtx, span := otel.Tracer(appName).Start(ctx, "callDownstream")
defer span.End()
log := requestLog("callDownstream", r)
log.Infof("calling downstream service: %s", url)
downstreamRequest := getDownstreamRequest(spanCtx, r, url)
client := getClient()
resp, err := client.Do(downstreamRequest)
if err != nil {
log.Errorf("error calling downstream service: %s", err)
}
log.Infof("downstream service returned http code: %d", resp.StatusCode)
log.Infof("downstream service returned request id: %s", resp.Header.Get(hdrRequestId))
log.Debugf("downstream service returned correlation id: %s", resp.Header.Get(hdrCorrelationId))
}
func getDownstreamRequest(ctx context.Context, r *http.Request, url string) *http.Request {
downstreamRequest, err := http.NewRequestWithContext(ctx, "GET", url, nil)
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(downstreamRequest.Header))
if err != nil {
log := requestLog("getDownstreamRequest", r)
log.Errorf("error assembling downstream request: %s", err)
}
downstreamRequest.Header.Set(hdrUserAgent, fmt.Sprintf("Golang/%s", goVersion))
downstreamRequest.Header.Add(hdrRequestId, uuid.New().String())
downstreamRequest.Header.Add(hdrCorrelationId, getCorrelationId(r))
return downstreamRequest
}
func getClient() *http.Client {
return &http.Client{
Timeout: time.Second * 10,
}
}