/
server.go
265 lines (228 loc) · 8.96 KB
/
server.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
package server
import (
"context"
"fmt"
"net"
"strings"
"time"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
ilogger "github.com/meateam/elasticsearch-logger"
pb "github.com/meateam/permit-service/proto"
"github.com/meateam/permit-service/service"
"github.com/meateam/permit-service/service/mongodb"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"go.elastic.co/apm/module/apmgrpc"
"go.elastic.co/apm/module/apmmongo"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
)
const (
envPrefix = "pmts"
configPort = "port"
configHealthCheckInterval = "health_check_interval"
configElasticAPMIgnoreURLS = "elastic_apm_ignore_urls"
configMongoConnectionString = "mongo_host"
configMongoClientConnectionTimeout = "mongo_client_connection_timeout"
configMongoClientPingTimeout = "mongo_client_ping_timeout"
configSpikeService = "spike_service"
configGrantType = "grant_type"
configAudience = "audience"
configApprovalUrl = "approval_url"
)
// PermitServer is a structure that holds the permit grpc server
// and its services configuration
type PermitServer struct {
*grpc.Server
logger *logrus.Logger
port string
healthCheckInterval int
permitService service.Service
}
func init() {
viper.SetDefault(configPort, "8080")
viper.SetDefault(configHealthCheckInterval, 3)
viper.SetDefault(configElasticAPMIgnoreURLS, "/grpc.health.v1.Health/Check")
viper.SetDefault(configMongoConnectionString, "mongodb://localhost:27017/permit")
viper.SetDefault(configMongoClientConnectionTimeout, 10)
viper.SetDefault(configSpikeService, "spike-service:8080")
viper.SetDefault(configMongoClientPingTimeout, 10)
viper.SetDefault(configGrantType, "client_credentials")
viper.SetDefault(configAudience, "kartoffel")
viper.SetDefault(configApprovalUrl, "approval:8080")
viper.SetEnvPrefix(envPrefix)
viper.AutomaticEnv()
}
// Serve accepts incoming connections on the listener `lis`, creating a new
// ServerTransport and service goroutine for each. The service goroutines
// read gRPC requests and then call the registered handlers to reply to them.
// Serve returns when `lis.Accept` fails with fatal errors. `lis` will be closed when
// this method returns.
// If `lis` is nil then Serve creates a `net.Listener` with "tcp" network listening
// on the configured `TCP_PORT`, which defaults to "8080".
// Serve will return a non-nil error unless Stop or GracefulStop is called.
func (s PermitServer) Serve(lis net.Listener) {
listener := lis
if lis == nil {
l, err := net.Listen("tcp", ":"+s.port)
if err != nil {
s.logger.Fatalf("failed to listen: %v", err)
}
listener = l
}
s.logger.Infof("listening and serving grpc server on port %s", s.port)
if err := s.Server.Serve(listener); err != nil {
s.logger.Fatalf(err.Error())
}
}
// NewServer configures and creates a grpc.Server instance.
// Configure using environment variables.
// `HEALTH_CHECK_INTERVAL`: Interval to update serving state of the health check server.
// `PORT`: TCP port on which the grpc server would serve on.
func NewServer(logger *logrus.Logger) *PermitServer {
// If no logger is given, create a new default logger for the server.
if logger == nil {
logger = ilogger.NewLogger()
}
// Set up grpc server opts with logger interceptor.
serverOpts := append(
serverLoggerInterceptor(logger),
grpc.MaxRecvMsgSize(16<<20),
)
// Create a new grpc server.
grpcServer := grpc.NewServer(
serverOpts...,
)
// Connect to mongodb.
controller, err := initMongoDBController(viper.GetString(configMongoConnectionString))
if err != nil {
logger.Fatalf("%v", err)
}
// Initiate services gRPC connections.
spikeConn, err := initServiceConn(viper.GetString(configSpikeService))
if err != nil {
logger.Fatalf("couldn't setup spike service connection: %v", err)
}
// Create a permit service and register it on the grpc server.
permitService := service.NewService(
controller, logger, spikeConn, viper.GetString(configGrantType),
viper.GetString(configAudience), viper.GetString(configApprovalUrl))
pb.RegisterPermitServer(grpcServer, permitService)
// Create a health server and register it on the grpc server.
healthServer := health.NewServer()
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
permitServer := &PermitServer{
Server: grpcServer,
logger: logger,
port: viper.GetString(configPort),
healthCheckInterval: viper.GetInt(configHealthCheckInterval),
permitService: permitService,
}
// Health check validation goroutine worker.
go permitServer.healthCheckWorker(healthServer)
return permitServer
}
// serverLoggerInterceptor configures the logger interceptor for the permit server.
func serverLoggerInterceptor(logger *logrus.Logger) []grpc.ServerOption {
// Create new logrus entry for logger interceptor.
logrusEntry := logrus.NewEntry(logger)
ignorePayload := ilogger.IgnoreServerMethodsDecider(
append(
strings.Split(viper.GetString(configElasticAPMIgnoreURLS), ","),
)...,
)
ignoreInitialRequest := ilogger.IgnoreServerMethodsDecider(
strings.Split(viper.GetString(configElasticAPMIgnoreURLS), ",")...,
)
// Shared options for the logger, with a custom gRPC code to log level function.
loggerOpts := []grpc_logrus.Option{
grpc_logrus.WithDecider(func(fullMethodName string, err error) bool {
return ignorePayload(fullMethodName)
}),
grpc_logrus.WithLevels(grpc_logrus.DefaultClientCodeToLevel),
}
return ilogger.ElasticsearchLoggerServerInterceptor(
logrusEntry,
ignorePayload,
ignoreInitialRequest,
loggerOpts...,
)
}
func connectToMongoDB(connectionString string) (*mongo.Client, error) {
// Create mongodb client
mongoOptions := options.Client().ApplyURI(connectionString).SetMonitor(apmmongo.CommandMonitor())
mongoClient, err := mongo.NewClient(mongoOptions)
if err != nil {
return nil, fmt.Errorf("failed creating mongodb client with connection string %s : %v", connectionString, err)
}
// Connect client to mongodb
mongoClientConnectionTimeout := viper.GetDuration(configMongoClientConnectionTimeout)
connectionTimeoutCtx, cancelConn := context.WithTimeout(context.TODO(), mongoClientConnectionTimeout*time.Second)
defer cancelConn()
err = mongoClient.Connect(connectionTimeoutCtx)
if err != nil {
return nil, fmt.Errorf("failed connecting to mongodb with connection string %s : %v", connectionString, err)
}
// Check the connection
mongoClientPingTimeout := viper.GetDuration(configMongoClientPingTimeout)
pingTimeoutCtx, cancelPing := context.WithTimeout(context.TODO(), mongoClientPingTimeout*time.Second)
defer cancelPing()
err = mongoClient.Ping(pingTimeoutCtx, readpref.Primary())
if err != nil {
return nil, fmt.Errorf("failed pinging to mongodb with connection string %s : %v", connectionString, err)
}
return mongoClient, nil
}
func initMongoDBController(connectionString string) (service.Controller, error) {
mongoClient, err := connectToMongoDB(connectionString)
if err != nil {
return nil, err
}
db, err := getMongoDatabaseName(mongoClient, connectionString)
if err != nil {
return nil, err
}
controller, err := mongodb.NewMongoController(db)
if err != nil {
return nil, fmt.Errorf("failed creating mongo store: %v", err)
}
return controller, nil
}
func getMongoDatabaseName(mongoClient *mongo.Client, connectionString string) (*mongo.Database, error) {
connString, err := connstring.Parse(connectionString)
if err != nil {
return nil, fmt.Errorf("failed parsing connection string %s: %v", connectionString, err)
}
return mongoClient.Database(connString.Database), nil
}
// healthCheckWorker is running an infinite loop that sets the serving status once
// in s.healthCheckInterval seconds.
func (s PermitServer) healthCheckWorker(healthServer *health.Server) {
mongoClientPingTimeout := viper.GetDuration(configMongoClientPingTimeout)
for {
if s.permitService.HealthCheck(mongoClientPingTimeout * time.Second) {
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
} else {
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_NOT_SERVING)
}
time.Sleep(time.Second * time.Duration(s.healthCheckInterval))
}
}
// initServiceConn creates a gRPC connection to url, returns the created connection
// and nil err on success. Returns non-nil error if any error occurred while
// creating the connection.
func initServiceConn(url string) (*grpc.ClientConn, error) {
conn, err := grpc.Dial(url,
grpc.WithUnaryInterceptor(apmgrpc.NewUnaryClientInterceptor()),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(10<<20)),
grpc.WithInsecure())
if err != nil {
return nil, err
}
return conn, nil
}