-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrpc_server.go
226 lines (207 loc) · 7.28 KB
/
grpc_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
package api
import (
"context"
"errors"
"runtime/debug"
"time"
pb "github.com/clyso/ceph-api/api/gen/grpc/go"
xctx "github.com/clyso/ceph-api/pkg/ctx"
"github.com/clyso/ceph-api/pkg/log"
"github.com/clyso/ceph-api/pkg/trace"
"github.com/clyso/ceph-api/pkg/types"
"github.com/golang/protobuf/proto"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/rs/zerolog"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
otel_trace "go.opentelemetry.io/otel/trace"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
func NewGrpcServer(conf Config,
clusterAPI pb.ClusterServer,
usersAPI pb.UsersServer,
authAPI pb.AuthServer,
crushRuleAPI pb.CrushRuleServer,
statusAPI pb.StatusServer,
authN grpc_auth.AuthFunc,
tracer otel_trace.TracerProvider,
logConf log.Config) *grpc.Server {
// lis, err := net.Listen("tcp", fmt.Sprintf(":%d", conf.GrpcPort))
// if err != nil {
// return nil, nil, err
// }
srv := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler(otelgrpc.WithTracerProvider(tracer))),
grpc.KeepaliveParams(keepalive.ServerParameters{
Time: 50 * time.Second,
Timeout: 10 * time.Second,
}),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 30 * time.Second,
PermitWithoutStream: true,
}),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
prometheus.UnaryServerInterceptor,
grpc_ctxtags.UnaryServerInterceptor(),
grpc_auth.UnaryServerInterceptor(authN),
log.UnaryInterceptor(logConf),
trace.UnaryInterceptor(),
ErrorInterceptor(),
unaryServerAccessLog(conf.AccessLog),
unaryServerRecover,
)),
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
prometheus.StreamServerInterceptor,
grpc_ctxtags.StreamServerInterceptor(),
grpc_auth.StreamServerInterceptor(authN),
log.StreamInterceptor(logConf),
trace.StreamInterceptor(),
ErrorStreamInterceptor(),
streamServerAccessLog(conf.AccessLog),
streamServerRecover,
)))
// Register Servers
pb.RegisterClusterServer(srv, clusterAPI)
pb.RegisterUsersServer(srv, usersAPI)
pb.RegisterAuthServer(srv, authAPI)
pb.RegisterCrushRuleServer(srv, crushRuleAPI)
pb.RegisterStatusServer(srv, statusAPI)
if conf.GrpcReflection {
reflection.Register(srv)
}
return srv
// return func(ctx context.Context) error {
// return srv.Serve(lis)
// }, func(ctx context.Context) error {
// srv.Stop()
// return nil
// }, nil
}
func unaryServerRecover(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) {
defer func() {
if p := recover(); p != nil {
l := zerolog.Ctx(ctx)
l.Error().
Stack().
Uint32("grpc_code", uint32(codes.Internal)).
Interface("panic", p).Stack().Msg(string(debug.Stack()))
err = status.Errorf(codes.Internal, "%v", p)
}
}()
return handler(ctx, req)
}
func streamServerRecover(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer func() {
if p := recover(); p != nil {
l := zerolog.Ctx(stream.Context())
l.Error().
Uint32("grpc_code", uint32(codes.Internal)).
Interface("panic", p).Stack().Msg("panic")
err = status.Errorf(codes.Internal, "%v", p)
}
}()
return handler(srv, stream)
}
func unaryServerAccessLog(enableAccessLog bool) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) {
if enableAccessLog {
zerolog.Ctx(ctx).Info().Str("grpc_method", info.FullMethod).Msg("access ceph api")
}
resp, err := handler(ctx, req)
logger := zerolog.Ctx(ctx)
rpcLogHandler(logger, err, info.FullMethod)
return resp, err
}
}
func rpcLogHandler(l *zerolog.Logger, err error, fullMethod string) {
s := status.Convert(err)
code, msg := s.Code(), s.Message()
switch code {
case codes.OK, codes.Canceled, codes.NotFound:
l.Debug().Str("grpc_code", code.String()).Str("grpc_method", fullMethod).Str("response_status", "success").Msg(msg)
case codes.Unauthenticated:
l.Debug().Str("grpc_code", code.String()).Str("grpc_method", fullMethod).Str("response_status", "failed").Msg(msg)
case codes.PermissionDenied, codes.FailedPrecondition, codes.AlreadyExists, codes.InvalidArgument:
// log expected errors with WARN level
l.Warn().Str("grpc_code", code.String()).Str("grpc_method", fullMethod).Str("response_status", "failed").Msg(msg)
default:
l.Error().Str("grpc_code", code.String()).Str("grpc_method", fullMethod).Str("response_status", "failed").Msg(msg)
}
}
func streamServerAccessLog(enableAccessLog bool) grpc.StreamServerInterceptor {
return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
if enableAccessLog {
zerolog.Ctx(stream.Context()).Info().Str("grpc_method", info.FullMethod).Msg("access ceph api stream")
}
err = handler(srv, stream)
logger := zerolog.Ctx(stream.Context())
rpcLogHandler(logger, err, info.FullMethod)
return err
}
}
func ErrorInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
resp, err := handler(ctx, req)
return resp, convertApiError(ctx, err)
}
}
func ErrorStreamInterceptor() grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return convertApiError(ss.Context(), handler(srv, ss))
}
}
func convertApiError(ctx context.Context, err error) error {
if err == nil {
return nil
}
details := []proto.Message{&errdetails.RequestInfo{RequestId: xctx.GetTraceID(ctx)}}
var code codes.Code
var mappedErr error
switch {
case errors.Is(err, types.ErrNotImplemented):
code = codes.Unimplemented
mappedErr = types.ErrNotImplemented
case errors.Is(err, types.ErrInvalidArg):
code = codes.InvalidArgument
mappedErr = types.ErrInvalidArg
details = append(details, &errdetails.ErrorInfo{
Reason: err.Error(),
})
case errors.Is(err, types.ErrInvalidConfig):
code = codes.InvalidArgument
mappedErr = types.ErrInvalidConfig
details = append(details, &errdetails.ErrorInfo{
Reason: err.Error(),
})
case errors.Is(err, types.ErrNotFound):
code = codes.NotFound
mappedErr = types.ErrNotFound
case errors.Is(err, types.ErrAlreadyExists):
code = codes.AlreadyExists
mappedErr = types.ErrAlreadyExists
case errors.Is(err, types.ErrUnauthenticated):
code = codes.Unauthenticated
mappedErr = types.ErrUnauthenticated
case errors.Is(err, types.ErrAccessDenied):
code = codes.PermissionDenied
mappedErr = types.ErrAccessDenied
default:
code = codes.Internal
mappedErr = types.ErrInternal
}
zerolog.Ctx(ctx).Err(err).Msg("api error returned")
st := status.New(code, mappedErr.Error())
stInfo, wdErr := st.WithDetails(details...)
if wdErr != nil {
zerolog.Ctx(ctx).Err(wdErr).Msg("unable to build details for grpc error message")
return st.Err()
}
return stInfo.Err()
}