server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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/context/store"
  37. "github.com/docker/api/server/proxy"
  38. )
  39. // New returns a new GRPC server.
  40. func New(ctx context.Context) *grpc.Server {
  41. s := grpc.NewServer(
  42. grpc.ChainUnaryInterceptor(
  43. unaryServerInterceptor(ctx),
  44. unary,
  45. ),
  46. grpc.ChainStreamInterceptor(
  47. grpc.StreamServerInterceptor(stream),
  48. grpc.StreamServerInterceptor(streamServerInterceptor(ctx)),
  49. ),
  50. )
  51. hs := health.NewServer()
  52. grpc_health_v1.RegisterHealthServer(s, hs)
  53. return s
  54. }
  55. //CreateListener creates a listener either on tcp://, or local listener, supporting unix:// for unix socket or npipe:// for named pipes on windows
  56. func CreateListener(address string) (net.Listener, error) {
  57. if strings.HasPrefix(address, "tcp://") {
  58. return net.Listen("tcp", strings.TrimPrefix(address, "tcp://"))
  59. }
  60. return createLocalListener(address)
  61. }
  62. func unary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  63. return grpc_prometheus.UnaryServerInterceptor(ctx, req, info, handler)
  64. }
  65. func stream(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  66. return grpc_prometheus.StreamServerInterceptor(srv, ss, info, handler)
  67. }
  68. // unaryServerInterceptor configures the context and sends it to the next handler
  69. func unaryServerInterceptor(clictx context.Context) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  70. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  71. currentContext := getContext(ctx)
  72. configuredCtx, err := configureContext(clictx, currentContext)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return handler(configuredCtx, req)
  77. }
  78. }
  79. // streamServerInterceptor configures the context and sends it to the next handler
  80. func streamServerInterceptor(clictx context.Context) func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  81. return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  82. currentContext := getContext(ss.Context())
  83. ctx, err := configureContext(clictx, currentContext)
  84. if err != nil {
  85. return err
  86. }
  87. return handler(srv, newServerStream(ctx, ss))
  88. }
  89. }
  90. // getContext returns the current context name sent in the request metadata, it
  91. // returns an empty string if there is no metadata
  92. // not present
  93. func getContext(ctx context.Context) string {
  94. md, ok := metadata.FromIncomingContext(ctx)
  95. if !ok {
  96. return ""
  97. }
  98. key, ok := md[apicontext.Key]
  99. if !ok {
  100. return ""
  101. }
  102. if len(key) == 1 {
  103. return key[0]
  104. }
  105. return ""
  106. }
  107. // configureContext populates the request context with objects the client
  108. // needs: the context store and the api client
  109. func configureContext(ctx context.Context, currentContext string) (context.Context, error) {
  110. s := store.ContextStore(ctx)
  111. ctx = store.WithContextStore(ctx, s)
  112. if currentContext != "" {
  113. ctx = apicontext.WithCurrentContext(ctx, currentContext)
  114. }
  115. c, err := client.New(ctx)
  116. if err != nil {
  117. return nil, err
  118. }
  119. ctx, err = proxy.WithClient(ctx, c)
  120. if err != nil {
  121. return nil, err
  122. }
  123. return ctx, nil
  124. }
  125. // A gRPC server stream will only let you get its context but
  126. // there is no way to set a new (augmented context) to the next
  127. // handler (like we do for a unary request). We need to wrap the grpc.ServerSteam
  128. // to be able to set a new context that will be sent to the next stream interceptor.
  129. type contextServerStream struct {
  130. s grpc.ServerStream
  131. ctx context.Context
  132. }
  133. func newServerStream(ctx context.Context, s grpc.ServerStream) grpc.ServerStream {
  134. return &contextServerStream{
  135. s: s,
  136. ctx: ctx,
  137. }
  138. }
  139. func (css *contextServerStream) SetHeader(md metadata.MD) error {
  140. return css.s.SetHeader(md)
  141. }
  142. func (css *contextServerStream) SendHeader(md metadata.MD) error {
  143. return css.s.SendHeader(md)
  144. }
  145. func (css *contextServerStream) SetTrailer(md metadata.MD) {
  146. css.s.SetTrailer(md)
  147. }
  148. func (css *contextServerStream) Context() context.Context {
  149. return css.ctx
  150. }
  151. func (css *contextServerStream) SendMsg(m interface{}) error {
  152. return css.s.SendMsg(m)
  153. }
  154. func (css *contextServerStream) RecvMsg(m interface{}) error {
  155. return css.s.RecvMsg(m)
  156. }