server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. /*
  2. *
  3. * Copyright 2014, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. package grpc
  34. import (
  35. "bytes"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "net"
  40. "net/http"
  41. "reflect"
  42. "runtime"
  43. "strings"
  44. "sync"
  45. "time"
  46. "golang.org/x/net/context"
  47. "golang.org/x/net/http2"
  48. "golang.org/x/net/trace"
  49. "google.golang.org/grpc/codes"
  50. "google.golang.org/grpc/credentials"
  51. "google.golang.org/grpc/grpclog"
  52. "google.golang.org/grpc/internal"
  53. "google.golang.org/grpc/metadata"
  54. "google.golang.org/grpc/transport"
  55. )
  56. type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
  57. // MethodDesc represents an RPC service's method specification.
  58. type MethodDesc struct {
  59. MethodName string
  60. Handler methodHandler
  61. }
  62. // ServiceDesc represents an RPC service's specification.
  63. type ServiceDesc struct {
  64. ServiceName string
  65. // The pointer to the service interface. Used to check whether the user
  66. // provided implementation satisfies the interface requirements.
  67. HandlerType interface{}
  68. Methods []MethodDesc
  69. Streams []StreamDesc
  70. Metadata interface{}
  71. }
  72. // service consists of the information of the server serving this service and
  73. // the methods in this service.
  74. type service struct {
  75. server interface{} // the server for service methods
  76. md map[string]*MethodDesc
  77. sd map[string]*StreamDesc
  78. mdata interface{}
  79. }
  80. // Server is a gRPC server to serve RPC requests.
  81. type Server struct {
  82. opts options
  83. mu sync.Mutex // guards following
  84. lis map[net.Listener]bool
  85. conns map[io.Closer]bool
  86. drain bool
  87. // A CondVar to let GracefulStop() blocks until all the pending RPCs are finished
  88. // and all the transport goes away.
  89. cv *sync.Cond
  90. m map[string]*service // service name -> service info
  91. events trace.EventLog
  92. }
  93. type options struct {
  94. creds credentials.TransportCredentials
  95. codec Codec
  96. cp Compressor
  97. dc Decompressor
  98. maxMsgSize int
  99. unaryInt UnaryServerInterceptor
  100. streamInt StreamServerInterceptor
  101. maxConcurrentStreams uint32
  102. useHandlerImpl bool // use http.Handler-based server
  103. }
  104. var defaultMaxMsgSize = 1024 * 1024 * 4 // use 4MB as the default message size limit
  105. // A ServerOption sets options.
  106. type ServerOption func(*options)
  107. // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
  108. func CustomCodec(codec Codec) ServerOption {
  109. return func(o *options) {
  110. o.codec = codec
  111. }
  112. }
  113. // RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
  114. func RPCCompressor(cp Compressor) ServerOption {
  115. return func(o *options) {
  116. o.cp = cp
  117. }
  118. }
  119. // RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
  120. func RPCDecompressor(dc Decompressor) ServerOption {
  121. return func(o *options) {
  122. o.dc = dc
  123. }
  124. }
  125. // MaxMsgSize returns a ServerOption to set the max message size in bytes for inbound mesages.
  126. // If this is not set, gRPC uses the default 4MB.
  127. func MaxMsgSize(m int) ServerOption {
  128. return func(o *options) {
  129. o.maxMsgSize = m
  130. }
  131. }
  132. // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
  133. // of concurrent streams to each ServerTransport.
  134. func MaxConcurrentStreams(n uint32) ServerOption {
  135. return func(o *options) {
  136. o.maxConcurrentStreams = n
  137. }
  138. }
  139. // Creds returns a ServerOption that sets credentials for server connections.
  140. func Creds(c credentials.TransportCredentials) ServerOption {
  141. return func(o *options) {
  142. o.creds = c
  143. }
  144. }
  145. // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
  146. // server. Only one unary interceptor can be installed. The construction of multiple
  147. // interceptors (e.g., chaining) can be implemented at the caller.
  148. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
  149. return func(o *options) {
  150. if o.unaryInt != nil {
  151. panic("The unary server interceptor has been set.")
  152. }
  153. o.unaryInt = i
  154. }
  155. }
  156. // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
  157. // server. Only one stream interceptor can be installed.
  158. func StreamInterceptor(i StreamServerInterceptor) ServerOption {
  159. return func(o *options) {
  160. if o.streamInt != nil {
  161. panic("The stream server interceptor has been set.")
  162. }
  163. o.streamInt = i
  164. }
  165. }
  166. // NewServer creates a gRPC server which has no service registered and has not
  167. // started to accept requests yet.
  168. func NewServer(opt ...ServerOption) *Server {
  169. var opts options
  170. opts.maxMsgSize = defaultMaxMsgSize
  171. for _, o := range opt {
  172. o(&opts)
  173. }
  174. if opts.codec == nil {
  175. // Set the default codec.
  176. opts.codec = protoCodec{}
  177. }
  178. s := &Server{
  179. lis: make(map[net.Listener]bool),
  180. opts: opts,
  181. conns: make(map[io.Closer]bool),
  182. m: make(map[string]*service),
  183. }
  184. s.cv = sync.NewCond(&s.mu)
  185. if EnableTracing {
  186. _, file, line, _ := runtime.Caller(1)
  187. s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
  188. }
  189. return s
  190. }
  191. // printf records an event in s's event log, unless s has been stopped.
  192. // REQUIRES s.mu is held.
  193. func (s *Server) printf(format string, a ...interface{}) {
  194. if s.events != nil {
  195. s.events.Printf(format, a...)
  196. }
  197. }
  198. // errorf records an error in s's event log, unless s has been stopped.
  199. // REQUIRES s.mu is held.
  200. func (s *Server) errorf(format string, a ...interface{}) {
  201. if s.events != nil {
  202. s.events.Errorf(format, a...)
  203. }
  204. }
  205. // RegisterService register a service and its implementation to the gRPC
  206. // server. Called from the IDL generated code. This must be called before
  207. // invoking Serve.
  208. func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
  209. ht := reflect.TypeOf(sd.HandlerType).Elem()
  210. st := reflect.TypeOf(ss)
  211. if !st.Implements(ht) {
  212. grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
  213. }
  214. s.register(sd, ss)
  215. }
  216. func (s *Server) register(sd *ServiceDesc, ss interface{}) {
  217. s.mu.Lock()
  218. defer s.mu.Unlock()
  219. s.printf("RegisterService(%q)", sd.ServiceName)
  220. if _, ok := s.m[sd.ServiceName]; ok {
  221. grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
  222. }
  223. srv := &service{
  224. server: ss,
  225. md: make(map[string]*MethodDesc),
  226. sd: make(map[string]*StreamDesc),
  227. mdata: sd.Metadata,
  228. }
  229. for i := range sd.Methods {
  230. d := &sd.Methods[i]
  231. srv.md[d.MethodName] = d
  232. }
  233. for i := range sd.Streams {
  234. d := &sd.Streams[i]
  235. srv.sd[d.StreamName] = d
  236. }
  237. s.m[sd.ServiceName] = srv
  238. }
  239. // MethodInfo contains the information of an RPC including its method name and type.
  240. type MethodInfo struct {
  241. // Name is the method name only, without the service name or package name.
  242. Name string
  243. // IsClientStream indicates whether the RPC is a client streaming RPC.
  244. IsClientStream bool
  245. // IsServerStream indicates whether the RPC is a server streaming RPC.
  246. IsServerStream bool
  247. }
  248. // ServiceInfo contains unary RPC method info, streaming RPC methid info and metadata for a service.
  249. type ServiceInfo struct {
  250. Methods []MethodInfo
  251. // Metadata is the metadata specified in ServiceDesc when registering service.
  252. Metadata interface{}
  253. }
  254. // GetServiceInfo returns a map from service names to ServiceInfo.
  255. // Service names include the package names, in the form of <package>.<service>.
  256. func (s *Server) GetServiceInfo() map[string]ServiceInfo {
  257. ret := make(map[string]ServiceInfo)
  258. for n, srv := range s.m {
  259. methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd))
  260. for m := range srv.md {
  261. methods = append(methods, MethodInfo{
  262. Name: m,
  263. IsClientStream: false,
  264. IsServerStream: false,
  265. })
  266. }
  267. for m, d := range srv.sd {
  268. methods = append(methods, MethodInfo{
  269. Name: m,
  270. IsClientStream: d.ClientStreams,
  271. IsServerStream: d.ServerStreams,
  272. })
  273. }
  274. ret[n] = ServiceInfo{
  275. Methods: methods,
  276. Metadata: srv.mdata,
  277. }
  278. }
  279. return ret
  280. }
  281. var (
  282. // ErrServerStopped indicates that the operation is now illegal because of
  283. // the server being stopped.
  284. ErrServerStopped = errors.New("grpc: the server has been stopped")
  285. )
  286. func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  287. if s.opts.creds == nil {
  288. return rawConn, nil, nil
  289. }
  290. return s.opts.creds.ServerHandshake(rawConn)
  291. }
  292. // Serve accepts incoming connections on the listener lis, creating a new
  293. // ServerTransport and service goroutine for each. The service goroutines
  294. // read gRPC requests and then call the registered handlers to reply to them.
  295. // Serve returns when lis.Accept fails. lis will be closed when
  296. // this method returns.
  297. func (s *Server) Serve(lis net.Listener) error {
  298. s.mu.Lock()
  299. s.printf("serving")
  300. if s.lis == nil {
  301. s.mu.Unlock()
  302. lis.Close()
  303. return ErrServerStopped
  304. }
  305. s.lis[lis] = true
  306. s.mu.Unlock()
  307. defer func() {
  308. s.mu.Lock()
  309. if s.lis != nil && s.lis[lis] {
  310. lis.Close()
  311. delete(s.lis, lis)
  312. }
  313. s.mu.Unlock()
  314. }()
  315. for {
  316. rawConn, err := lis.Accept()
  317. if err != nil {
  318. s.mu.Lock()
  319. s.printf("done serving; Accept = %v", err)
  320. s.mu.Unlock()
  321. return err
  322. }
  323. // Start a new goroutine to deal with rawConn
  324. // so we don't stall this Accept loop goroutine.
  325. go s.handleRawConn(rawConn)
  326. }
  327. }
  328. // handleRawConn is run in its own goroutine and handles a just-accepted
  329. // connection that has not had any I/O performed on it yet.
  330. func (s *Server) handleRawConn(rawConn net.Conn) {
  331. conn, authInfo, err := s.useTransportAuthenticator(rawConn)
  332. if err != nil {
  333. s.mu.Lock()
  334. s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
  335. s.mu.Unlock()
  336. grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
  337. // If serverHandShake returns ErrConnDispatched, keep rawConn open.
  338. if err != credentials.ErrConnDispatched {
  339. rawConn.Close()
  340. }
  341. return
  342. }
  343. s.mu.Lock()
  344. if s.conns == nil {
  345. s.mu.Unlock()
  346. conn.Close()
  347. return
  348. }
  349. s.mu.Unlock()
  350. if s.opts.useHandlerImpl {
  351. s.serveUsingHandler(conn)
  352. } else {
  353. s.serveNewHTTP2Transport(conn, authInfo)
  354. }
  355. }
  356. // serveNewHTTP2Transport sets up a new http/2 transport (using the
  357. // gRPC http2 server transport in transport/http2_server.go) and
  358. // serves streams on it.
  359. // This is run in its own goroutine (it does network I/O in
  360. // transport.NewServerTransport).
  361. func (s *Server) serveNewHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) {
  362. st, err := transport.NewServerTransport("http2", c, s.opts.maxConcurrentStreams, authInfo)
  363. if err != nil {
  364. s.mu.Lock()
  365. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  366. s.mu.Unlock()
  367. c.Close()
  368. grpclog.Println("grpc: Server.Serve failed to create ServerTransport: ", err)
  369. return
  370. }
  371. if !s.addConn(st) {
  372. st.Close()
  373. return
  374. }
  375. s.serveStreams(st)
  376. }
  377. func (s *Server) serveStreams(st transport.ServerTransport) {
  378. defer s.removeConn(st)
  379. defer st.Close()
  380. var wg sync.WaitGroup
  381. st.HandleStreams(func(stream *transport.Stream) {
  382. wg.Add(1)
  383. go func() {
  384. defer wg.Done()
  385. s.handleStream(st, stream, s.traceInfo(st, stream))
  386. }()
  387. })
  388. wg.Wait()
  389. }
  390. var _ http.Handler = (*Server)(nil)
  391. // serveUsingHandler is called from handleRawConn when s is configured
  392. // to handle requests via the http.Handler interface. It sets up a
  393. // net/http.Server to handle the just-accepted conn. The http.Server
  394. // is configured to route all incoming requests (all HTTP/2 streams)
  395. // to ServeHTTP, which creates a new ServerTransport for each stream.
  396. // serveUsingHandler blocks until conn closes.
  397. //
  398. // This codepath is only used when Server.TestingUseHandlerImpl has
  399. // been configured. This lets the end2end tests exercise the ServeHTTP
  400. // method as one of the environment types.
  401. //
  402. // conn is the *tls.Conn that's already been authenticated.
  403. func (s *Server) serveUsingHandler(conn net.Conn) {
  404. if !s.addConn(conn) {
  405. conn.Close()
  406. return
  407. }
  408. defer s.removeConn(conn)
  409. h2s := &http2.Server{
  410. MaxConcurrentStreams: s.opts.maxConcurrentStreams,
  411. }
  412. h2s.ServeConn(conn, &http2.ServeConnOpts{
  413. Handler: s,
  414. })
  415. }
  416. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  417. st, err := transport.NewServerHandlerTransport(w, r)
  418. if err != nil {
  419. http.Error(w, err.Error(), http.StatusInternalServerError)
  420. return
  421. }
  422. if !s.addConn(st) {
  423. st.Close()
  424. return
  425. }
  426. defer s.removeConn(st)
  427. s.serveStreams(st)
  428. }
  429. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  430. // If tracing is not enabled, it returns nil.
  431. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  432. if !EnableTracing {
  433. return nil
  434. }
  435. trInfo = &traceInfo{
  436. tr: trace.New("grpc.Recv."+methodFamily(stream.Method()), stream.Method()),
  437. }
  438. trInfo.firstLine.client = false
  439. trInfo.firstLine.remoteAddr = st.RemoteAddr()
  440. stream.TraceContext(trInfo.tr)
  441. if dl, ok := stream.Context().Deadline(); ok {
  442. trInfo.firstLine.deadline = dl.Sub(time.Now())
  443. }
  444. return trInfo
  445. }
  446. func (s *Server) addConn(c io.Closer) bool {
  447. s.mu.Lock()
  448. defer s.mu.Unlock()
  449. if s.conns == nil || s.drain {
  450. return false
  451. }
  452. s.conns[c] = true
  453. return true
  454. }
  455. func (s *Server) removeConn(c io.Closer) {
  456. s.mu.Lock()
  457. defer s.mu.Unlock()
  458. if s.conns != nil {
  459. delete(s.conns, c)
  460. s.cv.Signal()
  461. }
  462. }
  463. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
  464. var cbuf *bytes.Buffer
  465. if cp != nil {
  466. cbuf = new(bytes.Buffer)
  467. }
  468. p, err := encode(s.opts.codec, msg, cp, cbuf)
  469. if err != nil {
  470. // This typically indicates a fatal issue (e.g., memory
  471. // corruption or hardware faults) the application program
  472. // cannot handle.
  473. //
  474. // TODO(zhaoq): There exist other options also such as only closing the
  475. // faulty stream locally and remotely (Other streams can keep going). Find
  476. // the optimal option.
  477. grpclog.Fatalf("grpc: Server failed to encode response %v", err)
  478. }
  479. return t.Write(stream, p, opts)
  480. }
  481. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
  482. if trInfo != nil {
  483. defer trInfo.tr.Finish()
  484. trInfo.firstLine.client = false
  485. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  486. defer func() {
  487. if err != nil && err != io.EOF {
  488. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  489. trInfo.tr.SetError()
  490. }
  491. }()
  492. }
  493. if s.opts.cp != nil {
  494. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  495. stream.SetSendCompress(s.opts.cp.Type())
  496. }
  497. p := &parser{r: stream}
  498. for {
  499. pf, req, err := p.recvMsg(s.opts.maxMsgSize)
  500. if err == io.EOF {
  501. // The entire stream is done (for unary RPC only).
  502. return err
  503. }
  504. if err == io.ErrUnexpectedEOF {
  505. err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  506. }
  507. if err != nil {
  508. switch err := err.(type) {
  509. case *rpcError:
  510. if err := t.WriteStatus(stream, err.code, err.desc); err != nil {
  511. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  512. }
  513. case transport.ConnectionError:
  514. // Nothing to do here.
  515. case transport.StreamError:
  516. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  517. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  518. }
  519. default:
  520. panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", err, err))
  521. }
  522. return err
  523. }
  524. if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
  525. switch err := err.(type) {
  526. case *rpcError:
  527. if err := t.WriteStatus(stream, err.code, err.desc); err != nil {
  528. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  529. }
  530. default:
  531. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  532. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  533. }
  534. }
  535. return err
  536. }
  537. statusCode := codes.OK
  538. statusDesc := ""
  539. df := func(v interface{}) error {
  540. if pf == compressionMade {
  541. var err error
  542. req, err = s.opts.dc.Do(bytes.NewReader(req))
  543. if err != nil {
  544. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  545. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  546. }
  547. return err
  548. }
  549. }
  550. if len(req) > s.opts.maxMsgSize {
  551. // TODO: Revisit the error code. Currently keep it consistent with
  552. // java implementation.
  553. statusCode = codes.Internal
  554. statusDesc = fmt.Sprintf("grpc: server received a message of %d bytes exceeding %d limit", len(req), s.opts.maxMsgSize)
  555. }
  556. if err := s.opts.codec.Unmarshal(req, v); err != nil {
  557. return err
  558. }
  559. if trInfo != nil {
  560. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  561. }
  562. return nil
  563. }
  564. reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
  565. if appErr != nil {
  566. if err, ok := appErr.(*rpcError); ok {
  567. statusCode = err.code
  568. statusDesc = err.desc
  569. } else {
  570. statusCode = convertCode(appErr)
  571. statusDesc = appErr.Error()
  572. }
  573. if trInfo != nil && statusCode != codes.OK {
  574. trInfo.tr.LazyLog(stringer(statusDesc), true)
  575. trInfo.tr.SetError()
  576. }
  577. if err := t.WriteStatus(stream, statusCode, statusDesc); err != nil {
  578. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", err)
  579. return err
  580. }
  581. return nil
  582. }
  583. if trInfo != nil {
  584. trInfo.tr.LazyLog(stringer("OK"), false)
  585. }
  586. opts := &transport.Options{
  587. Last: true,
  588. Delay: false,
  589. }
  590. if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
  591. switch err := err.(type) {
  592. case transport.ConnectionError:
  593. // Nothing to do here.
  594. case transport.StreamError:
  595. statusCode = err.Code
  596. statusDesc = err.Desc
  597. default:
  598. statusCode = codes.Unknown
  599. statusDesc = err.Error()
  600. }
  601. return err
  602. }
  603. if trInfo != nil {
  604. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  605. }
  606. return t.WriteStatus(stream, statusCode, statusDesc)
  607. }
  608. }
  609. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
  610. if s.opts.cp != nil {
  611. stream.SetSendCompress(s.opts.cp.Type())
  612. }
  613. ss := &serverStream{
  614. t: t,
  615. s: stream,
  616. p: &parser{r: stream},
  617. codec: s.opts.codec,
  618. cp: s.opts.cp,
  619. dc: s.opts.dc,
  620. maxMsgSize: s.opts.maxMsgSize,
  621. trInfo: trInfo,
  622. }
  623. if ss.cp != nil {
  624. ss.cbuf = new(bytes.Buffer)
  625. }
  626. if trInfo != nil {
  627. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  628. defer func() {
  629. ss.mu.Lock()
  630. if err != nil && err != io.EOF {
  631. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  632. ss.trInfo.tr.SetError()
  633. }
  634. ss.trInfo.tr.Finish()
  635. ss.trInfo.tr = nil
  636. ss.mu.Unlock()
  637. }()
  638. }
  639. var appErr error
  640. if s.opts.streamInt == nil {
  641. appErr = sd.Handler(srv.server, ss)
  642. } else {
  643. info := &StreamServerInfo{
  644. FullMethod: stream.Method(),
  645. IsClientStream: sd.ClientStreams,
  646. IsServerStream: sd.ServerStreams,
  647. }
  648. appErr = s.opts.streamInt(srv.server, ss, info, sd.Handler)
  649. }
  650. if appErr != nil {
  651. if err, ok := appErr.(*rpcError); ok {
  652. ss.statusCode = err.code
  653. ss.statusDesc = err.desc
  654. } else if err, ok := appErr.(transport.StreamError); ok {
  655. ss.statusCode = err.Code
  656. ss.statusDesc = err.Desc
  657. } else {
  658. ss.statusCode = convertCode(appErr)
  659. ss.statusDesc = appErr.Error()
  660. }
  661. }
  662. if trInfo != nil {
  663. ss.mu.Lock()
  664. if ss.statusCode != codes.OK {
  665. ss.trInfo.tr.LazyLog(stringer(ss.statusDesc), true)
  666. ss.trInfo.tr.SetError()
  667. } else {
  668. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  669. }
  670. ss.mu.Unlock()
  671. }
  672. return t.WriteStatus(ss.s, ss.statusCode, ss.statusDesc)
  673. }
  674. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  675. sm := stream.Method()
  676. if sm != "" && sm[0] == '/' {
  677. sm = sm[1:]
  678. }
  679. pos := strings.LastIndex(sm, "/")
  680. if pos == -1 {
  681. if trInfo != nil {
  682. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  683. trInfo.tr.SetError()
  684. }
  685. if err := t.WriteStatus(stream, codes.InvalidArgument, fmt.Sprintf("malformed method name: %q", stream.Method())); err != nil {
  686. if trInfo != nil {
  687. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  688. trInfo.tr.SetError()
  689. }
  690. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  691. }
  692. if trInfo != nil {
  693. trInfo.tr.Finish()
  694. }
  695. return
  696. }
  697. service := sm[:pos]
  698. method := sm[pos+1:]
  699. srv, ok := s.m[service]
  700. if !ok {
  701. if trInfo != nil {
  702. trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
  703. trInfo.tr.SetError()
  704. }
  705. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown service %v", service)); err != nil {
  706. if trInfo != nil {
  707. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  708. trInfo.tr.SetError()
  709. }
  710. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  711. }
  712. if trInfo != nil {
  713. trInfo.tr.Finish()
  714. }
  715. return
  716. }
  717. // Unary RPC or Streaming RPC?
  718. if md, ok := srv.md[method]; ok {
  719. s.processUnaryRPC(t, stream, srv, md, trInfo)
  720. return
  721. }
  722. if sd, ok := srv.sd[method]; ok {
  723. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  724. return
  725. }
  726. if trInfo != nil {
  727. trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
  728. trInfo.tr.SetError()
  729. }
  730. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown method %v", method)); err != nil {
  731. if trInfo != nil {
  732. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  733. trInfo.tr.SetError()
  734. }
  735. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  736. }
  737. if trInfo != nil {
  738. trInfo.tr.Finish()
  739. }
  740. }
  741. // Stop stops the gRPC server. It immediately closes all open
  742. // connections and listeners.
  743. // It cancels all active RPCs on the server side and the corresponding
  744. // pending RPCs on the client side will get notified by connection
  745. // errors.
  746. func (s *Server) Stop() {
  747. s.mu.Lock()
  748. listeners := s.lis
  749. s.lis = nil
  750. st := s.conns
  751. s.conns = nil
  752. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  753. s.cv.Signal()
  754. s.mu.Unlock()
  755. for lis := range listeners {
  756. lis.Close()
  757. }
  758. for c := range st {
  759. c.Close()
  760. }
  761. s.mu.Lock()
  762. if s.events != nil {
  763. s.events.Finish()
  764. s.events = nil
  765. }
  766. s.mu.Unlock()
  767. }
  768. // GracefulStop stops the gRPC server gracefully. It stops the server to accept new
  769. // connections and RPCs and blocks until all the pending RPCs are finished.
  770. func (s *Server) GracefulStop() {
  771. s.mu.Lock()
  772. defer s.mu.Unlock()
  773. if s.drain == true || s.conns == nil {
  774. return
  775. }
  776. s.drain = true
  777. for lis := range s.lis {
  778. lis.Close()
  779. }
  780. s.lis = nil
  781. for c := range s.conns {
  782. c.(transport.ServerTransport).Drain()
  783. }
  784. for len(s.conns) != 0 {
  785. s.cv.Wait()
  786. }
  787. s.conns = nil
  788. if s.events != nil {
  789. s.events.Finish()
  790. s.events = nil
  791. }
  792. }
  793. func init() {
  794. internal.TestingCloseConns = func(arg interface{}) {
  795. arg.(*Server).testingCloseConns()
  796. }
  797. internal.TestingUseHandlerImpl = func(arg interface{}) {
  798. arg.(*Server).opts.useHandlerImpl = true
  799. }
  800. }
  801. // testingCloseConns closes all existing transports but keeps s.lis
  802. // accepting new connections.
  803. func (s *Server) testingCloseConns() {
  804. s.mu.Lock()
  805. for c := range s.conns {
  806. c.Close()
  807. delete(s.conns, c)
  808. }
  809. s.mu.Unlock()
  810. }
  811. // SendHeader sends header metadata. It may be called at most once from a unary
  812. // RPC handler. The ctx is the RPC handler's Context or one derived from it.
  813. func SendHeader(ctx context.Context, md metadata.MD) error {
  814. if md.Len() == 0 {
  815. return nil
  816. }
  817. stream, ok := transport.StreamFromContext(ctx)
  818. if !ok {
  819. return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  820. }
  821. t := stream.ServerTransport()
  822. if t == nil {
  823. grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
  824. }
  825. if err := t.WriteHeader(stream, md); err != nil {
  826. return toRPCErr(err)
  827. }
  828. return nil
  829. }
  830. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  831. // When called more than once, all the provided metadata will be merged.
  832. // The ctx is the RPC handler's Context or one derived from it.
  833. func SetTrailer(ctx context.Context, md metadata.MD) error {
  834. if md.Len() == 0 {
  835. return nil
  836. }
  837. stream, ok := transport.StreamFromContext(ctx)
  838. if !ok {
  839. return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  840. }
  841. return stream.SetTrailer(md)
  842. }