-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
197 lines (166 loc) · 6.15 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
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"strings"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/factory"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/repository"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/service/iam"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/contrib/propagators/b3"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
sdkAuth "github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/utils/auth"
promgrpc "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
prometheusCollectors "github.com/prometheus/client_golang/prometheus/collectors"
"revocation-grpc-plugin-server-go/pkg/common"
pb "revocation-grpc-plugin-server-go/pkg/pb"
"revocation-grpc-plugin-server-go/pkg/service"
)
const (
id = int64(1)
environment = "production"
metricsEndpoint = "/metrics"
metricsPort = 8080
grpcPort = 6565
)
var (
serviceName = common.GetEnv("OTEL_SERVICE_NAME", "RevocationServiceGoServerDocker")
logLevelStr = common.GetEnv("LOG_LEVEL", logrus.InfoLevel.String())
)
func main() {
go func() {
runtime.SetBlockProfileRate(1)
runtime.SetMutexProfileFraction(10)
}()
logrus.Infof("starting app server..")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
logrusLevel, err := logrus.ParseLevel(logLevelStr)
if err != nil {
logrusLevel = logrus.InfoLevel
}
logrusLogger := logrus.New()
logrusLogger.SetLevel(logrusLevel)
loggingOptions := []logging.Option{
logging.WithLogOnEvents(logging.PayloadSent),
logging.WithFieldsFromContext(func(ctx context.Context) logging.Fields {
if span := trace.SpanContextFromContext(ctx); span.IsSampled() {
return logging.Fields{"traceID", span.TraceID().String()}
}
return nil
}),
logging.WithLevels(logging.DefaultClientCodeToLevel),
logging.WithDurationField(logging.DurationToDurationField),
}
srvMetrics := promgrpc.NewServerMetrics()
unaryServerInterceptors := []grpc.UnaryServerInterceptor{
srvMetrics.UnaryServerInterceptor(),
logging.UnaryServerInterceptor(common.InterceptorLogger(logrusLogger), loggingOptions...),
}
streamServerInterceptors := []grpc.StreamServerInterceptor{
srvMetrics.StreamServerInterceptor(),
logging.StreamServerInterceptor(common.InterceptorLogger(logrusLogger), loggingOptions...),
}
// Preparing the IAM authorization
var tokenRepo repository.TokenRepository = sdkAuth.DefaultTokenRepositoryImpl()
var configRepo repository.ConfigRepository = sdkAuth.DefaultConfigRepositoryImpl()
var refreshRepo repository.RefreshTokenRepository = &sdkAuth.RefreshTokenImpl{AutoRefresh: true, RefreshRate: 0.01}
if strings.ToLower(common.GetEnv("PLUGIN_GRPC_SERVER_AUTH_ENABLED", "false")) == "true" {
common.OAuth = &iam.OAuth20Service{
Client: factory.NewIamClient(configRepo),
ConfigRepository: configRepo,
TokenRepository: tokenRepo,
RefreshTokenRepository: refreshRepo,
}
common.OAuth.SetLocalValidation(true)
unaryServerInterceptors = append(unaryServerInterceptors, common.UnaryAuthServerIntercept)
streamServerInterceptors = append(streamServerInterceptors, common.StreamAuthServerIntercept)
logrus.Infof("added auth interceptors")
}
// Create gRPC Server
grpcServer := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()),
grpc.ChainUnaryInterceptor(unaryServerInterceptors...),
grpc.ChainStreamInterceptor(streamServerInterceptors...),
)
// Register Filter Service
revocationServiceServer := service.NewRevocationServiceServer()
pb.RegisterRevocationServer(grpcServer, revocationServiceServer)
// Enable gRPC Reflection
reflection.Register(grpcServer)
logrus.Infof("gRPC reflection enabled")
// Enable gRPC Health Check
grpc_health_v1.RegisterHealthServer(grpcServer, health.NewServer())
// Register Prometheus Metrics
srvMetrics.InitializeMetrics(grpcServer)
prometheusRegistry := prometheus.NewRegistry()
prometheusRegistry.MustRegister(
prometheusCollectors.NewGoCollector(),
prometheusCollectors.NewProcessCollector(prometheusCollectors.ProcessCollectorOpts{}),
srvMetrics,
)
go func() {
http.Handle(metricsEndpoint, promhttp.HandlerFor(prometheusRegistry, promhttp.HandlerOpts{}))
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", metricsPort), nil))
}()
logrus.Infof("serving prometheus metrics at: (:%d%s)", metricsPort, metricsEndpoint)
// Set Tracer Provider
tracerProvider, err := common.NewTracerProvider(serviceName, environment, id)
if err != nil {
logrus.Fatalf("failed to create tracer provider: %v", err)
return
}
otel.SetTracerProvider(tracerProvider)
defer func(ctx context.Context) {
if err := tracerProvider.Shutdown(ctx); err != nil {
logrus.Fatal(err)
}
}(ctx)
logrus.Infof("set tracer provider: (name: %s environment: %s id: %d)", serviceName, environment, id)
// Set Text Map Propagator
otel.SetTextMapPropagator(
propagation.NewCompositeTextMapPropagator(
b3.New(),
propagation.TraceContext{},
propagation.Baggage{},
),
)
logrus.Infof("set text map propagator")
// Start gRPC Server
logrus.Infof("starting gRPC server..")
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
if err != nil {
logrus.Fatalf("failed to listen to tcp:%d: %v", grpcPort, err)
return
}
go func() {
if err = grpcServer.Serve(lis); err != nil {
logrus.Fatalf("failed to run gRPC server: %v", err)
return
}
}()
logrus.Infof("gRPC server started")
logrus.Infof("app server started")
ctx, _ = signal.NotifyContext(ctx, os.Interrupt)
<-ctx.Done()
}