forked from abronan/todo-grpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
158 lines (137 loc) · 4.64 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
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"path"
"runtime"
"time"
api "github.com/abronan/todo-grpc/api/todo/v1"
"github.com/abronan/todo-grpc/service/todo"
"github.com/go-pg/pg"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
"github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/grpc-ecosystem/go-grpc-prometheus"
grpc_runtime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/uber/jaeger-client-go/config"
"github.com/uber/jaeger-client-go/rpcmetrics"
prometheus_metrics "github.com/uber/jaeger-lib/metrics/prometheus"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Panic handler prints the stack trace when recovering from a panic.
var panicHandler = grpc_recovery.RecoveryHandlerFunc(func(p interface{}) error {
buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
log.Errorf("panic recovered: %+v", string(buf))
return status.Errorf(codes.Internal, "%s", p)
})
func main() {
app := cli.NewApp()
app.Name = path.Base(os.Args[0])
app.Usage = "Todo app"
app.Version = "0.0.1"
app.Flags = commonFlags
app.Action = start
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func start(c *cli.Context) {
lis, err := net.Listen("tcp", c.String("bind-grpc"))
if err != nil {
log.Fatalf("Failed to listen: %v", c.String("bind-grpc"))
}
// Logrus
logger := log.NewEntry(log.New())
grpc_logrus.ReplaceGrpcLogger(logger)
log.SetLevel(log.InfoLevel)
// Prometheus monitoring
metrics := prometheus_metrics.New()
// Jaeger tracing
cfg := config.Configuration{
Sampler: &config.SamplerConfig{
Type: "const",
Param: c.Float64("jaeger-sampler"),
},
Reporter: &config.ReporterConfig{
LocalAgentHostPort: c.String("jaeger-host") + ":" + c.String("jaeger-port"),
},
}
tracer, closer, err := cfg.New(
"todo",
config.Logger(jaegerLoggerAdapter{logger}),
config.Observer(rpcmetrics.NewObserver(metrics.Namespace("todo", nil), rpcmetrics.DefaultNameNormalizer)),
)
if err != nil {
logger.Fatalf("Cannot initialize Jaeger Tracer %s", err)
}
defer closer.Close()
// Set GRPC Interceptors
server := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_opentracing.StreamServerInterceptor(grpc_opentracing.WithTracer(tracer)),
grpc_prometheus.StreamServerInterceptor,
grpc_logrus.StreamServerInterceptor(logger),
grpc_recovery.StreamServerInterceptor(grpc_recovery.WithRecoveryHandler(panicHandler)),
)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_opentracing.UnaryServerInterceptor(grpc_opentracing.WithTracer(tracer)),
grpc_prometheus.UnaryServerInterceptor,
grpc_logrus.UnaryServerInterceptor(logger),
grpc_recovery.UnaryServerInterceptor(grpc_recovery.WithRecoveryHandler(panicHandler)),
)),
)
// Connect to PostgresQL
db := pg.Connect(&pg.Options{
User: c.String("db-user"),
Password: c.String("db-password"),
Database: c.String("db-name"),
Addr: c.String("db-host") + ":" + c.String("db-port"),
RetryStatementTimeout: true,
MaxRetries: 4,
MinRetryBackoff: 250 * time.Millisecond,
})
// Create Table from Todo struct generated by gRPC
db.CreateTable(&api.Todo{}, nil)
// Register Todo service, prometheus and HTTP service handler
api.RegisterTodoServiceServer(server, &todo.Service{DB: db})
grpc_prometheus.Register(server)
go func() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(c.String("bind-prometheus-http"), mux)
}()
log.Println("Starting Todo service..")
go server.Serve(lis)
conn, err := grpc.Dial(c.String("bind-grpc"), grpc.WithInsecure())
if err != nil {
panic("Couldn't contact grpc server")
}
mux := grpc_runtime.NewServeMux()
err = api.RegisterTodoServiceHandler(context.Background(), mux, conn)
if err != nil {
panic("Cannot serve http api")
}
http.ListenAndServe(c.String("bind-http"), mux)
}
type jaegerLoggerAdapter struct {
logger *log.Entry
}
func (l jaegerLoggerAdapter) Error(msg string) {
l.logger.Error(msg)
}
func (l jaegerLoggerAdapter) Infof(msg string, args ...interface{}) {
l.logger.Info(fmt.Sprintf(msg, args...))
}