-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
193 lines (165 loc) · 6.28 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
// Copyright (c) 2024 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"
"os"
"os/signal"
"runtime"
"strings"
"accelbyte.net/session-manager-grpc-plugin-server-go/pkg/common"
"accelbyte.net/session-manager-grpc-plugin-server-go/pkg/server"
"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"
registered_v1 "accelbyte.net/session-manager-grpc-plugin-server-go/pkg/pb"
"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"
sdkAuth "github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/utils/auth"
promgrpc "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/prometheus/client_golang/prometheus"
prometheusCollectors "github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
)
const (
environment = "production"
id = int64(1)
metricsEndpoint = "/metrics"
metricsPort = 8080
grpcPort = 6565
)
var (
serviceName = common.GetEnv("OTEL_SERVICE_NAME", "SessionManagerFunctionGrpcPluginServerGoDocker")
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.StartCall, logging.FinishCall, logging.PayloadReceived, 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")
}
gRPCServer := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()),
grpc.ChainUnaryInterceptor(unaryServerInterceptors...),
grpc.ChainStreamInterceptor(streamServerInterceptors...),
)
service := &server.SessionManager{
UnimplementedSessionManagerServer: registered_v1.UnimplementedSessionManagerServer{},
}
registered_v1.RegisterSessionManagerServer(gRPCServer, service)
// 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()
}