server.go 22 KB

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