-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
292 lines (274 loc) · 6.47 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
284
285
286
287
288
289
290
291
292
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
olog "github.com/opentracing/opentracing-go/log"
jaeger "github.com/uber/jaeger-client-go"
config "github.com/uber/jaeger-client-go/config"
jaegerlog "github.com/uber/jaeger-client-go/log"
"github.com/uber/jaeger-client-go/zipkin"
metrics "github.com/uber/jaeger-lib/metrics"
)
var (
delay int64
istio bool
logHeaders bool
port string
remote string
version string
)
// Value is the payload that is used to exchange data
type Value struct {
Value int64 `json:"value"`
}
// RequestHeader can be used to get X-Request-Id from request in Istio
type RequestHeader string
// Init is used to intiantiate the opentracing tracer
func Init(service string) (closer io.Closer) {
cfg := config.Configuration{
Sampler: &config.SamplerConfig{
Type: jaeger.SamplerTypeConst,
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
LocalAgentHostPort: "jaeger:6831",
},
}
var err error
if !istio {
closer, err = cfg.InitGlobalTracer(
service,
config.Logger(jaegerlog.StdLogger),
config.Metrics(metrics.NullFactory),
)
if err != nil {
log.Fatalf(
"Could not initialize Jaeger tracer: %s",
err.Error(),
)
}
return
}
zipkinPropagator := zipkin.NewZipkinB3HTTPHeaderPropagator()
closer, err = cfg.InitGlobalTracer(
service,
config.Logger(jaegerlog.StdLogger),
config.Metrics(metrics.NullFactory),
config.Injector(opentracing.HTTPHeaders, zipkinPropagator),
config.Extractor(opentracing.HTTPHeaders, zipkinPropagator),
config.ZipkinSharedRPCSpan(true),
config.Reporter(jaeger.NewNullReporter()),
)
if err != nil {
log.Fatalf("Could not initialize Zipkin tracer: %s", err.Error())
}
return
}
func injectSpan(
ctx context.Context,
req *http.Request,
) (span opentracing.Span) {
if istio &&
ctx.Value(
RequestHeader("x-request-id"),
) != nil {
requestID := ctx.Value(
RequestHeader("x-request-id"),
).(string)
req.Header.Set("x-request-id", requestID)
}
span = opentracing.SpanFromContext(ctx)
ext.SpanKindRPCClient.Set(span)
ext.HTTPUrl.Set(span, req.URL.String())
ext.HTTPMethod.Set(span, req.Method)
span.Tracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header),
)
return
}
// call perform a remote call for values other than 1
func call(ctx context.Context, i int64) int64 {
input := &Value{
Value: i - 1,
}
var output Value
buf, _ := json.Marshal(input)
r := bytes.NewReader(buf)
req, err := http.NewRequest("POST", remote, r)
req.Header.Set("Content-Type", "application/json")
if err != nil {
panic(err.Error())
}
span := injectSpan(ctx, req)
span.SetTag("execute-for", i)
span.LogFields(
olog.String("event", "call-start"),
olog.String(
"logs",
fmt.Sprintf("function call executed with %d", i),
),
)
if i == 7 {
time.Sleep(2 * time.Second)
}
client := http.Client{}
if resp, err := client.Do(req); err == nil {
if body, err := ioutil.ReadAll(resp.Body); err == nil {
if err := json.Unmarshal(body, &output); err == nil {
span.LogFields(
olog.String("event", "call-end"),
olog.String(
"logs",
fmt.Sprintf(
"function previous call returned %d",
output.Value,
),
),
)
return output.Value
}
}
}
return -1
}
func extractSpan(r *http.Request) (span opentracing.Span) {
tracer := opentracing.GlobalTracer()
spanCtx, _ := tracer.Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header),
)
span = tracer.StartSpan("/root", ext.RPCServerOption(spanCtx))
return
}
func middlewareCaptureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if logHeaders {
fmt.Println("Headers:")
for k, v := range r.Header {
fmt.Printf("%q: %q\n", k, v)
}
fmt.Println("--------")
}
next.ServeHTTP(w, r)
})
}
// recurse is the handler that manages the application root route
func recurse(w http.ResponseWriter, r *http.Request) {
span := extractSpan(r)
defer span.Finish()
var input Value
output := &Value{
Value: 0,
}
if body, err := ioutil.ReadAll(r.Body); err == nil {
json.Unmarshal(body, &input)
output.Value = 1
if input.Value > 1 {
ctx := opentracing.ContextWithSpan(
context.Background(),
span,
)
requestID := r.Header.Get("x-request-id")
if istio && requestID != "" {
ctx = context.WithValue(
ctx,
RequestHeader("x-request-id"),
requestID,
)
}
output.Value = input.Value + call(ctx, input.Value)
}
result, _ := json.Marshal(output)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s\n", result)
return
}
w.WriteHeader(http.StatusInternalServerError)
}
// hello is the handler that manages the application /hello route
func hello(w http.ResponseWriter, r *http.Request) {
start := time.Now()
span := extractSpan(r)
defer span.Finish()
time.Sleep(time.Duration(delay * 1000000))
host, _ := os.Hostname()
delay := time.Since(start).Nanoseconds() / 1000000
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "{\"hostname\": \"%s\", \"delay\": %d, \"version\": \"%s\"}\n", host, delay, version)
return
}
func main() {
flag.Int64Var(
&delay,
"delay",
0,
"The delay for the /hello route in milliseconds",
)
flag.BoolVar(&istio,
"istio",
false,
"Set Istio Envoy-based tracing, including Zipkin headers",
)
flag.BoolVar(&logHeaders,
"log-headers",
false,
"Display headers as part of the service logs",
)
flag.StringVar(
&port,
"port",
"8000",
"The default port for the application",
)
flag.StringVar(
&remote,
"remote",
"http://localhost:8000",
"The remote service location exposed on the outside",
)
flag.StringVar(
&version,
"version",
"v1",
"The application version (default: v1)",
)
flag.Parse()
closer := Init("recursed")
defer closer.Close()
r := mux.NewRouter()
r.Handle("/", middlewareCaptureHeaders(
handlers.LoggingHandler(
os.Stdout,
http.HandlerFunc(recurse),
)))
r.Handle("/hello",
handlers.LoggingHandler(
os.Stdout,
http.HandlerFunc(hello),
))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:8000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Printf("Starting on %s\n", srv.Addr)
log.Fatal(srv.ListenAndServe())
}