server.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. // Service 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. rawConn.Close()
  338. return
  339. }
  340. s.mu.Lock()
  341. if s.conns == nil {
  342. s.mu.Unlock()
  343. conn.Close()
  344. return
  345. }
  346. s.mu.Unlock()
  347. if s.opts.useHandlerImpl {
  348. s.serveUsingHandler(conn)
  349. } else {
  350. s.serveNewHTTP2Transport(conn, authInfo)
  351. }
  352. }
  353. // serveNewHTTP2Transport sets up a new http/2 transport (using the
  354. // gRPC http2 server transport in transport/http2_server.go) and
  355. // serves streams on it.
  356. // This is run in its own goroutine (it does network I/O in
  357. // transport.NewServerTransport).
  358. func (s *Server) serveNewHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) {
  359. st, err := transport.NewServerTransport("http2", c, s.opts.maxConcurrentStreams, authInfo)
  360. if err != nil {
  361. s.mu.Lock()
  362. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  363. s.mu.Unlock()
  364. c.Close()
  365. grpclog.Println("grpc: Server.Serve failed to create ServerTransport: ", err)
  366. return
  367. }
  368. if !s.addConn(st) {
  369. st.Close()
  370. return
  371. }
  372. s.serveStreams(st)
  373. }
  374. func (s *Server) serveStreams(st transport.ServerTransport) {
  375. defer s.removeConn(st)
  376. defer st.Close()
  377. var wg sync.WaitGroup
  378. st.HandleStreams(func(stream *transport.Stream) {
  379. wg.Add(1)
  380. go func() {
  381. defer wg.Done()
  382. s.handleStream(st, stream, s.traceInfo(st, stream))
  383. }()
  384. })
  385. wg.Wait()
  386. }
  387. var _ http.Handler = (*Server)(nil)
  388. // serveUsingHandler is called from handleRawConn when s is configured
  389. // to handle requests via the http.Handler interface. It sets up a
  390. // net/http.Server to handle the just-accepted conn. The http.Server
  391. // is configured to route all incoming requests (all HTTP/2 streams)
  392. // to ServeHTTP, which creates a new ServerTransport for each stream.
  393. // serveUsingHandler blocks until conn closes.
  394. //
  395. // This codepath is only used when Server.TestingUseHandlerImpl has
  396. // been configured. This lets the end2end tests exercise the ServeHTTP
  397. // method as one of the environment types.
  398. //
  399. // conn is the *tls.Conn that's already been authenticated.
  400. func (s *Server) serveUsingHandler(conn net.Conn) {
  401. if !s.addConn(conn) {
  402. conn.Close()
  403. return
  404. }
  405. defer s.removeConn(conn)
  406. h2s := &http2.Server{
  407. MaxConcurrentStreams: s.opts.maxConcurrentStreams,
  408. }
  409. h2s.ServeConn(conn, &http2.ServeConnOpts{
  410. Handler: s,
  411. })
  412. }
  413. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  414. st, err := transport.NewServerHandlerTransport(w, r)
  415. if err != nil {
  416. http.Error(w, err.Error(), http.StatusInternalServerError)
  417. return
  418. }
  419. if !s.addConn(st) {
  420. st.Close()
  421. return
  422. }
  423. defer s.removeConn(st)
  424. s.serveStreams(st)
  425. }
  426. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  427. // If tracing is not enabled, it returns nil.
  428. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  429. if !EnableTracing {
  430. return nil
  431. }
  432. trInfo = &traceInfo{
  433. tr: trace.New("grpc.Recv."+methodFamily(stream.Method()), stream.Method()),
  434. }
  435. trInfo.firstLine.client = false
  436. trInfo.firstLine.remoteAddr = st.RemoteAddr()
  437. stream.TraceContext(trInfo.tr)
  438. if dl, ok := stream.Context().Deadline(); ok {
  439. trInfo.firstLine.deadline = dl.Sub(time.Now())
  440. }
  441. return trInfo
  442. }
  443. func (s *Server) addConn(c io.Closer) bool {
  444. s.mu.Lock()
  445. defer s.mu.Unlock()
  446. if s.conns == nil || s.drain {
  447. return false
  448. }
  449. s.conns[c] = true
  450. return true
  451. }
  452. func (s *Server) removeConn(c io.Closer) {
  453. s.mu.Lock()
  454. defer s.mu.Unlock()
  455. if s.conns != nil {
  456. delete(s.conns, c)
  457. s.cv.Signal()
  458. }
  459. }
  460. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
  461. var cbuf *bytes.Buffer
  462. if cp != nil {
  463. cbuf = new(bytes.Buffer)
  464. }
  465. p, err := encode(s.opts.codec, msg, cp, cbuf)
  466. if err != nil {
  467. // This typically indicates a fatal issue (e.g., memory
  468. // corruption or hardware faults) the application program
  469. // cannot handle.
  470. //
  471. // TODO(zhaoq): There exist other options also such as only closing the
  472. // faulty stream locally and remotely (Other streams can keep going). Find
  473. // the optimal option.
  474. grpclog.Fatalf("grpc: Server failed to encode response %v", err)
  475. }
  476. return t.Write(stream, p, opts)
  477. }
  478. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
  479. if trInfo != nil {
  480. defer trInfo.tr.Finish()
  481. trInfo.firstLine.client = false
  482. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  483. defer func() {
  484. if err != nil && err != io.EOF {
  485. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  486. trInfo.tr.SetError()
  487. }
  488. }()
  489. }
  490. if s.opts.cp != nil {
  491. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  492. stream.SetSendCompress(s.opts.cp.Type())
  493. }
  494. p := &parser{r: stream}
  495. for {
  496. pf, req, err := p.recvMsg(s.opts.maxMsgSize)
  497. if err == io.EOF {
  498. // The entire stream is done (for unary RPC only).
  499. return err
  500. }
  501. if err == io.ErrUnexpectedEOF {
  502. err = transport.StreamError{Code: codes.Internal, Desc: "io.ErrUnexpectedEOF"}
  503. }
  504. if err != nil {
  505. switch err := err.(type) {
  506. case *rpcError:
  507. if err := t.WriteStatus(stream, err.code, err.desc); err != nil {
  508. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  509. }
  510. case transport.ConnectionError:
  511. // Nothing to do here.
  512. case transport.StreamError:
  513. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  514. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  515. }
  516. default:
  517. panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", err, err))
  518. }
  519. return err
  520. }
  521. if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
  522. switch err := err.(type) {
  523. case transport.StreamError:
  524. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  525. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  526. }
  527. default:
  528. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  529. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  530. }
  531. }
  532. return err
  533. }
  534. statusCode := codes.OK
  535. statusDesc := ""
  536. df := func(v interface{}) error {
  537. if pf == compressionMade {
  538. var err error
  539. req, err = s.opts.dc.Do(bytes.NewReader(req))
  540. if err != nil {
  541. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  542. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  543. }
  544. return err
  545. }
  546. }
  547. if len(req) > s.opts.maxMsgSize {
  548. // TODO: Revisit the error code. Currently keep it consistent with
  549. // java implementation.
  550. statusCode = codes.Internal
  551. statusDesc = fmt.Sprintf("grpc: server received a message of %d bytes exceeding %d limit", len(req), s.opts.maxMsgSize)
  552. }
  553. if err := s.opts.codec.Unmarshal(req, v); err != nil {
  554. return err
  555. }
  556. if trInfo != nil {
  557. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  558. }
  559. return nil
  560. }
  561. reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
  562. if appErr != nil {
  563. if err, ok := appErr.(*rpcError); ok {
  564. statusCode = err.code
  565. statusDesc = err.desc
  566. } else {
  567. statusCode = convertCode(appErr)
  568. statusDesc = appErr.Error()
  569. }
  570. if trInfo != nil && statusCode != codes.OK {
  571. trInfo.tr.LazyLog(stringer(statusDesc), true)
  572. trInfo.tr.SetError()
  573. }
  574. if err := t.WriteStatus(stream, statusCode, statusDesc); err != nil {
  575. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", err)
  576. return err
  577. }
  578. return nil
  579. }
  580. if trInfo != nil {
  581. trInfo.tr.LazyLog(stringer("OK"), false)
  582. }
  583. opts := &transport.Options{
  584. Last: true,
  585. Delay: false,
  586. }
  587. if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
  588. switch err := err.(type) {
  589. case transport.ConnectionError:
  590. // Nothing to do here.
  591. case transport.StreamError:
  592. statusCode = err.Code
  593. statusDesc = err.Desc
  594. default:
  595. statusCode = codes.Unknown
  596. statusDesc = err.Error()
  597. }
  598. return err
  599. }
  600. if trInfo != nil {
  601. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  602. }
  603. return t.WriteStatus(stream, statusCode, statusDesc)
  604. }
  605. }
  606. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
  607. if s.opts.cp != nil {
  608. stream.SetSendCompress(s.opts.cp.Type())
  609. }
  610. ss := &serverStream{
  611. t: t,
  612. s: stream,
  613. p: &parser{r: stream},
  614. codec: s.opts.codec,
  615. cp: s.opts.cp,
  616. dc: s.opts.dc,
  617. maxMsgSize: s.opts.maxMsgSize,
  618. trInfo: trInfo,
  619. }
  620. if ss.cp != nil {
  621. ss.cbuf = new(bytes.Buffer)
  622. }
  623. if trInfo != nil {
  624. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  625. defer func() {
  626. ss.mu.Lock()
  627. if err != nil && err != io.EOF {
  628. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  629. ss.trInfo.tr.SetError()
  630. }
  631. ss.trInfo.tr.Finish()
  632. ss.trInfo.tr = nil
  633. ss.mu.Unlock()
  634. }()
  635. }
  636. var appErr error
  637. if s.opts.streamInt == nil {
  638. appErr = sd.Handler(srv.server, ss)
  639. } else {
  640. info := &StreamServerInfo{
  641. FullMethod: stream.Method(),
  642. IsClientStream: sd.ClientStreams,
  643. IsServerStream: sd.ServerStreams,
  644. }
  645. appErr = s.opts.streamInt(srv.server, ss, info, sd.Handler)
  646. }
  647. if appErr != nil {
  648. if err, ok := appErr.(*rpcError); ok {
  649. ss.statusCode = err.code
  650. ss.statusDesc = err.desc
  651. } else if err, ok := appErr.(transport.StreamError); ok {
  652. ss.statusCode = err.Code
  653. ss.statusDesc = err.Desc
  654. } else {
  655. ss.statusCode = convertCode(appErr)
  656. ss.statusDesc = appErr.Error()
  657. }
  658. }
  659. if trInfo != nil {
  660. ss.mu.Lock()
  661. if ss.statusCode != codes.OK {
  662. ss.trInfo.tr.LazyLog(stringer(ss.statusDesc), true)
  663. ss.trInfo.tr.SetError()
  664. } else {
  665. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  666. }
  667. ss.mu.Unlock()
  668. }
  669. return t.WriteStatus(ss.s, ss.statusCode, ss.statusDesc)
  670. }
  671. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  672. sm := stream.Method()
  673. if sm != "" && sm[0] == '/' {
  674. sm = sm[1:]
  675. }
  676. pos := strings.LastIndex(sm, "/")
  677. if pos == -1 {
  678. if trInfo != nil {
  679. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  680. trInfo.tr.SetError()
  681. }
  682. if err := t.WriteStatus(stream, codes.InvalidArgument, fmt.Sprintf("malformed method name: %q", stream.Method())); err != nil {
  683. if trInfo != nil {
  684. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  685. trInfo.tr.SetError()
  686. }
  687. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  688. }
  689. if trInfo != nil {
  690. trInfo.tr.Finish()
  691. }
  692. return
  693. }
  694. service := sm[:pos]
  695. method := sm[pos+1:]
  696. srv, ok := s.m[service]
  697. if !ok {
  698. if trInfo != nil {
  699. trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
  700. trInfo.tr.SetError()
  701. }
  702. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown service %v", service)); err != nil {
  703. if trInfo != nil {
  704. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  705. trInfo.tr.SetError()
  706. }
  707. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  708. }
  709. if trInfo != nil {
  710. trInfo.tr.Finish()
  711. }
  712. return
  713. }
  714. // Unary RPC or Streaming RPC?
  715. if md, ok := srv.md[method]; ok {
  716. s.processUnaryRPC(t, stream, srv, md, trInfo)
  717. return
  718. }
  719. if sd, ok := srv.sd[method]; ok {
  720. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  721. return
  722. }
  723. if trInfo != nil {
  724. trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
  725. trInfo.tr.SetError()
  726. }
  727. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown method %v", method)); err != nil {
  728. if trInfo != nil {
  729. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  730. trInfo.tr.SetError()
  731. }
  732. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  733. }
  734. if trInfo != nil {
  735. trInfo.tr.Finish()
  736. }
  737. }
  738. // Stop stops the gRPC server. It immediately closes all open
  739. // connections and listeners.
  740. // It cancels all active RPCs on the server side and the corresponding
  741. // pending RPCs on the client side will get notified by connection
  742. // errors.
  743. func (s *Server) Stop() {
  744. s.mu.Lock()
  745. listeners := s.lis
  746. s.lis = nil
  747. st := s.conns
  748. s.conns = nil
  749. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  750. s.cv.Signal()
  751. s.mu.Unlock()
  752. for lis := range listeners {
  753. lis.Close()
  754. }
  755. for c := range st {
  756. c.Close()
  757. }
  758. s.mu.Lock()
  759. if s.events != nil {
  760. s.events.Finish()
  761. s.events = nil
  762. }
  763. s.mu.Unlock()
  764. }
  765. // GracefulStop stops the gRPC server gracefully. It stops the server to accept new
  766. // connections and RPCs and blocks until all the pending RPCs are finished.
  767. func (s *Server) GracefulStop() {
  768. s.mu.Lock()
  769. defer s.mu.Unlock()
  770. if s.drain == true || s.conns == nil {
  771. return
  772. }
  773. s.drain = true
  774. for lis := range s.lis {
  775. lis.Close()
  776. }
  777. s.lis = nil
  778. for c := range s.conns {
  779. c.(transport.ServerTransport).Drain()
  780. }
  781. for len(s.conns) != 0 {
  782. s.cv.Wait()
  783. }
  784. s.conns = nil
  785. if s.events != nil {
  786. s.events.Finish()
  787. s.events = nil
  788. }
  789. }
  790. func init() {
  791. internal.TestingCloseConns = func(arg interface{}) {
  792. arg.(*Server).testingCloseConns()
  793. }
  794. internal.TestingUseHandlerImpl = func(arg interface{}) {
  795. arg.(*Server).opts.useHandlerImpl = true
  796. }
  797. }
  798. // testingCloseConns closes all existing transports but keeps s.lis
  799. // accepting new connections.
  800. func (s *Server) testingCloseConns() {
  801. s.mu.Lock()
  802. for c := range s.conns {
  803. c.Close()
  804. delete(s.conns, c)
  805. }
  806. s.mu.Unlock()
  807. }
  808. // SendHeader sends header metadata. It may be called at most once from a unary
  809. // RPC handler. The ctx is the RPC handler's Context or one derived from it.
  810. func SendHeader(ctx context.Context, md metadata.MD) error {
  811. if md.Len() == 0 {
  812. return nil
  813. }
  814. stream, ok := transport.StreamFromContext(ctx)
  815. if !ok {
  816. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  817. }
  818. t := stream.ServerTransport()
  819. if t == nil {
  820. grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
  821. }
  822. return t.WriteHeader(stream, md)
  823. }
  824. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  825. // It may be called at most once from a unary RPC handler. The ctx is the RPC
  826. // handler's Context or one derived from it.
  827. func SetTrailer(ctx context.Context, md metadata.MD) error {
  828. if md.Len() == 0 {
  829. return nil
  830. }
  831. stream, ok := transport.StreamFromContext(ctx)
  832. if !ok {
  833. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  834. }
  835. return stream.SetTrailer(md)
  836. }