-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
329 lines (271 loc) · 10.5 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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright (c) 2023 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package main
import (
"bytes"
"context"
"encoding/json"
"extend-custom-guild-service/pkg/service"
"extend-custom-guild-service/pkg/storage"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
"github.com/go-openapi/loads"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/service/cloudsave"
"extend-custom-guild-service/pkg/common"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/repository"
"github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/factory"
"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"
pb "extend-custom-guild-service/pkg/pb"
sdkAuth "github.com/AccelByte/accelbyte-go-sdk/services-api/pkg/utils/auth"
prometheusGrpc "github.com/grpc-ecosystem/go-grpc-prometheus"
prometheusCollectors "github.com/prometheus/client_golang/prometheus/collectors"
)
const (
environment = "production"
id = int64(1)
metricsEndpoint = "/metrics"
metricsPort = 8080
grpcServerPort = 6565
grpcGatewayHTTPPort = 8000
)
var (
serviceName = common.GetEnv("OTEL_SERVICE_NAME", "ExtendCustomServiceGoDocker")
logLevelStr = common.GetEnv("LOG_LEVEL", logrus.InfoLevel.String())
)
func main() {
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),
}
unaryServerInterceptors := []grpc.UnaryServerInterceptor{
prometheusGrpc.UnaryServerInterceptor,
logging.UnaryServerInterceptor(common.InterceptorLogger(logrusLogger), loggingOptions...),
}
streamServerInterceptors := []grpc.StreamServerInterceptor{
prometheusGrpc.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{RefreshRate: 1.0, AutoRefresh: true}
oauthService := iam.OAuth20Service{
Client: factory.NewIamClient(configRepo),
TokenRepository: tokenRepo,
RefreshTokenRepository: refreshRepo,
ConfigRepository: configRepo,
}
if strings.ToLower(common.GetEnv("PLUGIN_GRPC_SERVER_AUTH_ENABLED", "true")) == "true" {
refreshInterval := common.GetEnvInt("REFRESH_INTERVAL", 600)
common.Validator = common.NewTokenValidator(oauthService, time.Duration(refreshInterval)*time.Second, true)
common.Validator.Initialize()
permissionExtractor := common.NewProtoPermissionExtractor()
unaryServerInterceptor := common.NewUnaryAuthServerIntercept(permissionExtractor)
serverServerInterceptor := common.NewStreamAuthServerIntercept(permissionExtractor)
unaryServerInterceptors = append(unaryServerInterceptors, unaryServerInterceptor)
streamServerInterceptors = append(streamServerInterceptors, serverServerInterceptor)
logrus.Infof("added auth interceptors")
}
// Create gRPC Server
s := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()),
grpc.ChainUnaryInterceptor(unaryServerInterceptors...),
grpc.ChainStreamInterceptor(streamServerInterceptors...),
)
// Configure IAM authorization
clientId := configRepo.GetClientId()
clientSecret := configRepo.GetClientSecret()
err = oauthService.LoginClient(&clientId, &clientSecret)
if err != nil {
logrus.Fatalf("Error unable to login using clientId and clientSecret: %v", err)
}
// Initialize the AccelByte CloudSave service
adminGameRecordService := cloudsave.AdminGameRecordService{
Client: factory.NewCloudsaveClient(configRepo),
TokenRepository: tokenRepo,
}
cloudSaveStorage := storage.NewCloudSaveStorage(&adminGameRecordService)
// Register Guild Service
myServiceServer := service.NewMyServiceServer(tokenRepo, configRepo, refreshRepo, cloudSaveStorage)
pb.RegisterServiceServer(s, myServiceServer)
// Enable gRPC Reflection
reflection.Register(s)
logrus.Infof("gRPC reflection enabled")
// Enable gRPC Health Check
grpc_health_v1.RegisterHealthServer(s, health.NewServer())
// Create a new HTTP server for the gRPC-Gateway
grpcGateway, err := common.NewGateway(ctx, fmt.Sprintf("localhost:%d", grpcServerPort))
if err != nil {
logrus.Fatalf("Failed to create gRPC-Gateway: %v", err)
}
// Start the gRPC-Gateway HTTP server
go func() {
swaggerDir := "gateway/apidocs" // Path to swagger directory
grpcGatewayHTTPServer := newGRPCGatewayHTTPServer(fmt.Sprintf(":%d", grpcGatewayHTTPPort), grpcGateway, logrus.New(), swaggerDir)
logrus.Infof("Starting gRPC-Gateway HTTP server on port %d", grpcGatewayHTTPPort)
if err := grpcGatewayHTTPServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Fatalf("Failed to run gRPC-Gateway HTTP server: %v", err)
}
}()
prometheusGrpc.Register(s)
// Register Prometheus Metrics
prometheusRegistry := prometheus.NewRegistry()
prometheusRegistry.MustRegister(
prometheusCollectors.NewGoCollector(),
prometheusCollectors.NewProcessCollector(prometheusCollectors.ProcessCollectorOpts{}),
prometheusGrpc.DefaultServerMetrics,
)
go func() {
http.Handle(metricsEndpoint, promhttp.HandlerFor(prometheusRegistry, promhttp.HandlerOpts{}))
logrus.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", grpcServerPort))
if err != nil {
logrus.Fatalf("failed to listen to tcp:%d: %v", grpcServerPort, err)
return
}
go func() {
if err = s.Serve(lis); err != nil {
logrus.Fatalf("failed to run gRPC server: %v", err)
return
}
}()
logrus.Infof("gRPC server started")
logrus.Infof("app server started on base path: " + common.BasePath)
ctx, _ = signal.NotifyContext(ctx, os.Interrupt)
<-ctx.Done()
}
func newGRPCGatewayHTTPServer(
addr string, handler http.Handler, logger *logrus.Logger, swaggerDir string,
) *http.Server {
// Create a new ServeMux
mux := http.NewServeMux()
// Add the gRPC-Gateway handler
mux.Handle("/", handler)
// Serve Swagger UI and JSON
serveSwaggerUI(mux)
serveSwaggerJSON(mux, swaggerDir)
// Add logging middleware
loggedMux := loggingMiddleware(logger, mux)
return &http.Server{
Addr: addr,
Handler: loggedMux,
ErrorLog: log.New(os.Stderr, "httpSrv: ", log.LstdFlags), // Configure the logger for the HTTP server
}
}
// loggingMiddleware is a middleware that logs HTTP requests
func loggingMiddleware(logger *logrus.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
duration := time.Since(start)
logger.WithFields(logrus.Fields{
"method": r.Method,
"path": r.URL.Path,
"duration": duration,
}).Info("HTTP request")
})
}
func serveSwaggerUI(mux *http.ServeMux) {
swaggerUIDir := "third_party/swagger-ui"
fileServer := http.FileServer(http.Dir(swaggerUIDir))
swaggerUiPath := fmt.Sprintf("%s/apidocs/", common.BasePath)
mux.Handle(swaggerUiPath, http.StripPrefix(swaggerUiPath, fileServer))
}
func serveSwaggerJSON(mux *http.ServeMux, swaggerDir string) {
fileHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
matchingFiles, err := filepath.Glob(filepath.Join(swaggerDir, "*.swagger.json"))
if err != nil || len(matchingFiles) == 0 {
http.Error(w, "Error finding Swagger JSON file", http.StatusInternalServerError)
return
}
firstMatchingFile := matchingFiles[0]
swagger, err := loads.Spec(firstMatchingFile)
if err != nil {
http.Error(w, "Error parsing Swagger JSON file", http.StatusInternalServerError)
return
}
// Update the base path
swagger.Spec().BasePath = common.BasePath
updatedSwagger, err := swagger.Spec().MarshalJSON()
if err != nil {
http.Error(w, "Error serializing updated Swagger JSON", http.StatusInternalServerError)
return
}
var prettySwagger bytes.Buffer
err = json.Indent(&prettySwagger, updatedSwagger, "", " ")
if err != nil {
http.Error(w, "Error formatting updated Swagger JSON", http.StatusInternalServerError)
return
}
_, err = w.Write(prettySwagger.Bytes())
if err != nil {
http.Error(w, "Error writing Swagger JSON response", http.StatusInternalServerError)
return
}
})
apidocsPath := fmt.Sprintf("%s/apidocs/api.json", common.BasePath)
mux.Handle(apidocsPath, fileHandler)
}