server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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.Credentials
  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.Credentials) 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. creds, ok := s.opts.creds.(credentials.TransportAuthenticator)
  229. if !ok {
  230. return rawConn, nil, nil
  231. }
  232. return creds.ServerHandshake(rawConn)
  233. }
  234. // Serve accepts incoming connections on the listener lis, creating a new
  235. // ServerTransport and service goroutine for each. The service goroutines
  236. // read gRPC requests and then call the registered handlers to reply to them.
  237. // Service returns when lis.Accept fails. lis will be closed when
  238. // this method returns.
  239. func (s *Server) Serve(lis net.Listener) error {
  240. s.mu.Lock()
  241. s.printf("serving")
  242. if s.lis == nil {
  243. s.mu.Unlock()
  244. lis.Close()
  245. return ErrServerStopped
  246. }
  247. s.lis[lis] = true
  248. s.mu.Unlock()
  249. defer func() {
  250. lis.Close()
  251. s.mu.Lock()
  252. delete(s.lis, lis)
  253. s.mu.Unlock()
  254. }()
  255. for {
  256. rawConn, err := lis.Accept()
  257. if err != nil {
  258. s.mu.Lock()
  259. s.printf("done serving; Accept = %v", err)
  260. s.mu.Unlock()
  261. return err
  262. }
  263. // Start a new goroutine to deal with rawConn
  264. // so we don't stall this Accept loop goroutine.
  265. go s.handleRawConn(rawConn)
  266. }
  267. }
  268. // handleRawConn is run in its own goroutine and handles a just-accepted
  269. // connection that has not had any I/O performed on it yet.
  270. func (s *Server) handleRawConn(rawConn net.Conn) {
  271. conn, authInfo, err := s.useTransportAuthenticator(rawConn)
  272. if err != nil {
  273. s.mu.Lock()
  274. s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
  275. s.mu.Unlock()
  276. grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
  277. rawConn.Close()
  278. return
  279. }
  280. s.mu.Lock()
  281. if s.conns == nil {
  282. s.mu.Unlock()
  283. conn.Close()
  284. return
  285. }
  286. s.mu.Unlock()
  287. if s.opts.useHandlerImpl {
  288. s.serveUsingHandler(conn)
  289. } else {
  290. s.serveNewHTTP2Transport(conn, authInfo)
  291. }
  292. }
  293. // serveNewHTTP2Transport sets up a new http/2 transport (using the
  294. // gRPC http2 server transport in transport/http2_server.go) and
  295. // serves streams on it.
  296. // This is run in its own goroutine (it does network I/O in
  297. // transport.NewServerTransport).
  298. func (s *Server) serveNewHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) {
  299. st, err := transport.NewServerTransport("http2", c, s.opts.maxConcurrentStreams, authInfo)
  300. if err != nil {
  301. s.mu.Lock()
  302. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  303. s.mu.Unlock()
  304. c.Close()
  305. grpclog.Println("grpc: Server.Serve failed to create ServerTransport: ", err)
  306. return
  307. }
  308. if !s.addConn(st) {
  309. st.Close()
  310. return
  311. }
  312. s.serveStreams(st)
  313. }
  314. func (s *Server) serveStreams(st transport.ServerTransport) {
  315. defer s.removeConn(st)
  316. defer st.Close()
  317. var wg sync.WaitGroup
  318. st.HandleStreams(func(stream *transport.Stream) {
  319. wg.Add(1)
  320. go func() {
  321. defer wg.Done()
  322. s.handleStream(st, stream, s.traceInfo(st, stream))
  323. }()
  324. })
  325. wg.Wait()
  326. }
  327. var _ http.Handler = (*Server)(nil)
  328. // serveUsingHandler is called from handleRawConn when s is configured
  329. // to handle requests via the http.Handler interface. It sets up a
  330. // net/http.Server to handle the just-accepted conn. The http.Server
  331. // is configured to route all incoming requests (all HTTP/2 streams)
  332. // to ServeHTTP, which creates a new ServerTransport for each stream.
  333. // serveUsingHandler blocks until conn closes.
  334. //
  335. // This codepath is only used when Server.TestingUseHandlerImpl has
  336. // been configured. This lets the end2end tests exercise the ServeHTTP
  337. // method as one of the environment types.
  338. //
  339. // conn is the *tls.Conn that's already been authenticated.
  340. func (s *Server) serveUsingHandler(conn net.Conn) {
  341. if !s.addConn(conn) {
  342. conn.Close()
  343. return
  344. }
  345. defer s.removeConn(conn)
  346. h2s := &http2.Server{
  347. MaxConcurrentStreams: s.opts.maxConcurrentStreams,
  348. }
  349. h2s.ServeConn(conn, &http2.ServeConnOpts{
  350. Handler: s,
  351. })
  352. }
  353. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  354. st, err := transport.NewServerHandlerTransport(w, r)
  355. if err != nil {
  356. http.Error(w, err.Error(), http.StatusInternalServerError)
  357. return
  358. }
  359. if !s.addConn(st) {
  360. st.Close()
  361. return
  362. }
  363. defer s.removeConn(st)
  364. s.serveStreams(st)
  365. }
  366. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  367. // If tracing is not enabled, it returns nil.
  368. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  369. if !EnableTracing {
  370. return nil
  371. }
  372. trInfo = &traceInfo{
  373. tr: trace.New("grpc.Recv."+methodFamily(stream.Method()), stream.Method()),
  374. }
  375. trInfo.firstLine.client = false
  376. trInfo.firstLine.remoteAddr = st.RemoteAddr()
  377. stream.TraceContext(trInfo.tr)
  378. if dl, ok := stream.Context().Deadline(); ok {
  379. trInfo.firstLine.deadline = dl.Sub(time.Now())
  380. }
  381. return trInfo
  382. }
  383. func (s *Server) addConn(c io.Closer) bool {
  384. s.mu.Lock()
  385. defer s.mu.Unlock()
  386. if s.conns == nil {
  387. return false
  388. }
  389. s.conns[c] = true
  390. return true
  391. }
  392. func (s *Server) removeConn(c io.Closer) {
  393. s.mu.Lock()
  394. defer s.mu.Unlock()
  395. if s.conns != nil {
  396. delete(s.conns, c)
  397. }
  398. }
  399. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
  400. var cbuf *bytes.Buffer
  401. if cp != nil {
  402. cbuf = new(bytes.Buffer)
  403. }
  404. p, err := encode(s.opts.codec, msg, cp, cbuf)
  405. if err != nil {
  406. // This typically indicates a fatal issue (e.g., memory
  407. // corruption or hardware faults) the application program
  408. // cannot handle.
  409. //
  410. // TODO(zhaoq): There exist other options also such as only closing the
  411. // faulty stream locally and remotely (Other streams can keep going). Find
  412. // the optimal option.
  413. grpclog.Fatalf("grpc: Server failed to encode response %v", err)
  414. }
  415. return t.Write(stream, p, opts)
  416. }
  417. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
  418. if trInfo != nil {
  419. defer trInfo.tr.Finish()
  420. trInfo.firstLine.client = false
  421. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  422. defer func() {
  423. if err != nil && err != io.EOF {
  424. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  425. trInfo.tr.SetError()
  426. }
  427. }()
  428. }
  429. if s.opts.cp != nil {
  430. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  431. stream.SetSendCompress(s.opts.cp.Type())
  432. }
  433. p := &parser{r: stream}
  434. for {
  435. pf, req, err := p.recvMsg()
  436. if err == io.EOF {
  437. // The entire stream is done (for unary RPC only).
  438. return err
  439. }
  440. if err == io.ErrUnexpectedEOF {
  441. err = transport.StreamError{Code: codes.Internal, Desc: "io.ErrUnexpectedEOF"}
  442. }
  443. if err != nil {
  444. switch err := err.(type) {
  445. case transport.ConnectionError:
  446. // Nothing to do here.
  447. case transport.StreamError:
  448. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  449. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  450. }
  451. default:
  452. panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", err, err))
  453. }
  454. return err
  455. }
  456. if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
  457. switch err := err.(type) {
  458. case transport.StreamError:
  459. if err := t.WriteStatus(stream, err.Code, err.Desc); err != nil {
  460. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  461. }
  462. default:
  463. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  464. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  465. }
  466. }
  467. return err
  468. }
  469. statusCode := codes.OK
  470. statusDesc := ""
  471. df := func(v interface{}) error {
  472. if pf == compressionMade {
  473. var err error
  474. req, err = s.opts.dc.Do(bytes.NewReader(req))
  475. if err != nil {
  476. if err := t.WriteStatus(stream, codes.Internal, err.Error()); err != nil {
  477. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status %v", err)
  478. }
  479. return err
  480. }
  481. }
  482. if err := s.opts.codec.Unmarshal(req, v); err != nil {
  483. return err
  484. }
  485. if trInfo != nil {
  486. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  487. }
  488. return nil
  489. }
  490. reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
  491. if appErr != nil {
  492. if err, ok := appErr.(rpcError); ok {
  493. statusCode = err.code
  494. statusDesc = err.desc
  495. } else {
  496. statusCode = convertCode(appErr)
  497. statusDesc = appErr.Error()
  498. }
  499. if trInfo != nil && statusCode != codes.OK {
  500. trInfo.tr.LazyLog(stringer(statusDesc), true)
  501. trInfo.tr.SetError()
  502. }
  503. if err := t.WriteStatus(stream, statusCode, statusDesc); err != nil {
  504. grpclog.Printf("grpc: Server.processUnaryRPC failed to write status: %v", err)
  505. return err
  506. }
  507. return nil
  508. }
  509. if trInfo != nil {
  510. trInfo.tr.LazyLog(stringer("OK"), false)
  511. }
  512. opts := &transport.Options{
  513. Last: true,
  514. Delay: false,
  515. }
  516. if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
  517. switch err := err.(type) {
  518. case transport.ConnectionError:
  519. // Nothing to do here.
  520. case transport.StreamError:
  521. statusCode = err.Code
  522. statusDesc = err.Desc
  523. default:
  524. statusCode = codes.Unknown
  525. statusDesc = err.Error()
  526. }
  527. return err
  528. }
  529. if trInfo != nil {
  530. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  531. }
  532. return t.WriteStatus(stream, statusCode, statusDesc)
  533. }
  534. }
  535. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
  536. if s.opts.cp != nil {
  537. stream.SetSendCompress(s.opts.cp.Type())
  538. }
  539. ss := &serverStream{
  540. t: t,
  541. s: stream,
  542. p: &parser{r: stream},
  543. codec: s.opts.codec,
  544. cp: s.opts.cp,
  545. dc: s.opts.dc,
  546. trInfo: trInfo,
  547. }
  548. if ss.cp != nil {
  549. ss.cbuf = new(bytes.Buffer)
  550. }
  551. if trInfo != nil {
  552. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  553. defer func() {
  554. ss.mu.Lock()
  555. if err != nil && err != io.EOF {
  556. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  557. ss.trInfo.tr.SetError()
  558. }
  559. ss.trInfo.tr.Finish()
  560. ss.trInfo.tr = nil
  561. ss.mu.Unlock()
  562. }()
  563. }
  564. var appErr error
  565. if s.opts.streamInt == nil {
  566. appErr = sd.Handler(srv.server, ss)
  567. } else {
  568. info := &StreamServerInfo{
  569. FullMethod: stream.Method(),
  570. IsClientStream: sd.ClientStreams,
  571. IsServerStream: sd.ServerStreams,
  572. }
  573. appErr = s.opts.streamInt(srv.server, ss, info, sd.Handler)
  574. }
  575. if appErr != nil {
  576. if err, ok := appErr.(rpcError); ok {
  577. ss.statusCode = err.code
  578. ss.statusDesc = err.desc
  579. } else if err, ok := appErr.(transport.StreamError); ok {
  580. ss.statusCode = err.Code
  581. ss.statusDesc = err.Desc
  582. } else {
  583. ss.statusCode = convertCode(appErr)
  584. ss.statusDesc = appErr.Error()
  585. }
  586. }
  587. if trInfo != nil {
  588. ss.mu.Lock()
  589. if ss.statusCode != codes.OK {
  590. ss.trInfo.tr.LazyLog(stringer(ss.statusDesc), true)
  591. ss.trInfo.tr.SetError()
  592. } else {
  593. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  594. }
  595. ss.mu.Unlock()
  596. }
  597. return t.WriteStatus(ss.s, ss.statusCode, ss.statusDesc)
  598. }
  599. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  600. sm := stream.Method()
  601. if sm != "" && sm[0] == '/' {
  602. sm = sm[1:]
  603. }
  604. pos := strings.LastIndex(sm, "/")
  605. if pos == -1 {
  606. if trInfo != nil {
  607. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  608. trInfo.tr.SetError()
  609. }
  610. if err := t.WriteStatus(stream, codes.InvalidArgument, fmt.Sprintf("malformed method name: %q", stream.Method())); err != nil {
  611. if trInfo != nil {
  612. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  613. trInfo.tr.SetError()
  614. }
  615. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  616. }
  617. if trInfo != nil {
  618. trInfo.tr.Finish()
  619. }
  620. return
  621. }
  622. service := sm[:pos]
  623. method := sm[pos+1:]
  624. srv, ok := s.m[service]
  625. if !ok {
  626. if trInfo != nil {
  627. trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
  628. trInfo.tr.SetError()
  629. }
  630. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown service %v", service)); err != nil {
  631. if trInfo != nil {
  632. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  633. trInfo.tr.SetError()
  634. }
  635. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  636. }
  637. if trInfo != nil {
  638. trInfo.tr.Finish()
  639. }
  640. return
  641. }
  642. // Unary RPC or Streaming RPC?
  643. if md, ok := srv.md[method]; ok {
  644. s.processUnaryRPC(t, stream, srv, md, trInfo)
  645. return
  646. }
  647. if sd, ok := srv.sd[method]; ok {
  648. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  649. return
  650. }
  651. if trInfo != nil {
  652. trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
  653. trInfo.tr.SetError()
  654. }
  655. if err := t.WriteStatus(stream, codes.Unimplemented, fmt.Sprintf("unknown method %v", method)); err != nil {
  656. if trInfo != nil {
  657. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  658. trInfo.tr.SetError()
  659. }
  660. grpclog.Printf("grpc: Server.handleStream failed to write status: %v", err)
  661. }
  662. if trInfo != nil {
  663. trInfo.tr.Finish()
  664. }
  665. }
  666. // Stop stops the gRPC server. It immediately closes all open
  667. // connections and listeners.
  668. // It cancels all active RPCs on the server side and the corresponding
  669. // pending RPCs on the client side will get notified by connection
  670. // errors.
  671. func (s *Server) Stop() {
  672. s.mu.Lock()
  673. listeners := s.lis
  674. s.lis = nil
  675. cs := s.conns
  676. s.conns = nil
  677. s.mu.Unlock()
  678. for lis := range listeners {
  679. lis.Close()
  680. }
  681. for c := range cs {
  682. c.Close()
  683. }
  684. s.mu.Lock()
  685. if s.events != nil {
  686. s.events.Finish()
  687. s.events = nil
  688. }
  689. s.mu.Unlock()
  690. }
  691. func init() {
  692. internal.TestingCloseConns = func(arg interface{}) {
  693. arg.(*Server).testingCloseConns()
  694. }
  695. internal.TestingUseHandlerImpl = func(arg interface{}) {
  696. arg.(*Server).opts.useHandlerImpl = true
  697. }
  698. }
  699. // testingCloseConns closes all existing transports but keeps s.lis
  700. // accepting new connections.
  701. func (s *Server) testingCloseConns() {
  702. s.mu.Lock()
  703. for c := range s.conns {
  704. c.Close()
  705. delete(s.conns, c)
  706. }
  707. s.mu.Unlock()
  708. }
  709. // SendHeader sends header metadata. It may be called at most once from a unary
  710. // RPC handler. The ctx is the RPC handler's Context or one derived from it.
  711. func SendHeader(ctx context.Context, md metadata.MD) error {
  712. if md.Len() == 0 {
  713. return nil
  714. }
  715. stream, ok := transport.StreamFromContext(ctx)
  716. if !ok {
  717. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  718. }
  719. t := stream.ServerTransport()
  720. if t == nil {
  721. grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
  722. }
  723. return t.WriteHeader(stream, md)
  724. }
  725. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  726. // It may be called at most once from a unary RPC handler. The ctx is the RPC
  727. // handler's Context or one derived from it.
  728. func SetTrailer(ctx context.Context, md metadata.MD) error {
  729. if md.Len() == 0 {
  730. return nil
  731. }
  732. stream, ok := transport.StreamFromContext(ctx)
  733. if !ok {
  734. return fmt.Errorf("grpc: failed to fetch the stream from the context %v", ctx)
  735. }
  736. return stream.SetTrailer(md)
  737. }