server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. }
  79. // Server is a gRPC server to serve RPC requests.
  80. type Server struct {
  81. opts options
  82. mu sync.Mutex // guards following
  83. lis map[net.Listener]bool
  84. conns map[io.Closer]bool
  85. m map[string]*service // service name -> service info
  86. events trace.EventLog
  87. }
  88. type options struct {
  89. creds credentials.TransportCredentials
  90. codec Codec
  91. cp Compressor
  92. dc Decompressor
  93. unaryInt UnaryServerInterceptor
  94. streamInt StreamServerInterceptor
  95. maxConcurrentStreams uint32
  96. useHandlerImpl bool // use http.Handler-based server
  97. }
  98. // A ServerOption sets options.
  99. type ServerOption func(*options)
  100. // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
  101. func CustomCodec(codec Codec) ServerOption {
  102. return func(o *options) {
  103. o.codec = codec
  104. }
  105. }
  106. // RPCCompressor returns a ServerOption that sets a compressor for outbound message.
  107. func RPCCompressor(cp Compressor) ServerOption {
  108. return func(o *options) {
  109. o.cp = cp
  110. }
  111. }
  112. // RPCDecompressor returns a ServerOption that sets a decompressor for inbound message.
  113. func RPCDecompressor(dc Decompressor) ServerOption {
  114. return func(o *options) {
  115. o.dc = dc
  116. }
  117. }
  118. // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
  119. // of concurrent streams to each ServerTransport.
  120. func MaxConcurrentStreams(n uint32) ServerOption {
  121. return func(o *options) {
  122. o.maxConcurrentStreams = n
  123. }
  124. }
  125. // Creds returns a ServerOption that sets credentials for server connections.
  126. func Creds(c credentials.TransportCredentials) ServerOption {
  127. return func(o *options) {
  128. o.creds = c
  129. }
  130. }
  131. // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
  132. // server. Only one unary interceptor can be installed. The construction of multiple
  133. // interceptors (e.g., chaining) can be implemented at the caller.
  134. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
  135. return func(o *options) {
  136. if o.unaryInt != nil {
  137. panic("The unary server interceptor has been set.")
  138. }
  139. o.unaryInt = i
  140. }
  141. }
  142. // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
  143. // server. Only one stream interceptor can be installed.
  144. func StreamInterceptor(i StreamServerInterceptor) ServerOption {
  145. return func(o *options) {
  146. if o.streamInt != nil {
  147. panic("The stream server interceptor has been set.")
  148. }
  149. o.streamInt = i
  150. }
  151. }
  152. // NewServer creates a gRPC server which has no service registered and has not
  153. // started to accept requests yet.
  154. func NewServer(opt ...ServerOption) *Server {
  155. var opts options
  156. for _, o := range opt {
  157. o(&opts)
  158. }
  159. if opts.codec == nil {
  160. // Set the default codec.
  161. opts.codec = protoCodec{}
  162. }
  163. s := &Server{
  164. lis: make(map[net.Listener]bool),
  165. opts: opts,
  166. conns: make(map[io.Closer]bool),
  167. m: make(map[string]*service),
  168. }
  169. if EnableTracing {
  170. _, file, line, _ := runtime.Caller(1)
  171. s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
  172. }
  173. return s
  174. }
  175. // printf records an event in s's event log, unless s has been stopped.
  176. // REQUIRES s.mu is held.
  177. func (s *Server) printf(format string, a ...interface{}) {
  178. if s.events != nil {
  179. s.events.Printf(format, a...)
  180. }
  181. }
  182. // errorf records an error in s's event log, unless s has been stopped.
  183. // REQUIRES s.mu is held.
  184. func (s *Server) errorf(format string, a ...interface{}) {
  185. if s.events != nil {
  186. s.events.Errorf(format, a...)
  187. }
  188. }
  189. // RegisterService register a service and its implementation to the gRPC
  190. // server. Called from the IDL generated code. This must be called before
  191. // invoking Serve.
  192. func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
  193. ht := reflect.TypeOf(sd.HandlerType).Elem()
  194. st := reflect.TypeOf(ss)
  195. if !st.Implements(ht) {
  196. grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
  197. }
  198. s.register(sd, ss)
  199. }
  200. func (s *Server) register(sd *ServiceDesc, ss interface{}) {
  201. s.mu.Lock()
  202. defer s.mu.Unlock()
  203. s.printf("RegisterService(%q)", sd.ServiceName)
  204. if _, ok := s.m[sd.ServiceName]; ok {
  205. grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
  206. }
  207. srv := &service{
  208. server: ss,
  209. md: make(map[string]*MethodDesc),
  210. sd: make(map[string]*StreamDesc),
  211. }
  212. for i := range sd.Methods {
  213. d := &sd.Methods[i]
  214. srv.md[d.MethodName] = d
  215. }
  216. for i := range sd.Streams {
  217. d := &sd.Streams[i]
  218. srv.sd[d.StreamName] = d
  219. }
  220. s.m[sd.ServiceName] = srv
  221. }
  222. var (
  223. // ErrServerStopped indicates that the operation is now illegal because of
  224. // the server being stopped.
  225. ErrServerStopped = errors.New("grpc: the server has been stopped")
  226. )
  227. func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  228. if s.opts.creds == nil {
  229. return rawConn, nil, nil
  230. }
  231. return s.opts.creds.ServerHandshake(rawConn)
  232. }
  233. // Serve accepts incoming connections on the listener lis, creating a new
  234. // ServerTransport and service goroutine for each. The service goroutines
  235. // read gRPC requests and then call the registered handlers to reply to them.
  236. // Service returns when lis.Accept fails. lis will be closed when
  237. // this method returns.
  238. func (s *Server) Serve(lis net.Listener) error {
  239. s.mu.Lock()
  240. s.printf("serving")
  241. if s.lis == nil {
  242. s.mu.Unlock()
  243. lis.Close()
  244. return ErrServerStopped
  245. }
  246. s.lis[lis] = true
  247. s.mu.Unlock()
  248. defer func() {
  249. lis.Close()
  250. s.mu.Lock()
  251. delete(s.lis, lis)
  252. s.mu.Unlock()
  253. }()
  254. for {
  255. rawConn, err := lis.Accept()
  256. if err != nil {
  257. s.mu.Lock()
  258. s.printf("done serving; Accept = %v", err)
  259. s.mu.Unlock()
  260. return err
  261. }
  262. // Start a new goroutine to deal with rawConn
  263. // so we don't stall this Accept loop goroutine.
  264. go s.handleRawConn(rawConn)
  265. }
  266. }
  267. // handleRawConn is run in its own goroutine and handles a just-accepted
  268. // connection that has not had any I/O performed on it yet.
  269. func (s *Server) handleRawConn(rawConn net.Conn) {
  270. conn, authInfo, err := s.useTransportAuthenticator(rawConn)
  271. if err != nil {
  272. s.mu.Lock()
  273. s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
  274. s.mu.Unlock()
  275. grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
  276. rawConn.Close()
  277. return
  278. }
  279. s.mu.Lock()
  280. if s.conns == nil {
  281. s.mu.Unlock()
  282. conn.Close()
  283. return
  284. }
  285. s.mu.Unlock()
  286. if s.opts.useHandlerImpl {
  287. s.serveUsingHandler(conn)
  288. } else {
  289. s.serveNewHTTP2Transport(conn, authInfo)
  290. }
  291. }
  292. // serveNewHTTP2Transport sets up a new http/2 transport (using the
  293. // gRPC http2 server transport in transport/http2_server.go) and
  294. // serves streams on it.
  295. // This is run in its own goroutine (it does network I/O in
  296. // transport.NewServerTransport).
  297. func (s *Server) serveNewHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) {
  298. st, err := transport.NewServerTransport("http2", c, s.opts.maxConcurrentStreams, authInfo)
  299. if err != nil {
  300. s.mu.Lock()
  301. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  302. s.mu.Unlock()
  303. c.Close()
  304. grpclog.Println("grpc: Server.Serve failed to create ServerTransport: ", err)
  305. return
  306. }
  307. if !s.addConn(st) {
  308. st.Close()
  309. return
  310. }
  311. s.serveStreams(st)
  312. }
  313. func (s *Server) serveStreams(st transport.ServerTransport) {
  314. defer s.removeConn(st)
  315. defer st.Close()
  316. var wg sync.WaitGroup
  317. st.HandleStreams(func(stream *transport.Stream) {
  318. wg.Add(1)
  319. go func() {
  320. defer wg.Done()
  321. s.handleStream(st, stream, s.traceInfo(st, stream))
  322. }()
  323. })
  324. wg.Wait()
  325. }
  326. var _ http.Handler = (*Server)(nil)
  327. // serveUsingHandler is called from handleRawConn when s is configured
  328. // to handle requests via the http.Handler interface. It sets up a
  329. // net/http.Server to handle the just-accepted conn. The http.Server
  330. // is configured to route all incoming requests (all HTTP/2 streams)
  331. // to ServeHTTP, which creates a new ServerTransport for each stream.
  332. // serveUsingHandler blocks until conn closes.
  333. //
  334. // This codepath is only used when Server.TestingUseHandlerImpl has
  335. // been configured. This lets the end2end tests exercise the ServeHTTP
  336. // method as one of the environment types.
  337. //
  338. // conn is the *tls.Conn that's already been authenticated.
  339. func (s *Server) serveUsingHandler(conn net.Conn) {
  340. if !s.addConn(conn) {
  341. conn.Close()
  342. return
  343. }
  344. defer s.removeConn(conn)
  345. h2s := &http2.Server{
  346. MaxConcurrentStreams: s.opts.maxConcurrentStreams,
  347. }
  348. h2s.ServeConn(conn, &http2.ServeConnOpts{
  349. Handler: s,
  350. })
  351. }
  352. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  353. st, err := transport.NewServerHandlerTransport(w, r)
  354. if err != nil {
  355. http.Error(w, err.Error(), http.StatusInternalServerError)
  356. return
  357. }
  358. if !s.addConn(st) {
  359. st.Close()
  360. return
  361. }
  362. defer s.removeConn(st)
  363. s.serveStreams(st)
  364. }
  365. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  366. // If tracing is not enabled, it returns nil.
  367. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  368. if !EnableTracing {
  369. return nil
  370. }
  371. trInfo = &traceInfo{
  372. tr: trace.New("grpc.Recv."+methodFamily(stream.Method()), stream.Method()),
  373. }
  374. trInfo.firstLine.client = false
  375. trInfo.firstLine.remoteAddr = st.RemoteAddr()
  376. stream.TraceContext(trInfo.tr)
  377. if dl, ok := stream.Context().Deadline(); ok {
  378. trInfo.firstLine.deadline = dl.Sub(time.Now())
  379. }
  380. return trInfo
  381. }
  382. func (s *Server) addConn(c io.Closer) bool {
  383. s.mu.Lock()
  384. defer s.mu.Unlock()
  385. if s.conns == nil {
  386. return false
  387. }
  388. s.conns[c] = true
  389. return true
  390. }
  391. func (s *Server) removeConn(c io.Closer) {
  392. s.mu.Lock()
  393. defer s.mu.Unlock()
  394. if s.conns != nil {
  395. delete(s.conns, c)
  396. }
  397. }
  398. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
  399. var cbuf *bytes.Buffer
  400. if cp != nil {
  401. cbuf = new(bytes.Buffer)
  402. }
  403. p, err := encode(s.opts.codec, msg, cp, cbuf)
  404. if err != nil {
  405. // This typically indicates a fatal issue (e.g., memory
  406. // corruption or hardware faults) the application program
  407. // cannot handle.
  408. //
  409. // TODO(zhaoq): There exist other options also such as only closing the
  410. // faulty stream locally and remotely (Other streams can keep going). Find
  411. // the optimal option.
  412. grpclog.Fatalf("grpc: Server failed to encode response %v", err)
  413. }
  414. return t.Write(stream, p, opts)
  415. }
  416. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
  417. if trInfo != nil {
  418. defer trInfo.tr.Finish()
  419. trInfo.firstLine.client = false
  420. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  421. defer func() {
  422. if err != nil && err != io.EOF {
  423. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  424. trInfo.tr.SetError()
  425. }
  426. }()
  427. }
  428. if s.opts.cp != nil {
  429. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  430. stream.SetSendCompress(s.opts.cp.Type())
  431. }
  432. p := &parser{r: stream}
  433. for {
  434. pf, req, err := p.recvMsg()
  435. if err == io.EOF {
  436. // The entire stream is done (for unary RPC only).
  437. return err
  438. }
  439. if err == io.ErrUnexpectedEOF {
  440. err = transport.StreamError{Code: codes.Internal, Desc: "io.ErrUnexpectedEOF"}
  441. }
  442. if err != nil {
  443. switch err := err.(type) {
  444. case transport.ConnectionError:
  445. // Nothing to do here.
  446. case transport.StreamError:
  447. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  448. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  449. }
  450. default:
  451. panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", err, err))
  452. }
  453. return err
  454. }
  455. if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
  456. switch err := err.(type) {
  457. case transport.StreamError:
  458. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  459. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  460. }
  461. default:
  462. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  463. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  464. }
  465. }
  466. return err
  467. }
  468. statusCode := codes.OK
  469. statusDesc := ""
  470. df := func(v interface{}) error {
  471. if pf == compressionMade {
  472. var err error
  473. req, err = s.opts.dc.Do(bytes.NewReader(req))
  474. if err != nil {
  475. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  476. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  477. }
  478. return err
  479. }
  480. }
  481. if err := s.opts.codec.Unmarshal(req, v); err != nil {
  482. return err
  483. }
  484. if trInfo != nil {
  485. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  486. }
  487. return nil
  488. }
  489. reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
  490. if appErr != nil {
  491. if err, ok := appErr.(rpcError); ok {
  492. statusCode = err.code
  493. statusDesc = err.desc
  494. } else {
  495. statusCode = convertCode(appErr)
  496. statusDesc = appErr.Error()
  497. }
  498. if trInfo != nil && statusCode != codes.OK {
  499. trInfo.tr.LazyLog(stringer(statusDesc), true)
  500. trInfo.tr.SetError()
  501. }
  502. if err := t.WriteStatus(stream, statusCode, statusDesc); err != nil {
  503. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", err)
  504. return err
  505. }
  506. return nil
  507. }
  508. if trInfo != nil {
  509. trInfo.tr.LazyLog(stringer("OK"), false)
  510. }
  511. opts := &transport.Options{
  512. Last: true,
  513. Delay: false,
  514. }
  515. if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
  516. switch err := err.(type) {
  517. case transport.ConnectionError:
  518. // Nothing to do here.
  519. case transport.StreamError:
  520. statusCode = err.Code
  521. statusDesc = err.Desc
  522. default:
  523. statusCode = codes.Unknown
  524. statusDesc = err.Error()
  525. }
  526. return err
  527. }
  528. if trInfo != nil {
  529. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  530. }
  531. return t.WriteStatus(stream, statusCode, statusDesc)
  532. }
  533. }
  534. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
  535. if s.opts.cp != nil {
  536. stream.SetSendCompress(s.opts.cp.Type())
  537. }
  538. ss := &serverStream{
  539. t: t,
  540. s: stream,
  541. p: &parser{r: stream},
  542. codec: s.opts.codec,
  543. cp: s.opts.cp,
  544. dc: s.opts.dc,
  545. trInfo: trInfo,
  546. }
  547. if ss.cp != nil {
  548. ss.cbuf = new(bytes.Buffer)
  549. }
  550. if trInfo != nil {
  551. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  552. defer func() {
  553. ss.mu.Lock()
  554. if err != nil && err != io.EOF {
  555. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  556. ss.trInfo.tr.SetError()
  557. }
  558. ss.trInfo.tr.Finish()
  559. ss.trInfo.tr = nil
  560. ss.mu.Unlock()
  561. }()
  562. }
  563. var appErr error
  564. if s.opts.streamInt == nil {
  565. appErr = sd.Handler(srv.server, ss)
  566. } else {
  567. info := &StreamServerInfo{
  568. FullMethod: stream.Method(),
  569. IsClientStream: sd.ClientStreams,
  570. IsServerStream: sd.ServerStreams,
  571. }
  572. appErr = s.opts.streamInt(srv.server, ss, info, sd.Handler)
  573. }
  574. if appErr != nil {
  575. if err, ok := appErr.(rpcError); ok {
  576. ss.statusCode = err.code
  577. ss.statusDesc = err.desc
  578. } else if err, ok := appErr.(transport.StreamError); ok {
  579. ss.statusCode = err.Code
  580. ss.statusDesc = err.Desc
  581. } else {
  582. ss.statusCode = convertCode(appErr)
  583. ss.statusDesc = appErr.Error()
  584. }
  585. }
  586. if trInfo != nil {
  587. ss.mu.Lock()
  588. if ss.statusCode != codes.OK {
  589. ss.trInfo.tr.LazyLog(stringer(ss.statusDesc), true)
  590. ss.trInfo.tr.SetError()
  591. } else {
  592. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  593. }
  594. ss.mu.Unlock()
  595. }
  596. return t.WriteStatus(ss.s, ss.statusCode, ss.statusDesc)
  597. }
  598. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  599. sm := stream.Method()
  600. if sm != "" && sm[0] == '/' {
  601. sm = sm[1:]
  602. }
  603. pos := strings.LastIndex(sm, "/")
  604. if pos == -1 {
  605. if trInfo != nil {
  606. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  607. trInfo.tr.SetError()
  608. }
  609. if err := t.WriteStatus(stream, codes.InvalidArgument, fmt.Sprintf("malformed method name: %q", stream.Method())); err != nil {
  610. if trInfo != nil {
  611. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  612. trInfo.tr.SetError()
  613. }
  614. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  615. }
  616. if trInfo != nil {
  617. trInfo.tr.Finish()
  618. }
  619. return
  620. }
  621. service := sm[:pos]
  622. method := sm[pos+1:]
  623. srv, ok := s.m[service]
  624. if !ok {
  625. if trInfo != nil {
  626. trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
  627. trInfo.tr.SetError()
  628. }
  629. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown service %v", service)); err != nil {
  630. if trInfo != nil {
  631. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  632. trInfo.tr.SetError()
  633. }
  634. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  635. }
  636. if trInfo != nil {
  637. trInfo.tr.Finish()
  638. }
  639. return
  640. }
  641. // Unary RPC or Streaming RPC?
  642. if md, ok := srv.md[method]; ok {
  643. s.processUnaryRPC(t, stream, srv, md, trInfo)
  644. return
  645. }
  646. if sd, ok := srv.sd[method]; ok {
  647. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  648. return
  649. }
  650. if trInfo != nil {
  651. trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
  652. trInfo.tr.SetError()
  653. }
  654. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown method %v", method)); err != nil {
  655. if trInfo != nil {
  656. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  657. trInfo.tr.SetError()
  658. }
  659. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  660. }
  661. if trInfo != nil {
  662. trInfo.tr.Finish()
  663. }
  664. }
  665. // Stop stops the gRPC server. It immediately closes all open
  666. // connections and listeners.
  667. // It cancels all active RPCs on the server side and the corresponding
  668. // pending RPCs on the client side will get notified by connection
  669. // errors.
  670. func (s *Server) Stop() {
  671. s.mu.Lock()
  672. listeners := s.lis
  673. s.lis = nil
  674. cs := s.conns
  675. s.conns = nil
  676. s.mu.Unlock()
  677. for lis := range listeners {
  678. lis.Close()
  679. }
  680. for c := range cs {
  681. c.Close()
  682. }
  683. s.mu.Lock()
  684. if s.events != nil {
  685. s.events.Finish()
  686. s.events = nil
  687. }
  688. s.mu.Unlock()
  689. }
  690. func init() {
  691. internal.TestingCloseConns = func(arg interface{}) {
  692. arg.(*Server).testingCloseConns()
  693. }
  694. internal.TestingUseHandlerImpl = func(arg interface{}) {
  695. arg.(*Server).opts.useHandlerImpl = true
  696. }
  697. }
  698. // testingCloseConns closes all existing transports but keeps s.lis
  699. // accepting new connections.
  700. func (s *Server) testingCloseConns() {
  701. s.mu.Lock()
  702. for c := range s.conns {
  703. c.Close()
  704. delete(s.conns, c)
  705. }
  706. s.mu.Unlock()
  707. }
  708. // SendHeader sends header metadata. It may be called at most once from a unary
  709. // RPC handler. The ctx is the RPC handler's Context or one derived from it.
  710. func SendHeader(ctx context.Context, md metadata.MD) error {
  711. if md.Len() == 0 {
  712. return nil
  713. }
  714. stream, ok := transport.StreamFromContext(ctx)
  715. if !ok {
  716. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  717. }
  718. t := stream.ServerTransport()
  719. if t == nil {
  720. grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
  721. }
  722. return t.WriteHeader(stream, md)
  723. }
  724. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  725. // It may be called at most once from a unary RPC handler. The ctx is the RPC
  726. // handler's Context or one derived from it.
  727. func SetTrailer(ctx context.Context, md metadata.MD) error {
  728. if md.Len() == 0 {
  729. return nil
  730. }
  731. stream, ok := transport.StreamFromContext(ctx)
  732. if !ok {
  733. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  734. }
  735. return stream.SetTrailer(md)
  736. }