-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
189 lines (171 loc) 路 5.59 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
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"net/http/httptrace"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"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/exporters/otlp/otlpmetric/otlpmetricgrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"goa.design/clue/clue"
"goa.design/clue/debug"
"goa.design/clue/health"
"goa.design/clue/log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/reflection"
"goa.design/clue/example/middleware"
"goa.design/clue/example/weather/services/forecaster"
"goa.design/clue/example/weather/services/forecaster/clients/weathergov"
genforecaster "goa.design/clue/example/weather/services/forecaster/gen/forecaster"
genpb "goa.design/clue/example/weather/services/forecaster/gen/grpc/forecaster/pb"
gengrpc "goa.design/clue/example/weather/services/forecaster/gen/grpc/forecaster/server"
)
func main() {
var (
grpcaddr = flag.String("grpc-addr", ":8080", "gRPC listen address")
httpaddr = flag.String("http-addr", ":8081", "HTTP listen address (health checks and metrics)")
coladdr = flag.String("otel-addr", ":4317", "OpenTelemetry collector listen address")
debugf = flag.Bool("debug", false, "Enable debug logs")
)
flag.Parse()
// 1. Create logger
format := log.FormatJSON
if log.IsTerminal() {
format = log.FormatTerminal
}
ctx := log.Context(context.Background(), log.WithFormat(format), log.WithFunc(log.Span))
if *debugf {
ctx = log.Context(ctx, log.WithDebug())
log.Debugf(ctx, "debug logs enabled")
}
// 2. Setup instrumentation
spanExporter, err := otlptracegrpc.New(ctx,
otlptracegrpc.WithEndpoint(*coladdr),
otlptracegrpc.WithTLSCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(ctx, err, "failed to initialize tracing")
}
defer func() {
// Create new context in case the parent context has been canceled.
ctx := log.Context(context.Background(), log.WithFormat(format))
if err := spanExporter.Shutdown(ctx); err != nil {
log.Errorf(ctx, err, "failed to shutdown tracing")
}
}()
metricExporter, err := otlpmetricgrpc.New(ctx,
otlpmetricgrpc.WithEndpoint(*coladdr),
otlpmetricgrpc.WithTLSCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(ctx, err, "failed to initialize metrics")
}
defer func() {
// Create new context in case the parent context has been canceled.
ctx := log.Context(context.Background(), log.WithFormat(format))
if err := metricExporter.Shutdown(ctx); err != nil {
log.Errorf(ctx, err, "failed to shutdown metrics")
}
}()
cfg, err := clue.NewConfig(ctx,
genforecaster.ServiceName,
genforecaster.APIVersion,
metricExporter,
spanExporter,
)
if err != nil {
log.Fatalf(ctx, err, "failed to initialize instrumentation")
}
clue.ConfigureOpenTelemetry(ctx, cfg)
// 3. Create clients
httpc := &http.Client{
Transport: log.Client(
otelhttp.NewTransport(
http.DefaultTransport,
otelhttp.WithClientTrace(func(ctx context.Context) *httptrace.ClientTrace {
return otelhttptrace.NewClientTrace(ctx)
}),
))}
wc := weathergov.New(httpc)
// 4. Create service & endpoints
svc := forecaster.New(wc)
endpoints := genforecaster.NewEndpoints(svc)
endpoints.Use(debug.LogPayloads())
endpoints.Use(log.Endpoint)
endpoints.Use(middleware.ErrorReporter())
// 5. Create transport
server := gengrpc.New(endpoints, nil)
grpcsvr := grpc.NewServer(
grpc.ChainUnaryInterceptor(
log.UnaryServerInterceptor(ctx), // Add logger to request context and log requests.
debug.UnaryServerInterceptor()), // Enable debug log level control
grpc.StatsHandler(otelgrpc.NewServerHandler())) // Instrument server.
genpb.RegisterForecasterServer(grpcsvr, server)
reflection.Register(grpcsvr)
for svc, info := range grpcsvr.GetServiceInfo() {
for _, m := range info.Methods {
log.Print(ctx, log.KV{K: "method", V: svc + "/" + m.Name})
}
}
// 6. Setup health check and debug endpoints
mux := http.NewServeMux()
debug.MountDebugLogEnabler(mux)
debug.MountPprofHandlers(mux)
check := health.Handler(health.NewChecker(wc))
check = log.HTTP(ctx)(check).(http.HandlerFunc) // Log health-check errors
mux.Handle("/healthz", check)
mux.Handle("/livez", check)
httpsvr := &http.Server{Addr: *httpaddr, Handler: mux}
// 7. Start gRPC and HTTP servers
errc := make(chan error)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errc <- fmt.Errorf("signal: %s", <-c)
}()
ctx, cancel := context.WithCancel(ctx)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
go func() {
log.Printf(ctx, "HTTP server listening on %s", *httpaddr)
errc <- httpsvr.ListenAndServe()
}()
var l net.Listener
go func() {
var err error
l, err = net.Listen("tcp", *grpcaddr)
if err != nil {
errc <- err
}
log.Printf(ctx, "gRPC server listening on %s", *grpcaddr)
errc <- grpcsvr.Serve(l)
}()
<-ctx.Done()
log.Printf(ctx, "shutting down HTTP and gRPC servers")
// Shutdown gracefully with a 30s timeout.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
grpcsvr.GracefulStop()
if err := httpsvr.Shutdown(ctx); err != nil {
log.Errorf(ctx, err, "failed to shutdown HTTP server")
}
}()
// Cleanup
if err := <-errc; err != nil && !strings.HasPrefix(err.Error(), "signal:") {
log.Errorf(ctx, err, "exiting")
}
cancel()
wg.Wait()
log.Printf(ctx, "exited")
}