You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/transport/grpc/server.go

200 lines
4.7 KiB

4 years ago
package grpc
import (
"context"
"net"
"net/url"
"sync"
4 years ago
"time"
apimd "github.com/go-kratos/kratos/v2/api/metadata"
ic "github.com/go-kratos/kratos/v2/internal/context"
4 years ago
"github.com/go-kratos/kratos/v2/internal/host"
"github.com/go-kratos/kratos/v2/log"
"github.com/go-kratos/kratos/v2/metadata"
4 years ago
"github.com/go-kratos/kratos/v2/middleware"
"github.com/go-kratos/kratos/v2/transport"
4 years ago
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
grpcmd "google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
4 years ago
)
var _ transport.Server = (*Server)(nil)
var _ transport.Endpointer = (*Server)(nil)
4 years ago
// ServerOption is gRPC server option.
type ServerOption func(o *Server)
// Network with server network.
func Network(network string) ServerOption {
return func(s *Server) {
s.network = network
}
}
// Address with server address.
func Address(addr string) ServerOption {
return func(s *Server) {
s.address = addr
}
}
// Timeout with server timeout.
func Timeout(timeout time.Duration) ServerOption {
return func(s *Server) {
s.timeout = timeout
}
}
// Logger with server logger.
func Logger(logger log.Logger) ServerOption {
return func(s *Server) {
s.log = log.NewHelper(logger)
4 years ago
}
}
// Middleware with server middleware.
func Middleware(m ...middleware.Middleware) ServerOption {
4 years ago
return func(s *Server) {
s.middleware = middleware.Chain(m...)
4 years ago
}
}
// UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server.
func UnaryInterceptor(in ...grpc.UnaryServerInterceptor) ServerOption {
return func(s *Server) {
s.ints = in
}
}
4 years ago
// Options with grpc options.
func Options(opts ...grpc.ServerOption) ServerOption {
return func(s *Server) {
s.grpcOpts = opts
}
}
// Server is a gRPC server wrapper.
type Server struct {
*grpc.Server
ctx context.Context
4 years ago
lis net.Listener
once sync.Once
err error
4 years ago
network string
address string
endpoint *url.URL
4 years ago
timeout time.Duration
log *log.Helper
middleware middleware.Middleware
ints []grpc.UnaryServerInterceptor
4 years ago
grpcOpts []grpc.ServerOption
health *health.Server
metadata *apimd.Server
4 years ago
}
// NewServer creates a gRPC server by options.
func NewServer(opts ...ServerOption) *Server {
srv := &Server{
network: "tcp",
address: ":0",
timeout: 1 * time.Second,
health: health.NewServer(),
log: log.NewHelper(log.DefaultLogger),
4 years ago
}
for _, o := range opts {
o(srv)
}
var ints = []grpc.UnaryServerInterceptor{
srv.unaryServerInterceptor(),
}
if len(srv.ints) > 0 {
ints = append(ints, srv.ints...)
}
4 years ago
var grpcOpts = []grpc.ServerOption{
grpc.ChainUnaryInterceptor(ints...),
4 years ago
}
if len(srv.grpcOpts) > 0 {
grpcOpts = append(grpcOpts, srv.grpcOpts...)
}
srv.Server = grpc.NewServer(grpcOpts...)
srv.metadata = apimd.NewServer(srv.Server)
// internal register
grpc_health_v1.RegisterHealthServer(srv.Server, srv.health)
apimd.RegisterMetadataServer(srv.Server, srv.metadata)
reflection.Register(srv.Server)
4 years ago
return srv
}
// Endpoint return a real address to registry endpoint.
// examples:
// grpc://127.0.0.1:9000?isSecure=false
func (s *Server) Endpoint() (*url.URL, error) {
s.once.Do(func() {
lis, err := net.Listen(s.network, s.address)
if err != nil {
s.err = err
return
}
addr, err := host.Extract(s.address, s.lis)
if err != nil {
lis.Close()
s.err = err
return
}
s.lis = lis
s.endpoint = &url.URL{Scheme: "grpc", Host: addr}
})
if s.err != nil {
return nil, s.err
}
return s.endpoint, nil
4 years ago
}
// Start start the gRPC server.
func (s *Server) Start(ctx context.Context) error {
if _, err := s.Endpoint(); err != nil {
return err
4 years ago
}
s.ctx = ctx
s.log.Infof("[gRPC] server listening on: %s", s.lis.Addr().String())
s.health.Resume()
return s.Serve(s.lis)
4 years ago
}
// Stop stop the gRPC server.
func (s *Server) Stop(ctx context.Context) error {
4 years ago
s.GracefulStop()
s.health.Shutdown()
4 years ago
s.log.Info("[gRPC] server stopping")
return nil
}
func (s *Server) unaryServerInterceptor() grpc.UnaryServerInterceptor {
4 years ago
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx, cancel := ic.Merge(ctx, s.ctx)
defer cancel()
md, _ := grpcmd.FromIncomingContext(ctx)
ctx = transport.NewServerContext(ctx, &Transport{
endpoint: s.endpoint.String(),
method: info.FullMethod,
metadata: metadata.New(md),
})
if s.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.timeout)
defer cancel()
}
4 years ago
h := func(ctx context.Context, req interface{}) (interface{}, error) {
return handler(ctx, req)
}
if s.middleware != nil {
h = s.middleware(h)
4 years ago
}
return h(ctx, req)
}
}