stream.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. "io"
  38. "sync"
  39. "time"
  40. "golang.org/x/net/context"
  41. "golang.org/x/net/trace"
  42. "google.golang.org/grpc/codes"
  43. "google.golang.org/grpc/metadata"
  44. "google.golang.org/grpc/stats"
  45. "google.golang.org/grpc/transport"
  46. )
  47. // StreamHandler defines the handler called by gRPC server to complete the
  48. // execution of a streaming RPC.
  49. type StreamHandler func(srv interface{}, stream ServerStream) error
  50. // StreamDesc represents a streaming RPC service's method specification.
  51. type StreamDesc struct {
  52. StreamName string
  53. Handler StreamHandler
  54. // At least one of these is true.
  55. ServerStreams bool
  56. ClientStreams bool
  57. }
  58. // Stream defines the common interface a client or server stream has to satisfy.
  59. type Stream interface {
  60. // Context returns the context for this stream.
  61. Context() context.Context
  62. // SendMsg blocks until it sends m, the stream is done or the stream
  63. // breaks.
  64. // On error, it aborts the stream and returns an RPC status on client
  65. // side. On server side, it simply returns the error to the caller.
  66. // SendMsg is called by generated code. Also Users can call SendMsg
  67. // directly when it is really needed in their use cases.
  68. SendMsg(m interface{}) error
  69. // RecvMsg blocks until it receives a message or the stream is
  70. // done. On client side, it returns io.EOF when the stream is done. On
  71. // any other error, it aborts the stream and returns an RPC status. On
  72. // server side, it simply returns the error to the caller.
  73. RecvMsg(m interface{}) error
  74. }
  75. // ClientStream defines the interface a client stream has to satisfy.
  76. type ClientStream interface {
  77. // Header returns the header metadata received from the server if there
  78. // is any. It blocks if the metadata is not ready to read.
  79. Header() (metadata.MD, error)
  80. // Trailer returns the trailer metadata from the server, if there is any.
  81. // It must only be called after stream.CloseAndRecv has returned, or
  82. // stream.Recv has returned a non-nil error (including io.EOF).
  83. Trailer() metadata.MD
  84. // CloseSend closes the send direction of the stream. It closes the stream
  85. // when non-nil error is met.
  86. CloseSend() error
  87. Stream
  88. }
  89. // NewClientStream creates a new Stream for the client side. This is called
  90. // by generated code.
  91. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
  92. if cc.dopts.streamInt != nil {
  93. return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
  94. }
  95. return newClientStream(ctx, desc, cc, method, opts...)
  96. }
  97. func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
  98. var (
  99. t transport.ClientTransport
  100. s *transport.Stream
  101. put func()
  102. cancel context.CancelFunc
  103. )
  104. c := defaultCallInfo
  105. if mc, ok := cc.getMethodConfig(method); ok {
  106. c.failFast = !mc.WaitForReady
  107. if mc.Timeout > 0 {
  108. ctx, cancel = context.WithTimeout(ctx, mc.Timeout)
  109. }
  110. }
  111. for _, o := range opts {
  112. if err := o.before(&c); err != nil {
  113. return nil, toRPCErr(err)
  114. }
  115. }
  116. callHdr := &transport.CallHdr{
  117. Host: cc.authority,
  118. Method: method,
  119. Flush: desc.ServerStreams && desc.ClientStreams,
  120. }
  121. if cc.dopts.cp != nil {
  122. callHdr.SendCompress = cc.dopts.cp.Type()
  123. }
  124. var trInfo traceInfo
  125. if EnableTracing {
  126. trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  127. trInfo.firstLine.client = true
  128. if deadline, ok := ctx.Deadline(); ok {
  129. trInfo.firstLine.deadline = deadline.Sub(time.Now())
  130. }
  131. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  132. ctx = trace.NewContext(ctx, trInfo.tr)
  133. defer func() {
  134. if err != nil {
  135. // Need to call tr.finish() if error is returned.
  136. // Because tr will not be returned to caller.
  137. trInfo.tr.LazyPrintf("RPC: [%v]", err)
  138. trInfo.tr.SetError()
  139. trInfo.tr.Finish()
  140. }
  141. }()
  142. }
  143. sh := cc.dopts.copts.StatsHandler
  144. if sh != nil {
  145. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method})
  146. begin := &stats.Begin{
  147. Client: true,
  148. BeginTime: time.Now(),
  149. FailFast: c.failFast,
  150. }
  151. sh.HandleRPC(ctx, begin)
  152. }
  153. defer func() {
  154. if err != nil && sh != nil {
  155. // Only handle end stats if err != nil.
  156. end := &stats.End{
  157. Client: true,
  158. Error: err,
  159. }
  160. sh.HandleRPC(ctx, end)
  161. }
  162. }()
  163. gopts := BalancerGetOptions{
  164. BlockingWait: !c.failFast,
  165. }
  166. for {
  167. t, put, err = cc.getTransport(ctx, gopts)
  168. if err != nil {
  169. // TODO(zhaoq): Probably revisit the error handling.
  170. if _, ok := err.(*rpcError); ok {
  171. return nil, err
  172. }
  173. if err == errConnClosing || err == errConnUnavailable {
  174. if c.failFast {
  175. return nil, Errorf(codes.Unavailable, "%v", err)
  176. }
  177. continue
  178. }
  179. // All the other errors are treated as Internal errors.
  180. return nil, Errorf(codes.Internal, "%v", err)
  181. }
  182. s, err = t.NewStream(ctx, callHdr)
  183. if err != nil {
  184. if put != nil {
  185. put()
  186. put = nil
  187. }
  188. if _, ok := err.(transport.ConnectionError); ok || err == transport.ErrStreamDrain {
  189. if c.failFast {
  190. return nil, toRPCErr(err)
  191. }
  192. continue
  193. }
  194. return nil, toRPCErr(err)
  195. }
  196. break
  197. }
  198. cs := &clientStream{
  199. opts: opts,
  200. c: c,
  201. desc: desc,
  202. codec: cc.dopts.codec,
  203. cp: cc.dopts.cp,
  204. dc: cc.dopts.dc,
  205. maxMsgSize: cc.dopts.maxMsgSize,
  206. cancel: cancel,
  207. put: put,
  208. t: t,
  209. s: s,
  210. p: &parser{r: s},
  211. tracing: EnableTracing,
  212. trInfo: trInfo,
  213. statsCtx: ctx,
  214. statsHandler: cc.dopts.copts.StatsHandler,
  215. }
  216. if cc.dopts.cp != nil {
  217. cs.cbuf = new(bytes.Buffer)
  218. }
  219. // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination
  220. // when there is no pending I/O operations on this stream.
  221. go func() {
  222. select {
  223. case <-t.Error():
  224. // Incur transport error, simply exit.
  225. case <-s.Done():
  226. // TODO: The trace of the RPC is terminated here when there is no pending
  227. // I/O, which is probably not the optimal solution.
  228. if s.StatusCode() == codes.OK {
  229. cs.finish(nil)
  230. } else {
  231. cs.finish(Errorf(s.StatusCode(), "%s", s.StatusDesc()))
  232. }
  233. cs.closeTransportStream(nil)
  234. case <-s.GoAway():
  235. cs.finish(errConnDrain)
  236. cs.closeTransportStream(errConnDrain)
  237. case <-s.Context().Done():
  238. err := s.Context().Err()
  239. cs.finish(err)
  240. cs.closeTransportStream(transport.ContextErr(err))
  241. }
  242. }()
  243. return cs, nil
  244. }
  245. // clientStream implements a client side Stream.
  246. type clientStream struct {
  247. opts []CallOption
  248. c callInfo
  249. t transport.ClientTransport
  250. s *transport.Stream
  251. p *parser
  252. desc *StreamDesc
  253. codec Codec
  254. cp Compressor
  255. cbuf *bytes.Buffer
  256. dc Decompressor
  257. maxMsgSize int
  258. cancel context.CancelFunc
  259. tracing bool // set to EnableTracing when the clientStream is created.
  260. mu sync.Mutex
  261. put func()
  262. closed bool
  263. // trInfo.tr is set when the clientStream is created (if EnableTracing is true),
  264. // and is set to nil when the clientStream's finish method is called.
  265. trInfo traceInfo
  266. // statsCtx keeps the user context for stats handling.
  267. // All stats collection should use the statsCtx (instead of the stream context)
  268. // so that all the generated stats for a particular RPC can be associated in the processing phase.
  269. statsCtx context.Context
  270. statsHandler stats.Handler
  271. }
  272. func (cs *clientStream) Context() context.Context {
  273. return cs.s.Context()
  274. }
  275. func (cs *clientStream) Header() (metadata.MD, error) {
  276. m, err := cs.s.Header()
  277. if err != nil {
  278. if _, ok := err.(transport.ConnectionError); !ok {
  279. cs.closeTransportStream(err)
  280. }
  281. }
  282. return m, err
  283. }
  284. func (cs *clientStream) Trailer() metadata.MD {
  285. return cs.s.Trailer()
  286. }
  287. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  288. if cs.tracing {
  289. cs.mu.Lock()
  290. if cs.trInfo.tr != nil {
  291. cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  292. }
  293. cs.mu.Unlock()
  294. }
  295. // TODO Investigate how to signal the stats handling party.
  296. // generate error stats if err != nil && err != io.EOF?
  297. defer func() {
  298. if err != nil {
  299. cs.finish(err)
  300. }
  301. if err == nil {
  302. return
  303. }
  304. if err == io.EOF {
  305. // Specialize the process for server streaming. SendMesg is only called
  306. // once when creating the stream object. io.EOF needs to be skipped when
  307. // the rpc is early finished (before the stream object is created.).
  308. // TODO: It is probably better to move this into the generated code.
  309. if !cs.desc.ClientStreams && cs.desc.ServerStreams {
  310. err = nil
  311. }
  312. return
  313. }
  314. if _, ok := err.(transport.ConnectionError); !ok {
  315. cs.closeTransportStream(err)
  316. }
  317. err = toRPCErr(err)
  318. }()
  319. var outPayload *stats.OutPayload
  320. if cs.statsHandler != nil {
  321. outPayload = &stats.OutPayload{
  322. Client: true,
  323. }
  324. }
  325. out, err := encode(cs.codec, m, cs.cp, cs.cbuf, outPayload)
  326. defer func() {
  327. if cs.cbuf != nil {
  328. cs.cbuf.Reset()
  329. }
  330. }()
  331. if err != nil {
  332. return Errorf(codes.Internal, "grpc: %v", err)
  333. }
  334. err = cs.t.Write(cs.s, out, &transport.Options{Last: false})
  335. if err == nil && outPayload != nil {
  336. outPayload.SentTime = time.Now()
  337. cs.statsHandler.HandleRPC(cs.statsCtx, outPayload)
  338. }
  339. return err
  340. }
  341. func (cs *clientStream) RecvMsg(m interface{}) (err error) {
  342. defer func() {
  343. if err != nil && cs.statsHandler != nil {
  344. // Only generate End if err != nil.
  345. // If err == nil, it's not the last RecvMsg.
  346. // The last RecvMsg gets either an RPC error or io.EOF.
  347. end := &stats.End{
  348. Client: true,
  349. EndTime: time.Now(),
  350. }
  351. if err != io.EOF {
  352. end.Error = toRPCErr(err)
  353. }
  354. cs.statsHandler.HandleRPC(cs.statsCtx, end)
  355. }
  356. }()
  357. var inPayload *stats.InPayload
  358. if cs.statsHandler != nil {
  359. inPayload = &stats.InPayload{
  360. Client: true,
  361. }
  362. }
  363. err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxMsgSize, inPayload)
  364. defer func() {
  365. // err != nil indicates the termination of the stream.
  366. if err != nil {
  367. cs.finish(err)
  368. }
  369. }()
  370. if err == nil {
  371. if cs.tracing {
  372. cs.mu.Lock()
  373. if cs.trInfo.tr != nil {
  374. cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  375. }
  376. cs.mu.Unlock()
  377. }
  378. if inPayload != nil {
  379. cs.statsHandler.HandleRPC(cs.statsCtx, inPayload)
  380. }
  381. if !cs.desc.ClientStreams || cs.desc.ServerStreams {
  382. return
  383. }
  384. // Special handling for client streaming rpc.
  385. // This recv expects EOF or errors, so we don't collect inPayload.
  386. err = recv(cs.p, cs.codec, cs.s, cs.dc, m, cs.maxMsgSize, nil)
  387. cs.closeTransportStream(err)
  388. if err == nil {
  389. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  390. }
  391. if err == io.EOF {
  392. if cs.s.StatusCode() == codes.OK {
  393. cs.finish(err)
  394. return nil
  395. }
  396. return Errorf(cs.s.StatusCode(), "%s", cs.s.StatusDesc())
  397. }
  398. return toRPCErr(err)
  399. }
  400. if _, ok := err.(transport.ConnectionError); !ok {
  401. cs.closeTransportStream(err)
  402. }
  403. if err == io.EOF {
  404. if cs.s.StatusCode() == codes.OK {
  405. // Returns io.EOF to indicate the end of the stream.
  406. return
  407. }
  408. return Errorf(cs.s.StatusCode(), "%s", cs.s.StatusDesc())
  409. }
  410. return toRPCErr(err)
  411. }
  412. func (cs *clientStream) CloseSend() (err error) {
  413. err = cs.t.Write(cs.s, nil, &transport.Options{Last: true})
  414. defer func() {
  415. if err != nil {
  416. cs.finish(err)
  417. }
  418. }()
  419. if err == nil || err == io.EOF {
  420. return nil
  421. }
  422. if _, ok := err.(transport.ConnectionError); !ok {
  423. cs.closeTransportStream(err)
  424. }
  425. err = toRPCErr(err)
  426. return
  427. }
  428. func (cs *clientStream) closeTransportStream(err error) {
  429. cs.mu.Lock()
  430. if cs.closed {
  431. cs.mu.Unlock()
  432. return
  433. }
  434. cs.closed = true
  435. cs.mu.Unlock()
  436. cs.t.CloseStream(cs.s, err)
  437. }
  438. func (cs *clientStream) finish(err error) {
  439. defer func() {
  440. if cs.cancel != nil {
  441. cs.cancel()
  442. }
  443. }()
  444. cs.mu.Lock()
  445. defer cs.mu.Unlock()
  446. for _, o := range cs.opts {
  447. o.after(&cs.c)
  448. }
  449. if cs.put != nil {
  450. cs.put()
  451. cs.put = nil
  452. }
  453. if !cs.tracing {
  454. return
  455. }
  456. if cs.trInfo.tr != nil {
  457. if err == nil || err == io.EOF {
  458. cs.trInfo.tr.LazyPrintf("RPC: [OK]")
  459. } else {
  460. cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  461. cs.trInfo.tr.SetError()
  462. }
  463. cs.trInfo.tr.Finish()
  464. cs.trInfo.tr = nil
  465. }
  466. }
  467. // ServerStream defines the interface a server stream has to satisfy.
  468. type ServerStream interface {
  469. // SetHeader sets the header metadata. It may be called multiple times.
  470. // When call multiple times, all the provided metadata will be merged.
  471. // All the metadata will be sent out when one of the following happens:
  472. // - ServerStream.SendHeader() is called;
  473. // - The first response is sent out;
  474. // - An RPC status is sent out (error or success).
  475. SetHeader(metadata.MD) error
  476. // SendHeader sends the header metadata.
  477. // The provided md and headers set by SetHeader() will be sent.
  478. // It fails if called multiple times.
  479. SendHeader(metadata.MD) error
  480. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  481. // When called more than once, all the provided metadata will be merged.
  482. SetTrailer(metadata.MD)
  483. Stream
  484. }
  485. // serverStream implements a server side Stream.
  486. type serverStream struct {
  487. t transport.ServerTransport
  488. s *transport.Stream
  489. p *parser
  490. codec Codec
  491. cp Compressor
  492. dc Decompressor
  493. cbuf *bytes.Buffer
  494. maxMsgSize int
  495. statusCode codes.Code
  496. statusDesc string
  497. trInfo *traceInfo
  498. statsHandler stats.Handler
  499. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  500. }
  501. func (ss *serverStream) Context() context.Context {
  502. return ss.s.Context()
  503. }
  504. func (ss *serverStream) SetHeader(md metadata.MD) error {
  505. if md.Len() == 0 {
  506. return nil
  507. }
  508. return ss.s.SetHeader(md)
  509. }
  510. func (ss *serverStream) SendHeader(md metadata.MD) error {
  511. return ss.t.WriteHeader(ss.s, md)
  512. }
  513. func (ss *serverStream) SetTrailer(md metadata.MD) {
  514. if md.Len() == 0 {
  515. return
  516. }
  517. ss.s.SetTrailer(md)
  518. return
  519. }
  520. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  521. defer func() {
  522. if ss.trInfo != nil {
  523. ss.mu.Lock()
  524. if ss.trInfo.tr != nil {
  525. if err == nil {
  526. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  527. } else {
  528. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  529. ss.trInfo.tr.SetError()
  530. }
  531. }
  532. ss.mu.Unlock()
  533. }
  534. }()
  535. var outPayload *stats.OutPayload
  536. if ss.statsHandler != nil {
  537. outPayload = &stats.OutPayload{}
  538. }
  539. out, err := encode(ss.codec, m, ss.cp, ss.cbuf, outPayload)
  540. defer func() {
  541. if ss.cbuf != nil {
  542. ss.cbuf.Reset()
  543. }
  544. }()
  545. if err != nil {
  546. err = Errorf(codes.Internal, "grpc: %v", err)
  547. return err
  548. }
  549. if err := ss.t.Write(ss.s, out, &transport.Options{Last: false}); err != nil {
  550. return toRPCErr(err)
  551. }
  552. if outPayload != nil {
  553. outPayload.SentTime = time.Now()
  554. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload)
  555. }
  556. return nil
  557. }
  558. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  559. defer func() {
  560. if ss.trInfo != nil {
  561. ss.mu.Lock()
  562. if ss.trInfo.tr != nil {
  563. if err == nil {
  564. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  565. } else if err != io.EOF {
  566. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  567. ss.trInfo.tr.SetError()
  568. }
  569. }
  570. ss.mu.Unlock()
  571. }
  572. }()
  573. var inPayload *stats.InPayload
  574. if ss.statsHandler != nil {
  575. inPayload = &stats.InPayload{}
  576. }
  577. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxMsgSize, inPayload); err != nil {
  578. if err == io.EOF {
  579. return err
  580. }
  581. if err == io.ErrUnexpectedEOF {
  582. err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  583. }
  584. return toRPCErr(err)
  585. }
  586. if inPayload != nil {
  587. ss.statsHandler.HandleRPC(ss.s.Context(), inPayload)
  588. }
  589. return nil
  590. }