services.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. Copyright The containerd Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ttrpc
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path"
  21. "unsafe"
  22. "google.golang.org/grpc/codes"
  23. "google.golang.org/grpc/status"
  24. "google.golang.org/protobuf/proto"
  25. )
  26. type Method func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error)
  27. type StreamHandler func(context.Context, StreamServer) (interface{}, error)
  28. type Stream struct {
  29. Handler StreamHandler
  30. StreamingClient bool
  31. StreamingServer bool
  32. }
  33. type ServiceDesc struct {
  34. Methods map[string]Method
  35. Streams map[string]Stream
  36. }
  37. type serviceSet struct {
  38. services map[string]*ServiceDesc
  39. unaryInterceptor UnaryServerInterceptor
  40. streamInterceptor StreamServerInterceptor
  41. }
  42. func newServiceSet(interceptor UnaryServerInterceptor) *serviceSet {
  43. return &serviceSet{
  44. services: make(map[string]*ServiceDesc),
  45. unaryInterceptor: interceptor,
  46. streamInterceptor: defaultStreamServerInterceptor,
  47. }
  48. }
  49. func (s *serviceSet) register(name string, desc *ServiceDesc) {
  50. if _, ok := s.services[name]; ok {
  51. panic(fmt.Errorf("duplicate service %v registered", name))
  52. }
  53. s.services[name] = desc
  54. }
  55. func (s *serviceSet) unaryCall(ctx context.Context, method Method, info *UnaryServerInfo, data []byte) (p []byte, st *status.Status) {
  56. unmarshal := func(obj interface{}) error {
  57. return protoUnmarshal(data, obj)
  58. }
  59. resp, err := s.unaryInterceptor(ctx, unmarshal, info, method)
  60. if err == nil {
  61. if isNil(resp) {
  62. err = errors.New("ttrpc: marshal called with nil")
  63. } else {
  64. p, err = protoMarshal(resp)
  65. }
  66. }
  67. st, ok := status.FromError(err)
  68. if !ok {
  69. st = status.New(convertCode(err), err.Error())
  70. }
  71. return p, st
  72. }
  73. func (s *serviceSet) streamCall(ctx context.Context, stream StreamHandler, info *StreamServerInfo, ss StreamServer) (p []byte, st *status.Status) {
  74. resp, err := s.streamInterceptor(ctx, ss, info, stream)
  75. if err == nil {
  76. p, err = protoMarshal(resp)
  77. }
  78. st, ok := status.FromError(err)
  79. if !ok {
  80. st = status.New(convertCode(err), err.Error())
  81. }
  82. return
  83. }
  84. func (s *serviceSet) handle(ctx context.Context, req *Request, respond func(*status.Status, []byte, bool, bool) error) (*streamHandler, error) {
  85. srv, ok := s.services[req.Service]
  86. if !ok {
  87. return nil, status.Errorf(codes.Unimplemented, "service %v", req.Service)
  88. }
  89. if method, ok := srv.Methods[req.Method]; ok {
  90. go func() {
  91. ctx, cancel := getRequestContext(ctx, req)
  92. defer cancel()
  93. info := &UnaryServerInfo{
  94. FullMethod: fullPath(req.Service, req.Method),
  95. }
  96. p, st := s.unaryCall(ctx, method, info, req.Payload)
  97. respond(st, p, false, true)
  98. }()
  99. return nil, nil
  100. }
  101. if stream, ok := srv.Streams[req.Method]; ok {
  102. ctx, cancel := getRequestContext(ctx, req)
  103. info := &StreamServerInfo{
  104. FullMethod: fullPath(req.Service, req.Method),
  105. StreamingClient: stream.StreamingClient,
  106. StreamingServer: stream.StreamingServer,
  107. }
  108. sh := &streamHandler{
  109. ctx: ctx,
  110. respond: respond,
  111. recv: make(chan Unmarshaler, 5),
  112. info: info,
  113. }
  114. go func() {
  115. defer cancel()
  116. p, st := s.streamCall(ctx, stream.Handler, info, sh)
  117. respond(st, p, stream.StreamingServer, true)
  118. }()
  119. if req.Payload != nil {
  120. unmarshal := func(obj interface{}) error {
  121. return protoUnmarshal(req.Payload, obj)
  122. }
  123. if err := sh.data(unmarshal); err != nil {
  124. return nil, err
  125. }
  126. }
  127. return sh, nil
  128. }
  129. return nil, status.Errorf(codes.Unimplemented, "method %v", req.Method)
  130. }
  131. type streamHandler struct {
  132. ctx context.Context
  133. respond func(*status.Status, []byte, bool, bool) error
  134. recv chan Unmarshaler
  135. info *StreamServerInfo
  136. remoteClosed bool
  137. localClosed bool
  138. }
  139. func (s *streamHandler) closeSend() {
  140. if !s.remoteClosed {
  141. s.remoteClosed = true
  142. close(s.recv)
  143. }
  144. }
  145. func (s *streamHandler) data(unmarshal Unmarshaler) error {
  146. if s.remoteClosed {
  147. return ErrStreamClosed
  148. }
  149. select {
  150. case s.recv <- unmarshal:
  151. return nil
  152. case <-s.ctx.Done():
  153. return s.ctx.Err()
  154. }
  155. }
  156. func (s *streamHandler) SendMsg(m interface{}) error {
  157. if s.localClosed {
  158. return ErrStreamClosed
  159. }
  160. p, err := protoMarshal(m)
  161. if err != nil {
  162. return err
  163. }
  164. return s.respond(nil, p, true, false)
  165. }
  166. func (s *streamHandler) RecvMsg(m interface{}) error {
  167. select {
  168. case unmarshal, ok := <-s.recv:
  169. if !ok {
  170. return io.EOF
  171. }
  172. return unmarshal(m)
  173. case <-s.ctx.Done():
  174. return s.ctx.Err()
  175. }
  176. }
  177. func protoUnmarshal(p []byte, obj interface{}) error {
  178. switch v := obj.(type) {
  179. case proto.Message:
  180. if err := proto.Unmarshal(p, v); err != nil {
  181. return status.Errorf(codes.Internal, "ttrpc: error unmarshalling payload: %v", err.Error())
  182. }
  183. default:
  184. return status.Errorf(codes.Internal, "ttrpc: error unsupported request type: %T", v)
  185. }
  186. return nil
  187. }
  188. func protoMarshal(obj interface{}) ([]byte, error) {
  189. if obj == nil {
  190. return nil, nil
  191. }
  192. switch v := obj.(type) {
  193. case proto.Message:
  194. r, err := proto.Marshal(v)
  195. if err != nil {
  196. return nil, status.Errorf(codes.Internal, "ttrpc: error marshaling payload: %v", err.Error())
  197. }
  198. return r, nil
  199. default:
  200. return nil, status.Errorf(codes.Internal, "ttrpc: error unsupported response type: %T", v)
  201. }
  202. }
  203. // convertCode maps stdlib go errors into grpc space.
  204. //
  205. // This is ripped from the grpc-go code base.
  206. func convertCode(err error) codes.Code {
  207. switch err {
  208. case nil:
  209. return codes.OK
  210. case io.EOF:
  211. return codes.OutOfRange
  212. case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF:
  213. return codes.FailedPrecondition
  214. case os.ErrInvalid:
  215. return codes.InvalidArgument
  216. case context.Canceled:
  217. return codes.Canceled
  218. case context.DeadlineExceeded:
  219. return codes.DeadlineExceeded
  220. }
  221. switch {
  222. case os.IsExist(err):
  223. return codes.AlreadyExists
  224. case os.IsNotExist(err):
  225. return codes.NotFound
  226. case os.IsPermission(err):
  227. return codes.PermissionDenied
  228. }
  229. return codes.Unknown
  230. }
  231. func fullPath(service, method string) string {
  232. return "/" + path.Join(service, method)
  233. }
  234. func isNil(resp interface{}) bool {
  235. return (*[2]uintptr)(unsafe.Pointer(&resp))[1] == 0
  236. }