server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. Copyright (c) 2020 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package server
  25. import (
  26. "context"
  27. "net"
  28. "strings"
  29. grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
  30. "google.golang.org/grpc"
  31. "google.golang.org/grpc/health"
  32. "google.golang.org/grpc/health/grpc_health_v1"
  33. "google.golang.org/grpc/metadata"
  34. "github.com/docker/api/client"
  35. apicontext "github.com/docker/api/context"
  36. "github.com/docker/api/server/proxy"
  37. )
  38. // New returns a new GRPC server.
  39. func New(ctx context.Context) *grpc.Server {
  40. s := grpc.NewServer(
  41. grpc.ChainUnaryInterceptor(
  42. unaryServerInterceptor(ctx),
  43. unary,
  44. ),
  45. grpc.ChainStreamInterceptor(
  46. grpc.StreamServerInterceptor(stream),
  47. grpc.StreamServerInterceptor(streamServerInterceptor(ctx)),
  48. ),
  49. )
  50. hs := health.NewServer()
  51. grpc_health_v1.RegisterHealthServer(s, hs)
  52. return s
  53. }
  54. //CreateListener creates a listener either on tcp://, or local listener, supporting unix:// for unix socket or npipe:// for named pipes on windows
  55. func CreateListener(address string) (net.Listener, error) {
  56. if strings.HasPrefix(address, "tcp://") {
  57. return net.Listen("tcp", strings.TrimPrefix(address, "tcp://"))
  58. }
  59. return createLocalListener(address)
  60. }
  61. func unary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  62. return grpc_prometheus.UnaryServerInterceptor(ctx, req, info, handler)
  63. }
  64. func stream(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  65. return grpc_prometheus.StreamServerInterceptor(srv, ss, info, handler)
  66. }
  67. // unaryServerInterceptor configures the context and sends it to the next handler
  68. func unaryServerInterceptor(clictx context.Context) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  69. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  70. currentContext := getContext(ctx)
  71. configuredCtx, err := configureContext(clictx, currentContext)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return handler(configuredCtx, req)
  76. }
  77. }
  78. // streamServerInterceptor configures the context and sends it to the next handler
  79. func streamServerInterceptor(clictx context.Context) func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  80. return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  81. currentContext := getContext(ss.Context())
  82. ctx, err := configureContext(clictx, currentContext)
  83. if err != nil {
  84. return err
  85. }
  86. return handler(srv, newServerStream(ctx, ss))
  87. }
  88. }
  89. // getContext returns the current context name sent in the request metadata, it
  90. // returns an empty string if there is no metadata
  91. // not present
  92. func getContext(ctx context.Context) string {
  93. md, ok := metadata.FromIncomingContext(ctx)
  94. if !ok {
  95. return ""
  96. }
  97. key, ok := md[apicontext.Key]
  98. if !ok {
  99. return ""
  100. }
  101. if len(key) == 1 {
  102. return key[0]
  103. }
  104. return ""
  105. }
  106. // configureContext populates the request context with objects the client
  107. // needs: the context store and the api client
  108. func configureContext(ctx context.Context, currentContext string) (context.Context, error) {
  109. if currentContext != "" {
  110. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  111. }
  112. c, err := client.New(ctx)
  113. if err != nil {
  114. return nil, err
  115. }
  116. ctx, err = proxy.WithClient(ctx, c)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return ctx, nil
  121. }
  122. // A gRPC server stream will only let you get its context but
  123. // there is no way to set a new (augmented context) to the next
  124. // handler (like we do for a unary request). We need to wrap the grpc.ServerSteam
  125. // to be able to set a new context that will be sent to the next stream interceptor.
  126. type contextServerStream struct {
  127. s grpc.ServerStream
  128. ctx context.Context
  129. }
  130. func newServerStream(ctx context.Context, s grpc.ServerStream) grpc.ServerStream {
  131. return &contextServerStream{
  132. s: s,
  133. ctx: ctx,
  134. }
  135. }
  136. func (css *contextServerStream) SetHeader(md metadata.MD) error {
  137. return css.s.SetHeader(md)
  138. }
  139. func (css *contextServerStream) SendHeader(md metadata.MD) error {
  140. return css.s.SendHeader(md)
  141. }
  142. func (css *contextServerStream) SetTrailer(md metadata.MD) {
  143. css.s.SetTrailer(md)
  144. }
  145. func (css *contextServerStream) Context() context.Context {
  146. return css.ctx
  147. }
  148. func (css *contextServerStream) SendMsg(m interface{}) error {
  149. return css.s.SendMsg(m)
  150. }
  151. func (css *contextServerStream) RecvMsg(m interface{}) error {
  152. return css.s.RecvMsg(m)
  153. }