stream.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. "math"
  39. "sync"
  40. "time"
  41. "golang.org/x/net/context"
  42. "golang.org/x/net/trace"
  43. "google.golang.org/grpc/codes"
  44. "google.golang.org/grpc/metadata"
  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. var (
  93. t transport.ClientTransport
  94. s *transport.Stream
  95. put func()
  96. )
  97. c := defaultCallInfo
  98. for _, o := range opts {
  99. if err := o.before(&c); err != nil {
  100. return nil, toRPCErr(err)
  101. }
  102. }
  103. callHdr := &transport.CallHdr{
  104. Host: cc.authority,
  105. Method: method,
  106. Flush: desc.ServerStreams && desc.ClientStreams,
  107. }
  108. if cc.dopts.cp != nil {
  109. callHdr.SendCompress = cc.dopts.cp.Type()
  110. }
  111. var trInfo traceInfo
  112. if EnableTracing {
  113. trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method)
  114. trInfo.firstLine.client = true
  115. if deadline, ok := ctx.Deadline(); ok {
  116. trInfo.firstLine.deadline = deadline.Sub(time.Now())
  117. }
  118. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  119. ctx = trace.NewContext(ctx, trInfo.tr)
  120. defer func() {
  121. if err != nil {
  122. // Need to call tr.finish() if error is returned.
  123. // Because tr will not be returned to caller.
  124. trInfo.tr.LazyPrintf("RPC: [%v]", err)
  125. trInfo.tr.SetError()
  126. trInfo.tr.Finish()
  127. }
  128. }()
  129. }
  130. gopts := BalancerGetOptions{
  131. BlockingWait: !c.failFast,
  132. }
  133. for {
  134. t, put, err = cc.getTransport(ctx, gopts)
  135. if err != nil {
  136. // TODO(zhaoq): Probably revisit the error handling.
  137. if _, ok := err.(*rpcError); ok {
  138. return nil, err
  139. }
  140. if err == errConnClosing || err == errConnUnavailable {
  141. if c.failFast {
  142. return nil, Errorf(codes.Unavailable, "%v", err)
  143. }
  144. continue
  145. }
  146. // All the other errors are treated as Internal errors.
  147. return nil, Errorf(codes.Internal, "%v", err)
  148. }
  149. s, err = t.NewStream(ctx, callHdr)
  150. if err != nil {
  151. if put != nil {
  152. put()
  153. put = nil
  154. }
  155. if _, ok := err.(transport.ConnectionError); ok || err == transport.ErrStreamDrain {
  156. if c.failFast {
  157. return nil, toRPCErr(err)
  158. }
  159. continue
  160. }
  161. return nil, toRPCErr(err)
  162. }
  163. break
  164. }
  165. cs := &clientStream{
  166. opts: opts,
  167. c: c,
  168. desc: desc,
  169. codec: cc.dopts.codec,
  170. cp: cc.dopts.cp,
  171. dc: cc.dopts.dc,
  172. put: put,
  173. t: t,
  174. s: s,
  175. p: &parser{r: s},
  176. tracing: EnableTracing,
  177. trInfo: trInfo,
  178. }
  179. if cc.dopts.cp != nil {
  180. cs.cbuf = new(bytes.Buffer)
  181. }
  182. // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination
  183. // when there is no pending I/O operations on this stream.
  184. go func() {
  185. select {
  186. case <-t.Error():
  187. // Incur transport error, simply exit.
  188. case <-s.Done():
  189. // TODO: The trace of the RPC is terminated here when there is no pending
  190. // I/O, which is probably not the optimal solution.
  191. if s.StatusCode() == codes.OK {
  192. cs.finish(nil)
  193. } else {
  194. cs.finish(Errorf(s.StatusCode(), "%s", s.StatusDesc()))
  195. }
  196. cs.closeTransportStream(nil)
  197. case <-s.GoAway():
  198. cs.finish(errConnDrain)
  199. cs.closeTransportStream(errConnDrain)
  200. case <-s.Context().Done():
  201. err := s.Context().Err()
  202. cs.finish(err)
  203. cs.closeTransportStream(transport.ContextErr(err))
  204. }
  205. }()
  206. return cs, nil
  207. }
  208. // clientStream implements a client side Stream.
  209. type clientStream struct {
  210. opts []CallOption
  211. c callInfo
  212. t transport.ClientTransport
  213. s *transport.Stream
  214. p *parser
  215. desc *StreamDesc
  216. codec Codec
  217. cp Compressor
  218. cbuf *bytes.Buffer
  219. dc Decompressor
  220. tracing bool // set to EnableTracing when the clientStream is created.
  221. mu sync.Mutex
  222. put func()
  223. closed bool
  224. // trInfo.tr is set when the clientStream is created (if EnableTracing is true),
  225. // and is set to nil when the clientStream's finish method is called.
  226. trInfo traceInfo
  227. }
  228. func (cs *clientStream) Context() context.Context {
  229. return cs.s.Context()
  230. }
  231. func (cs *clientStream) Header() (metadata.MD, error) {
  232. m, err := cs.s.Header()
  233. if err != nil {
  234. if _, ok := err.(transport.ConnectionError); !ok {
  235. cs.closeTransportStream(err)
  236. }
  237. }
  238. return m, err
  239. }
  240. func (cs *clientStream) Trailer() metadata.MD {
  241. return cs.s.Trailer()
  242. }
  243. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  244. if cs.tracing {
  245. cs.mu.Lock()
  246. if cs.trInfo.tr != nil {
  247. cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  248. }
  249. cs.mu.Unlock()
  250. }
  251. defer func() {
  252. if err != nil {
  253. cs.finish(err)
  254. }
  255. if err == nil {
  256. return
  257. }
  258. if err == io.EOF {
  259. // Specialize the process for server streaming. SendMesg is only called
  260. // once when creating the stream object. io.EOF needs to be skipped when
  261. // the rpc is early finished (before the stream object is created.).
  262. // TODO: It is probably better to move this into the generated code.
  263. if !cs.desc.ClientStreams && cs.desc.ServerStreams {
  264. err = nil
  265. }
  266. return
  267. }
  268. if _, ok := err.(transport.ConnectionError); !ok {
  269. cs.closeTransportStream(err)
  270. }
  271. err = toRPCErr(err)
  272. }()
  273. out, err := encode(cs.codec, m, cs.cp, cs.cbuf)
  274. defer func() {
  275. if cs.cbuf != nil {
  276. cs.cbuf.Reset()
  277. }
  278. }()
  279. if err != nil {
  280. return transport.StreamErrorf(codes.Internal, "grpc: %v", err)
  281. }
  282. return cs.t.Write(cs.s, out, &transport.Options{Last: false})
  283. }
  284. func (cs *clientStream) RecvMsg(m interface{}) (err error) {
  285. err = recv(cs.p, cs.codec, cs.s, cs.dc, m, math.MaxInt32)
  286. defer func() {
  287. // err != nil indicates the termination of the stream.
  288. if err != nil {
  289. cs.finish(err)
  290. }
  291. }()
  292. if err == nil {
  293. if cs.tracing {
  294. cs.mu.Lock()
  295. if cs.trInfo.tr != nil {
  296. cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  297. }
  298. cs.mu.Unlock()
  299. }
  300. if !cs.desc.ClientStreams || cs.desc.ServerStreams {
  301. return
  302. }
  303. // Special handling for client streaming rpc.
  304. err = recv(cs.p, cs.codec, cs.s, cs.dc, m, math.MaxInt32)
  305. cs.closeTransportStream(err)
  306. if err == nil {
  307. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  308. }
  309. if err == io.EOF {
  310. if cs.s.StatusCode() == codes.OK {
  311. cs.finish(err)
  312. return nil
  313. }
  314. return Errorf(cs.s.StatusCode(), "%s", cs.s.StatusDesc())
  315. }
  316. return toRPCErr(err)
  317. }
  318. if _, ok := err.(transport.ConnectionError); !ok {
  319. cs.closeTransportStream(err)
  320. }
  321. if err == io.EOF {
  322. if cs.s.StatusCode() == codes.OK {
  323. // Returns io.EOF to indicate the end of the stream.
  324. return
  325. }
  326. return Errorf(cs.s.StatusCode(), "%s", cs.s.StatusDesc())
  327. }
  328. return toRPCErr(err)
  329. }
  330. func (cs *clientStream) CloseSend() (err error) {
  331. err = cs.t.Write(cs.s, nil, &transport.Options{Last: true})
  332. defer func() {
  333. if err != nil {
  334. cs.finish(err)
  335. }
  336. }()
  337. if err == nil || err == io.EOF {
  338. return nil
  339. }
  340. if _, ok := err.(transport.ConnectionError); !ok {
  341. cs.closeTransportStream(err)
  342. }
  343. err = toRPCErr(err)
  344. return
  345. }
  346. func (cs *clientStream) closeTransportStream(err error) {
  347. cs.mu.Lock()
  348. if cs.closed {
  349. cs.mu.Unlock()
  350. return
  351. }
  352. cs.closed = true
  353. cs.mu.Unlock()
  354. cs.t.CloseStream(cs.s, err)
  355. }
  356. func (cs *clientStream) finish(err error) {
  357. cs.mu.Lock()
  358. defer cs.mu.Unlock()
  359. for _, o := range cs.opts {
  360. o.after(&cs.c)
  361. }
  362. if cs.put != nil {
  363. cs.put()
  364. cs.put = nil
  365. }
  366. if !cs.tracing {
  367. return
  368. }
  369. if cs.trInfo.tr != nil {
  370. if err == nil || err == io.EOF {
  371. cs.trInfo.tr.LazyPrintf("RPC: [OK]")
  372. } else {
  373. cs.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  374. cs.trInfo.tr.SetError()
  375. }
  376. cs.trInfo.tr.Finish()
  377. cs.trInfo.tr = nil
  378. }
  379. }
  380. // ServerStream defines the interface a server stream has to satisfy.
  381. type ServerStream interface {
  382. // SendHeader sends the header metadata. It should not be called
  383. // after SendProto. It fails if called multiple times or if
  384. // called after SendProto.
  385. SendHeader(metadata.MD) error
  386. // SetTrailer sets the trailer metadata which will be sent with the
  387. // RPC status.
  388. SetTrailer(metadata.MD)
  389. Stream
  390. }
  391. // serverStream implements a server side Stream.
  392. type serverStream struct {
  393. t transport.ServerTransport
  394. s *transport.Stream
  395. p *parser
  396. codec Codec
  397. cp Compressor
  398. dc Decompressor
  399. cbuf *bytes.Buffer
  400. maxMsgSize int
  401. statusCode codes.Code
  402. statusDesc string
  403. trInfo *traceInfo
  404. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  405. }
  406. func (ss *serverStream) Context() context.Context {
  407. return ss.s.Context()
  408. }
  409. func (ss *serverStream) SendHeader(md metadata.MD) error {
  410. return ss.t.WriteHeader(ss.s, md)
  411. }
  412. func (ss *serverStream) SetTrailer(md metadata.MD) {
  413. if md.Len() == 0 {
  414. return
  415. }
  416. ss.s.SetTrailer(md)
  417. return
  418. }
  419. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  420. defer func() {
  421. if ss.trInfo != nil {
  422. ss.mu.Lock()
  423. if ss.trInfo.tr != nil {
  424. if err == nil {
  425. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  426. } else {
  427. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  428. ss.trInfo.tr.SetError()
  429. }
  430. }
  431. ss.mu.Unlock()
  432. }
  433. }()
  434. out, err := encode(ss.codec, m, ss.cp, ss.cbuf)
  435. defer func() {
  436. if ss.cbuf != nil {
  437. ss.cbuf.Reset()
  438. }
  439. }()
  440. if err != nil {
  441. err = transport.StreamErrorf(codes.Internal, "grpc: %v", err)
  442. return err
  443. }
  444. return ss.t.Write(ss.s, out, &transport.Options{Last: false})
  445. }
  446. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  447. defer func() {
  448. if ss.trInfo != nil {
  449. ss.mu.Lock()
  450. if ss.trInfo.tr != nil {
  451. if err == nil {
  452. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  453. } else if err != io.EOF {
  454. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  455. ss.trInfo.tr.SetError()
  456. }
  457. }
  458. ss.mu.Unlock()
  459. }
  460. }()
  461. return recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxMsgSize)
  462. }