stream.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "context"
  21. "errors"
  22. "io"
  23. "math"
  24. "strconv"
  25. "sync"
  26. "time"
  27. "golang.org/x/net/trace"
  28. "google.golang.org/grpc/balancer"
  29. "google.golang.org/grpc/codes"
  30. "google.golang.org/grpc/encoding"
  31. "google.golang.org/grpc/grpclog"
  32. "google.golang.org/grpc/internal/balancerload"
  33. "google.golang.org/grpc/internal/binarylog"
  34. "google.golang.org/grpc/internal/channelz"
  35. "google.golang.org/grpc/internal/grpcrand"
  36. "google.golang.org/grpc/internal/transport"
  37. "google.golang.org/grpc/metadata"
  38. "google.golang.org/grpc/peer"
  39. "google.golang.org/grpc/stats"
  40. "google.golang.org/grpc/status"
  41. )
  42. // StreamHandler defines the handler called by gRPC server to complete the
  43. // execution of a streaming RPC. If a StreamHandler returns an error, it
  44. // should be produced by the status package, or else gRPC will use
  45. // codes.Unknown as the status code and err.Error() as the status message
  46. // of the RPC.
  47. type StreamHandler func(srv interface{}, stream ServerStream) error
  48. // StreamDesc represents a streaming RPC service's method specification.
  49. type StreamDesc struct {
  50. StreamName string
  51. Handler StreamHandler
  52. // At least one of these is true.
  53. ServerStreams bool
  54. ClientStreams bool
  55. }
  56. // Stream defines the common interface a client or server stream has to satisfy.
  57. //
  58. // Deprecated: See ClientStream and ServerStream documentation instead.
  59. type Stream interface {
  60. // Deprecated: See ClientStream and ServerStream documentation instead.
  61. Context() context.Context
  62. // Deprecated: See ClientStream and ServerStream documentation instead.
  63. SendMsg(m interface{}) error
  64. // Deprecated: See ClientStream and ServerStream documentation instead.
  65. RecvMsg(m interface{}) error
  66. }
  67. // ClientStream defines the client-side behavior of a streaming RPC.
  68. //
  69. // All errors returned from ClientStream methods are compatible with the
  70. // status package.
  71. type ClientStream interface {
  72. // Header returns the header metadata received from the server if there
  73. // is any. It blocks if the metadata is not ready to read.
  74. Header() (metadata.MD, error)
  75. // Trailer returns the trailer metadata from the server, if there is any.
  76. // It must only be called after stream.CloseAndRecv has returned, or
  77. // stream.Recv has returned a non-nil error (including io.EOF).
  78. Trailer() metadata.MD
  79. // CloseSend closes the send direction of the stream. It closes the stream
  80. // when non-nil error is met. It is also not safe to call CloseSend
  81. // concurrently with SendMsg.
  82. CloseSend() error
  83. // Context returns the context for this stream.
  84. //
  85. // It should not be called until after Header or RecvMsg has returned. Once
  86. // called, subsequent client-side retries are disabled.
  87. Context() context.Context
  88. // SendMsg is generally called by generated code. On error, SendMsg aborts
  89. // the stream. If the error was generated by the client, the status is
  90. // returned directly; otherwise, io.EOF is returned and the status of
  91. // the stream may be discovered using RecvMsg.
  92. //
  93. // SendMsg blocks until:
  94. // - There is sufficient flow control to schedule m with the transport, or
  95. // - The stream is done, or
  96. // - The stream breaks.
  97. //
  98. // SendMsg does not wait until the message is received by the server. An
  99. // untimely stream closure may result in lost messages. To ensure delivery,
  100. // users should ensure the RPC completed successfully using RecvMsg.
  101. //
  102. // It is safe to have a goroutine calling SendMsg and another goroutine
  103. // calling RecvMsg on the same stream at the same time, but it is not safe
  104. // to call SendMsg on the same stream in different goroutines. It is also
  105. // not safe to call CloseSend concurrently with SendMsg.
  106. SendMsg(m interface{}) error
  107. // RecvMsg blocks until it receives a message into m or the stream is
  108. // done. It returns io.EOF when the stream completes successfully. On
  109. // any other error, the stream is aborted and the error contains the RPC
  110. // status.
  111. //
  112. // It is safe to have a goroutine calling SendMsg and another goroutine
  113. // calling RecvMsg on the same stream at the same time, but it is not
  114. // safe to call RecvMsg on the same stream in different goroutines.
  115. RecvMsg(m interface{}) error
  116. }
  117. // NewStream creates a new Stream for the client side. This is typically
  118. // called by generated code. ctx is used for the lifetime of the stream.
  119. //
  120. // To ensure resources are not leaked due to the stream returned, one of the following
  121. // actions must be performed:
  122. //
  123. // 1. Call Close on the ClientConn.
  124. // 2. Cancel the context provided.
  125. // 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated
  126. // client-streaming RPC, for instance, might use the helper function
  127. // CloseAndRecv (note that CloseSend does not Recv, therefore is not
  128. // guaranteed to release all resources).
  129. // 4. Receive a non-nil, non-io.EOF error from Header or SendMsg.
  130. //
  131. // If none of the above happen, a goroutine and a context will be leaked, and grpc
  132. // will not call the optionally-configured stats handler with a stats.End message.
  133. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) {
  134. // allow interceptor to see all applicable call options, which means those
  135. // configured as defaults from dial option as well as per-call options
  136. opts = combine(cc.dopts.callOptions, opts)
  137. if cc.dopts.streamInt != nil {
  138. return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...)
  139. }
  140. return newClientStream(ctx, desc, cc, method, opts...)
  141. }
  142. // NewClientStream is a wrapper for ClientConn.NewStream.
  143. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) {
  144. return cc.NewStream(ctx, desc, method, opts...)
  145. }
  146. func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) {
  147. if channelz.IsOn() {
  148. cc.incrCallsStarted()
  149. defer func() {
  150. if err != nil {
  151. cc.incrCallsFailed()
  152. }
  153. }()
  154. }
  155. c := defaultCallInfo()
  156. // Provide an opportunity for the first RPC to see the first service config
  157. // provided by the resolver.
  158. if err := cc.waitForResolvedAddrs(ctx); err != nil {
  159. return nil, err
  160. }
  161. mc := cc.GetMethodConfig(method)
  162. if mc.WaitForReady != nil {
  163. c.failFast = !*mc.WaitForReady
  164. }
  165. // Possible context leak:
  166. // The cancel function for the child context we create will only be called
  167. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  168. // an error is generated by SendMsg.
  169. // https://github.com/grpc/grpc-go/issues/1818.
  170. var cancel context.CancelFunc
  171. if mc.Timeout != nil && *mc.Timeout >= 0 {
  172. ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)
  173. } else {
  174. ctx, cancel = context.WithCancel(ctx)
  175. }
  176. defer func() {
  177. if err != nil {
  178. cancel()
  179. }
  180. }()
  181. for _, o := range opts {
  182. if err := o.before(c); err != nil {
  183. return nil, toRPCErr(err)
  184. }
  185. }
  186. c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize)
  187. c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  188. if err := setCallInfoCodec(c); err != nil {
  189. return nil, err
  190. }
  191. callHdr := &transport.CallHdr{
  192. Host: cc.authority,
  193. Method: method,
  194. ContentSubtype: c.contentSubtype,
  195. }
  196. // Set our outgoing compression according to the UseCompressor CallOption, if
  197. // set. In that case, also find the compressor from the encoding package.
  198. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  199. // if set.
  200. var cp Compressor
  201. var comp encoding.Compressor
  202. if ct := c.compressorType; ct != "" {
  203. callHdr.SendCompress = ct
  204. if ct != encoding.Identity {
  205. comp = encoding.GetCompressor(ct)
  206. if comp == nil {
  207. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  208. }
  209. }
  210. } else if cc.dopts.cp != nil {
  211. callHdr.SendCompress = cc.dopts.cp.Type()
  212. cp = cc.dopts.cp
  213. }
  214. if c.creds != nil {
  215. callHdr.Creds = c.creds
  216. }
  217. var trInfo *traceInfo
  218. if EnableTracing {
  219. trInfo = &traceInfo{
  220. tr: trace.New("grpc.Sent."+methodFamily(method), method),
  221. firstLine: firstLine{
  222. client: true,
  223. },
  224. }
  225. if deadline, ok := ctx.Deadline(); ok {
  226. trInfo.firstLine.deadline = time.Until(deadline)
  227. }
  228. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  229. ctx = trace.NewContext(ctx, trInfo.tr)
  230. }
  231. ctx = newContextWithRPCInfo(ctx, c.failFast, c.codec, cp, comp)
  232. sh := cc.dopts.copts.StatsHandler
  233. var beginTime time.Time
  234. if sh != nil {
  235. ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast})
  236. beginTime = time.Now()
  237. begin := &stats.Begin{
  238. Client: true,
  239. BeginTime: beginTime,
  240. FailFast: c.failFast,
  241. }
  242. sh.HandleRPC(ctx, begin)
  243. }
  244. cs := &clientStream{
  245. callHdr: callHdr,
  246. ctx: ctx,
  247. methodConfig: &mc,
  248. opts: opts,
  249. callInfo: c,
  250. cc: cc,
  251. desc: desc,
  252. codec: c.codec,
  253. cp: cp,
  254. comp: comp,
  255. cancel: cancel,
  256. beginTime: beginTime,
  257. firstAttempt: true,
  258. }
  259. if !cc.dopts.disableRetry {
  260. cs.retryThrottler = cc.retryThrottler.Load().(*retryThrottler)
  261. }
  262. cs.binlog = binarylog.GetMethodLogger(method)
  263. cs.callInfo.stream = cs
  264. // Only this initial attempt has stats/tracing.
  265. // TODO(dfawley): move to newAttempt when per-attempt stats are implemented.
  266. if err := cs.newAttemptLocked(sh, trInfo); err != nil {
  267. cs.finish(err)
  268. return nil, err
  269. }
  270. op := func(a *csAttempt) error { return a.newStream() }
  271. if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) }); err != nil {
  272. cs.finish(err)
  273. return nil, err
  274. }
  275. if cs.binlog != nil {
  276. md, _ := metadata.FromOutgoingContext(ctx)
  277. logEntry := &binarylog.ClientHeader{
  278. OnClientSide: true,
  279. Header: md,
  280. MethodName: method,
  281. Authority: cs.cc.authority,
  282. }
  283. if deadline, ok := ctx.Deadline(); ok {
  284. logEntry.Timeout = time.Until(deadline)
  285. if logEntry.Timeout < 0 {
  286. logEntry.Timeout = 0
  287. }
  288. }
  289. cs.binlog.Log(logEntry)
  290. }
  291. if desc != unaryStreamDesc {
  292. // Listen on cc and stream contexts to cleanup when the user closes the
  293. // ClientConn or cancels the stream context. In all other cases, an error
  294. // should already be injected into the recv buffer by the transport, which
  295. // the client will eventually receive, and then we will cancel the stream's
  296. // context in clientStream.finish.
  297. go func() {
  298. select {
  299. case <-cc.ctx.Done():
  300. cs.finish(ErrClientConnClosing)
  301. case <-ctx.Done():
  302. cs.finish(toRPCErr(ctx.Err()))
  303. }
  304. }()
  305. }
  306. return cs, nil
  307. }
  308. // newAttemptLocked creates a new attempt with a transport.
  309. // If it succeeds, then it replaces clientStream's attempt with this new attempt.
  310. func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo *traceInfo) (retErr error) {
  311. newAttempt := &csAttempt{
  312. cs: cs,
  313. dc: cs.cc.dopts.dc,
  314. statsHandler: sh,
  315. trInfo: trInfo,
  316. }
  317. defer func() {
  318. if retErr != nil {
  319. // This attempt is not set in the clientStream, so it's finish won't
  320. // be called. Call it here for stats and trace in case they are not
  321. // nil.
  322. newAttempt.finish(retErr)
  323. }
  324. }()
  325. if err := cs.ctx.Err(); err != nil {
  326. return toRPCErr(err)
  327. }
  328. t, done, err := cs.cc.getTransport(cs.ctx, cs.callInfo.failFast, cs.callHdr.Method)
  329. if err != nil {
  330. return err
  331. }
  332. if trInfo != nil {
  333. trInfo.firstLine.SetRemoteAddr(t.RemoteAddr())
  334. }
  335. newAttempt.t = t
  336. newAttempt.done = done
  337. cs.attempt = newAttempt
  338. return nil
  339. }
  340. func (a *csAttempt) newStream() error {
  341. cs := a.cs
  342. cs.callHdr.PreviousAttempts = cs.numRetries
  343. s, err := a.t.NewStream(cs.ctx, cs.callHdr)
  344. if err != nil {
  345. return toRPCErr(err)
  346. }
  347. cs.attempt.s = s
  348. cs.attempt.p = &parser{r: s}
  349. return nil
  350. }
  351. // clientStream implements a client side Stream.
  352. type clientStream struct {
  353. callHdr *transport.CallHdr
  354. opts []CallOption
  355. callInfo *callInfo
  356. cc *ClientConn
  357. desc *StreamDesc
  358. codec baseCodec
  359. cp Compressor
  360. comp encoding.Compressor
  361. cancel context.CancelFunc // cancels all attempts
  362. sentLast bool // sent an end stream
  363. beginTime time.Time
  364. methodConfig *MethodConfig
  365. ctx context.Context // the application's context, wrapped by stats/tracing
  366. retryThrottler *retryThrottler // The throttler active when the RPC began.
  367. binlog *binarylog.MethodLogger // Binary logger, can be nil.
  368. // serverHeaderBinlogged is a boolean for whether server header has been
  369. // logged. Server header will be logged when the first time one of those
  370. // happens: stream.Header(), stream.Recv().
  371. //
  372. // It's only read and used by Recv() and Header(), so it doesn't need to be
  373. // synchronized.
  374. serverHeaderBinlogged bool
  375. mu sync.Mutex
  376. firstAttempt bool // if true, transparent retry is valid
  377. numRetries int // exclusive of transparent retry attempt(s)
  378. numRetriesSincePushback int // retries since pushback; to reset backoff
  379. finished bool // TODO: replace with atomic cmpxchg or sync.Once?
  380. // attempt is the active client stream attempt.
  381. // The only place where it is written is the newAttemptLocked method and this method never writes nil.
  382. // So, attempt can be nil only inside newClientStream function when clientStream is first created.
  383. // One of the first things done after clientStream's creation, is to call newAttemptLocked which either
  384. // assigns a non nil value to the attempt or returns an error. If an error is returned from newAttemptLocked,
  385. // then newClientStream calls finish on the clientStream and returns. So, finish method is the only
  386. // place where we need to check if the attempt is nil.
  387. attempt *csAttempt
  388. // TODO(hedging): hedging will have multiple attempts simultaneously.
  389. committed bool // active attempt committed for retry?
  390. buffer []func(a *csAttempt) error // operations to replay on retry
  391. bufferSize int // current size of buffer
  392. }
  393. // csAttempt implements a single transport stream attempt within a
  394. // clientStream.
  395. type csAttempt struct {
  396. cs *clientStream
  397. t transport.ClientTransport
  398. s *transport.Stream
  399. p *parser
  400. done func(balancer.DoneInfo)
  401. finished bool
  402. dc Decompressor
  403. decomp encoding.Compressor
  404. decompSet bool
  405. mu sync.Mutex // guards trInfo.tr
  406. // trInfo may be nil (if EnableTracing is false).
  407. // trInfo.tr is set when created (if EnableTracing is true),
  408. // and cleared when the finish method is called.
  409. trInfo *traceInfo
  410. statsHandler stats.Handler
  411. }
  412. func (cs *clientStream) commitAttemptLocked() {
  413. cs.committed = true
  414. cs.buffer = nil
  415. }
  416. func (cs *clientStream) commitAttempt() {
  417. cs.mu.Lock()
  418. cs.commitAttemptLocked()
  419. cs.mu.Unlock()
  420. }
  421. // shouldRetry returns nil if the RPC should be retried; otherwise it returns
  422. // the error that should be returned by the operation.
  423. func (cs *clientStream) shouldRetry(err error) error {
  424. if cs.attempt.s == nil && !cs.callInfo.failFast {
  425. // In the event of any error from NewStream (attempt.s == nil), we
  426. // never attempted to write anything to the wire, so we can retry
  427. // indefinitely for non-fail-fast RPCs.
  428. return nil
  429. }
  430. if cs.finished || cs.committed {
  431. // RPC is finished or committed; cannot retry.
  432. return err
  433. }
  434. // Wait for the trailers.
  435. if cs.attempt.s != nil {
  436. <-cs.attempt.s.Done()
  437. }
  438. if cs.firstAttempt && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) {
  439. // First attempt, stream unprocessed: transparently retry.
  440. cs.firstAttempt = false
  441. return nil
  442. }
  443. cs.firstAttempt = false
  444. if cs.cc.dopts.disableRetry {
  445. return err
  446. }
  447. pushback := 0
  448. hasPushback := false
  449. if cs.attempt.s != nil {
  450. if to, toErr := cs.attempt.s.TrailersOnly(); toErr != nil || !to {
  451. return err
  452. }
  453. // TODO(retry): Move down if the spec changes to not check server pushback
  454. // before considering this a failure for throttling.
  455. sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"]
  456. if len(sps) == 1 {
  457. var e error
  458. if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 {
  459. grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0])
  460. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  461. return err
  462. }
  463. hasPushback = true
  464. } else if len(sps) > 1 {
  465. grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps)
  466. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  467. return err
  468. }
  469. }
  470. var code codes.Code
  471. if cs.attempt.s != nil {
  472. code = cs.attempt.s.Status().Code()
  473. } else {
  474. code = status.Convert(err).Code()
  475. }
  476. rp := cs.methodConfig.retryPolicy
  477. if rp == nil || !rp.retryableStatusCodes[code] {
  478. return err
  479. }
  480. // Note: the ordering here is important; we count this as a failure
  481. // only if the code matched a retryable code.
  482. if cs.retryThrottler.throttle() {
  483. return err
  484. }
  485. if cs.numRetries+1 >= rp.maxAttempts {
  486. return err
  487. }
  488. var dur time.Duration
  489. if hasPushback {
  490. dur = time.Millisecond * time.Duration(pushback)
  491. cs.numRetriesSincePushback = 0
  492. } else {
  493. fact := math.Pow(rp.backoffMultiplier, float64(cs.numRetriesSincePushback))
  494. cur := float64(rp.initialBackoff) * fact
  495. if max := float64(rp.maxBackoff); cur > max {
  496. cur = max
  497. }
  498. dur = time.Duration(grpcrand.Int63n(int64(cur)))
  499. cs.numRetriesSincePushback++
  500. }
  501. // TODO(dfawley): we could eagerly fail here if dur puts us past the
  502. // deadline, but unsure if it is worth doing.
  503. t := time.NewTimer(dur)
  504. select {
  505. case <-t.C:
  506. cs.numRetries++
  507. return nil
  508. case <-cs.ctx.Done():
  509. t.Stop()
  510. return status.FromContextError(cs.ctx.Err()).Err()
  511. }
  512. }
  513. // Returns nil if a retry was performed and succeeded; error otherwise.
  514. func (cs *clientStream) retryLocked(lastErr error) error {
  515. for {
  516. cs.attempt.finish(lastErr)
  517. if err := cs.shouldRetry(lastErr); err != nil {
  518. cs.commitAttemptLocked()
  519. return err
  520. }
  521. if err := cs.newAttemptLocked(nil, nil); err != nil {
  522. return err
  523. }
  524. if lastErr = cs.replayBufferLocked(); lastErr == nil {
  525. return nil
  526. }
  527. }
  528. }
  529. func (cs *clientStream) Context() context.Context {
  530. cs.commitAttempt()
  531. // No need to lock before using attempt, since we know it is committed and
  532. // cannot change.
  533. return cs.attempt.s.Context()
  534. }
  535. func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error {
  536. cs.mu.Lock()
  537. for {
  538. if cs.committed {
  539. cs.mu.Unlock()
  540. return op(cs.attempt)
  541. }
  542. a := cs.attempt
  543. cs.mu.Unlock()
  544. err := op(a)
  545. cs.mu.Lock()
  546. if a != cs.attempt {
  547. // We started another attempt already.
  548. continue
  549. }
  550. if err == io.EOF {
  551. <-a.s.Done()
  552. }
  553. if err == nil || (err == io.EOF && a.s.Status().Code() == codes.OK) {
  554. onSuccess()
  555. cs.mu.Unlock()
  556. return err
  557. }
  558. if err := cs.retryLocked(err); err != nil {
  559. cs.mu.Unlock()
  560. return err
  561. }
  562. }
  563. }
  564. func (cs *clientStream) Header() (metadata.MD, error) {
  565. var m metadata.MD
  566. err := cs.withRetry(func(a *csAttempt) error {
  567. var err error
  568. m, err = a.s.Header()
  569. return toRPCErr(err)
  570. }, cs.commitAttemptLocked)
  571. if err != nil {
  572. cs.finish(err)
  573. return nil, err
  574. }
  575. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  576. // Only log if binary log is on and header has not been logged.
  577. logEntry := &binarylog.ServerHeader{
  578. OnClientSide: true,
  579. Header: m,
  580. PeerAddr: nil,
  581. }
  582. if peer, ok := peer.FromContext(cs.Context()); ok {
  583. logEntry.PeerAddr = peer.Addr
  584. }
  585. cs.binlog.Log(logEntry)
  586. cs.serverHeaderBinlogged = true
  587. }
  588. return m, err
  589. }
  590. func (cs *clientStream) Trailer() metadata.MD {
  591. // On RPC failure, we never need to retry, because usage requires that
  592. // RecvMsg() returned a non-nil error before calling this function is valid.
  593. // We would have retried earlier if necessary.
  594. //
  595. // Commit the attempt anyway, just in case users are not following those
  596. // directions -- it will prevent races and should not meaningfully impact
  597. // performance.
  598. cs.commitAttempt()
  599. if cs.attempt.s == nil {
  600. return nil
  601. }
  602. return cs.attempt.s.Trailer()
  603. }
  604. func (cs *clientStream) replayBufferLocked() error {
  605. a := cs.attempt
  606. for _, f := range cs.buffer {
  607. if err := f(a); err != nil {
  608. return err
  609. }
  610. }
  611. return nil
  612. }
  613. func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error) {
  614. // Note: we still will buffer if retry is disabled (for transparent retries).
  615. if cs.committed {
  616. return
  617. }
  618. cs.bufferSize += sz
  619. if cs.bufferSize > cs.callInfo.maxRetryRPCBufferSize {
  620. cs.commitAttemptLocked()
  621. return
  622. }
  623. cs.buffer = append(cs.buffer, op)
  624. }
  625. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  626. defer func() {
  627. if err != nil && err != io.EOF {
  628. // Call finish on the client stream for errors generated by this SendMsg
  629. // call, as these indicate problems created by this client. (Transport
  630. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  631. // error will be returned from RecvMsg eventually in that case, or be
  632. // retried.)
  633. cs.finish(err)
  634. }
  635. }()
  636. if cs.sentLast {
  637. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  638. }
  639. if !cs.desc.ClientStreams {
  640. cs.sentLast = true
  641. }
  642. // load hdr, payload, data
  643. hdr, payload, data, err := prepareMsg(m, cs.codec, cs.cp, cs.comp)
  644. if err != nil {
  645. return err
  646. }
  647. // TODO(dfawley): should we be checking len(data) instead?
  648. if len(payload) > *cs.callInfo.maxSendMessageSize {
  649. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize)
  650. }
  651. msgBytes := data // Store the pointer before setting to nil. For binary logging.
  652. op := func(a *csAttempt) error {
  653. err := a.sendMsg(m, hdr, payload, data)
  654. // nil out the message and uncomp when replaying; they are only needed for
  655. // stats which is disabled for subsequent attempts.
  656. m, data = nil, nil
  657. return err
  658. }
  659. err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) })
  660. if cs.binlog != nil && err == nil {
  661. cs.binlog.Log(&binarylog.ClientMessage{
  662. OnClientSide: true,
  663. Message: msgBytes,
  664. })
  665. }
  666. return
  667. }
  668. func (cs *clientStream) RecvMsg(m interface{}) error {
  669. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  670. // Call Header() to binary log header if it's not already logged.
  671. cs.Header()
  672. }
  673. var recvInfo *payloadInfo
  674. if cs.binlog != nil {
  675. recvInfo = &payloadInfo{}
  676. }
  677. err := cs.withRetry(func(a *csAttempt) error {
  678. return a.recvMsg(m, recvInfo)
  679. }, cs.commitAttemptLocked)
  680. if cs.binlog != nil && err == nil {
  681. cs.binlog.Log(&binarylog.ServerMessage{
  682. OnClientSide: true,
  683. Message: recvInfo.uncompressedBytes,
  684. })
  685. }
  686. if err != nil || !cs.desc.ServerStreams {
  687. // err != nil or non-server-streaming indicates end of stream.
  688. cs.finish(err)
  689. if cs.binlog != nil {
  690. // finish will not log Trailer. Log Trailer here.
  691. logEntry := &binarylog.ServerTrailer{
  692. OnClientSide: true,
  693. Trailer: cs.Trailer(),
  694. Err: err,
  695. }
  696. if logEntry.Err == io.EOF {
  697. logEntry.Err = nil
  698. }
  699. if peer, ok := peer.FromContext(cs.Context()); ok {
  700. logEntry.PeerAddr = peer.Addr
  701. }
  702. cs.binlog.Log(logEntry)
  703. }
  704. }
  705. return err
  706. }
  707. func (cs *clientStream) CloseSend() error {
  708. if cs.sentLast {
  709. // TODO: return an error and finish the stream instead, due to API misuse?
  710. return nil
  711. }
  712. cs.sentLast = true
  713. op := func(a *csAttempt) error {
  714. a.t.Write(a.s, nil, nil, &transport.Options{Last: true})
  715. // Always return nil; io.EOF is the only error that might make sense
  716. // instead, but there is no need to signal the client to call RecvMsg
  717. // as the only use left for the stream after CloseSend is to call
  718. // RecvMsg. This also matches historical behavior.
  719. return nil
  720. }
  721. cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) })
  722. if cs.binlog != nil {
  723. cs.binlog.Log(&binarylog.ClientHalfClose{
  724. OnClientSide: true,
  725. })
  726. }
  727. // We never returned an error here for reasons.
  728. return nil
  729. }
  730. func (cs *clientStream) finish(err error) {
  731. if err == io.EOF {
  732. // Ending a stream with EOF indicates a success.
  733. err = nil
  734. }
  735. cs.mu.Lock()
  736. if cs.finished {
  737. cs.mu.Unlock()
  738. return
  739. }
  740. cs.finished = true
  741. cs.commitAttemptLocked()
  742. cs.mu.Unlock()
  743. // For binary logging. only log cancel in finish (could be caused by RPC ctx
  744. // canceled or ClientConn closed). Trailer will be logged in RecvMsg.
  745. //
  746. // Only one of cancel or trailer needs to be logged. In the cases where
  747. // users don't call RecvMsg, users must have already canceled the RPC.
  748. if cs.binlog != nil && status.Code(err) == codes.Canceled {
  749. cs.binlog.Log(&binarylog.Cancel{
  750. OnClientSide: true,
  751. })
  752. }
  753. if err == nil {
  754. cs.retryThrottler.successfulRPC()
  755. }
  756. if channelz.IsOn() {
  757. if err != nil {
  758. cs.cc.incrCallsFailed()
  759. } else {
  760. cs.cc.incrCallsSucceeded()
  761. }
  762. }
  763. if cs.attempt != nil {
  764. cs.attempt.finish(err)
  765. // after functions all rely upon having a stream.
  766. if cs.attempt.s != nil {
  767. for _, o := range cs.opts {
  768. o.after(cs.callInfo)
  769. }
  770. }
  771. }
  772. cs.cancel()
  773. }
  774. func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error {
  775. cs := a.cs
  776. if a.trInfo != nil {
  777. a.mu.Lock()
  778. if a.trInfo.tr != nil {
  779. a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  780. }
  781. a.mu.Unlock()
  782. }
  783. if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil {
  784. if !cs.desc.ClientStreams {
  785. // For non-client-streaming RPCs, we return nil instead of EOF on error
  786. // because the generated code requires it. finish is not called; RecvMsg()
  787. // will call it with the stream's status independently.
  788. return nil
  789. }
  790. return io.EOF
  791. }
  792. if a.statsHandler != nil {
  793. a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now()))
  794. }
  795. if channelz.IsOn() {
  796. a.t.IncrMsgSent()
  797. }
  798. return nil
  799. }
  800. func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) {
  801. cs := a.cs
  802. if a.statsHandler != nil && payInfo == nil {
  803. payInfo = &payloadInfo{}
  804. }
  805. if !a.decompSet {
  806. // Block until we receive headers containing received message encoding.
  807. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  808. if a.dc == nil || a.dc.Type() != ct {
  809. // No configured decompressor, or it does not match the incoming
  810. // message encoding; attempt to find a registered compressor that does.
  811. a.dc = nil
  812. a.decomp = encoding.GetCompressor(ct)
  813. }
  814. } else {
  815. // No compression is used; disable our decompressor.
  816. a.dc = nil
  817. }
  818. // Only initialize this state once per stream.
  819. a.decompSet = true
  820. }
  821. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, payInfo, a.decomp)
  822. if err != nil {
  823. if err == io.EOF {
  824. if statusErr := a.s.Status().Err(); statusErr != nil {
  825. return statusErr
  826. }
  827. return io.EOF // indicates successful end of stream.
  828. }
  829. return toRPCErr(err)
  830. }
  831. if a.trInfo != nil {
  832. a.mu.Lock()
  833. if a.trInfo.tr != nil {
  834. a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  835. }
  836. a.mu.Unlock()
  837. }
  838. if a.statsHandler != nil {
  839. a.statsHandler.HandleRPC(cs.ctx, &stats.InPayload{
  840. Client: true,
  841. RecvTime: time.Now(),
  842. Payload: m,
  843. // TODO truncate large payload.
  844. Data: payInfo.uncompressedBytes,
  845. WireLength: payInfo.wireLength,
  846. Length: len(payInfo.uncompressedBytes),
  847. })
  848. }
  849. if channelz.IsOn() {
  850. a.t.IncrMsgRecv()
  851. }
  852. if cs.desc.ServerStreams {
  853. // Subsequent messages should be received by subsequent RecvMsg calls.
  854. return nil
  855. }
  856. // Special handling for non-server-stream rpcs.
  857. // This recv expects EOF or errors, so we don't collect inPayload.
  858. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp)
  859. if err == nil {
  860. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  861. }
  862. if err == io.EOF {
  863. return a.s.Status().Err() // non-server streaming Recv returns nil on success
  864. }
  865. return toRPCErr(err)
  866. }
  867. func (a *csAttempt) finish(err error) {
  868. a.mu.Lock()
  869. if a.finished {
  870. a.mu.Unlock()
  871. return
  872. }
  873. a.finished = true
  874. if err == io.EOF {
  875. // Ending a stream with EOF indicates a success.
  876. err = nil
  877. }
  878. var tr metadata.MD
  879. if a.s != nil {
  880. a.t.CloseStream(a.s, err)
  881. tr = a.s.Trailer()
  882. }
  883. if a.done != nil {
  884. br := false
  885. if a.s != nil {
  886. br = a.s.BytesReceived()
  887. }
  888. a.done(balancer.DoneInfo{
  889. Err: err,
  890. Trailer: tr,
  891. BytesSent: a.s != nil,
  892. BytesReceived: br,
  893. ServerLoad: balancerload.Parse(tr),
  894. })
  895. }
  896. if a.statsHandler != nil {
  897. end := &stats.End{
  898. Client: true,
  899. BeginTime: a.cs.beginTime,
  900. EndTime: time.Now(),
  901. Trailer: tr,
  902. Error: err,
  903. }
  904. a.statsHandler.HandleRPC(a.cs.ctx, end)
  905. }
  906. if a.trInfo != nil && a.trInfo.tr != nil {
  907. if err == nil {
  908. a.trInfo.tr.LazyPrintf("RPC: [OK]")
  909. } else {
  910. a.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  911. a.trInfo.tr.SetError()
  912. }
  913. a.trInfo.tr.Finish()
  914. a.trInfo.tr = nil
  915. }
  916. a.mu.Unlock()
  917. }
  918. // newClientStream creates a ClientStream with the specified transport, on the
  919. // given addrConn.
  920. //
  921. // It's expected that the given transport is either the same one in addrConn, or
  922. // is already closed. To avoid race, transport is specified separately, instead
  923. // of using ac.transpot.
  924. //
  925. // Main difference between this and ClientConn.NewStream:
  926. // - no retry
  927. // - no service config (or wait for service config)
  928. // - no tracing or stats
  929. func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, ac *addrConn, opts ...CallOption) (_ ClientStream, err error) {
  930. if t == nil {
  931. // TODO: return RPC error here?
  932. return nil, errors.New("transport provided is nil")
  933. }
  934. // defaultCallInfo contains unnecessary info(i.e. failfast, maxRetryRPCBufferSize), so we just initialize an empty struct.
  935. c := &callInfo{}
  936. // Possible context leak:
  937. // The cancel function for the child context we create will only be called
  938. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  939. // an error is generated by SendMsg.
  940. // https://github.com/grpc/grpc-go/issues/1818.
  941. ctx, cancel := context.WithCancel(ctx)
  942. defer func() {
  943. if err != nil {
  944. cancel()
  945. }
  946. }()
  947. for _, o := range opts {
  948. if err := o.before(c); err != nil {
  949. return nil, toRPCErr(err)
  950. }
  951. }
  952. c.maxReceiveMessageSize = getMaxSize(nil, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  953. c.maxSendMessageSize = getMaxSize(nil, c.maxSendMessageSize, defaultServerMaxSendMessageSize)
  954. if err := setCallInfoCodec(c); err != nil {
  955. return nil, err
  956. }
  957. callHdr := &transport.CallHdr{
  958. Host: ac.cc.authority,
  959. Method: method,
  960. ContentSubtype: c.contentSubtype,
  961. }
  962. // Set our outgoing compression according to the UseCompressor CallOption, if
  963. // set. In that case, also find the compressor from the encoding package.
  964. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  965. // if set.
  966. var cp Compressor
  967. var comp encoding.Compressor
  968. if ct := c.compressorType; ct != "" {
  969. callHdr.SendCompress = ct
  970. if ct != encoding.Identity {
  971. comp = encoding.GetCompressor(ct)
  972. if comp == nil {
  973. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  974. }
  975. }
  976. } else if ac.cc.dopts.cp != nil {
  977. callHdr.SendCompress = ac.cc.dopts.cp.Type()
  978. cp = ac.cc.dopts.cp
  979. }
  980. if c.creds != nil {
  981. callHdr.Creds = c.creds
  982. }
  983. // Use a special addrConnStream to avoid retry.
  984. as := &addrConnStream{
  985. callHdr: callHdr,
  986. ac: ac,
  987. ctx: ctx,
  988. cancel: cancel,
  989. opts: opts,
  990. callInfo: c,
  991. desc: desc,
  992. codec: c.codec,
  993. cp: cp,
  994. comp: comp,
  995. t: t,
  996. }
  997. as.callInfo.stream = as
  998. s, err := as.t.NewStream(as.ctx, as.callHdr)
  999. if err != nil {
  1000. err = toRPCErr(err)
  1001. return nil, err
  1002. }
  1003. as.s = s
  1004. as.p = &parser{r: s}
  1005. ac.incrCallsStarted()
  1006. if desc != unaryStreamDesc {
  1007. // Listen on cc and stream contexts to cleanup when the user closes the
  1008. // ClientConn or cancels the stream context. In all other cases, an error
  1009. // should already be injected into the recv buffer by the transport, which
  1010. // the client will eventually receive, and then we will cancel the stream's
  1011. // context in clientStream.finish.
  1012. go func() {
  1013. select {
  1014. case <-ac.ctx.Done():
  1015. as.finish(status.Error(codes.Canceled, "grpc: the SubConn is closing"))
  1016. case <-ctx.Done():
  1017. as.finish(toRPCErr(ctx.Err()))
  1018. }
  1019. }()
  1020. }
  1021. return as, nil
  1022. }
  1023. type addrConnStream struct {
  1024. s *transport.Stream
  1025. ac *addrConn
  1026. callHdr *transport.CallHdr
  1027. cancel context.CancelFunc
  1028. opts []CallOption
  1029. callInfo *callInfo
  1030. t transport.ClientTransport
  1031. ctx context.Context
  1032. sentLast bool
  1033. desc *StreamDesc
  1034. codec baseCodec
  1035. cp Compressor
  1036. comp encoding.Compressor
  1037. decompSet bool
  1038. dc Decompressor
  1039. decomp encoding.Compressor
  1040. p *parser
  1041. mu sync.Mutex
  1042. finished bool
  1043. }
  1044. func (as *addrConnStream) Header() (metadata.MD, error) {
  1045. m, err := as.s.Header()
  1046. if err != nil {
  1047. as.finish(toRPCErr(err))
  1048. }
  1049. return m, err
  1050. }
  1051. func (as *addrConnStream) Trailer() metadata.MD {
  1052. return as.s.Trailer()
  1053. }
  1054. func (as *addrConnStream) CloseSend() error {
  1055. if as.sentLast {
  1056. // TODO: return an error and finish the stream instead, due to API misuse?
  1057. return nil
  1058. }
  1059. as.sentLast = true
  1060. as.t.Write(as.s, nil, nil, &transport.Options{Last: true})
  1061. // Always return nil; io.EOF is the only error that might make sense
  1062. // instead, but there is no need to signal the client to call RecvMsg
  1063. // as the only use left for the stream after CloseSend is to call
  1064. // RecvMsg. This also matches historical behavior.
  1065. return nil
  1066. }
  1067. func (as *addrConnStream) Context() context.Context {
  1068. return as.s.Context()
  1069. }
  1070. func (as *addrConnStream) SendMsg(m interface{}) (err error) {
  1071. defer func() {
  1072. if err != nil && err != io.EOF {
  1073. // Call finish on the client stream for errors generated by this SendMsg
  1074. // call, as these indicate problems created by this client. (Transport
  1075. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  1076. // error will be returned from RecvMsg eventually in that case, or be
  1077. // retried.)
  1078. as.finish(err)
  1079. }
  1080. }()
  1081. if as.sentLast {
  1082. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  1083. }
  1084. if !as.desc.ClientStreams {
  1085. as.sentLast = true
  1086. }
  1087. // load hdr, payload, data
  1088. hdr, payld, _, err := prepareMsg(m, as.codec, as.cp, as.comp)
  1089. if err != nil {
  1090. return err
  1091. }
  1092. // TODO(dfawley): should we be checking len(data) instead?
  1093. if len(payld) > *as.callInfo.maxSendMessageSize {
  1094. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payld), *as.callInfo.maxSendMessageSize)
  1095. }
  1096. if err := as.t.Write(as.s, hdr, payld, &transport.Options{Last: !as.desc.ClientStreams}); err != nil {
  1097. if !as.desc.ClientStreams {
  1098. // For non-client-streaming RPCs, we return nil instead of EOF on error
  1099. // because the generated code requires it. finish is not called; RecvMsg()
  1100. // will call it with the stream's status independently.
  1101. return nil
  1102. }
  1103. return io.EOF
  1104. }
  1105. if channelz.IsOn() {
  1106. as.t.IncrMsgSent()
  1107. }
  1108. return nil
  1109. }
  1110. func (as *addrConnStream) RecvMsg(m interface{}) (err error) {
  1111. defer func() {
  1112. if err != nil || !as.desc.ServerStreams {
  1113. // err != nil or non-server-streaming indicates end of stream.
  1114. as.finish(err)
  1115. }
  1116. }()
  1117. if !as.decompSet {
  1118. // Block until we receive headers containing received message encoding.
  1119. if ct := as.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  1120. if as.dc == nil || as.dc.Type() != ct {
  1121. // No configured decompressor, or it does not match the incoming
  1122. // message encoding; attempt to find a registered compressor that does.
  1123. as.dc = nil
  1124. as.decomp = encoding.GetCompressor(ct)
  1125. }
  1126. } else {
  1127. // No compression is used; disable our decompressor.
  1128. as.dc = nil
  1129. }
  1130. // Only initialize this state once per stream.
  1131. as.decompSet = true
  1132. }
  1133. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1134. if err != nil {
  1135. if err == io.EOF {
  1136. if statusErr := as.s.Status().Err(); statusErr != nil {
  1137. return statusErr
  1138. }
  1139. return io.EOF // indicates successful end of stream.
  1140. }
  1141. return toRPCErr(err)
  1142. }
  1143. if channelz.IsOn() {
  1144. as.t.IncrMsgRecv()
  1145. }
  1146. if as.desc.ServerStreams {
  1147. // Subsequent messages should be received by subsequent RecvMsg calls.
  1148. return nil
  1149. }
  1150. // Special handling for non-server-stream rpcs.
  1151. // This recv expects EOF or errors, so we don't collect inPayload.
  1152. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1153. if err == nil {
  1154. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  1155. }
  1156. if err == io.EOF {
  1157. return as.s.Status().Err() // non-server streaming Recv returns nil on success
  1158. }
  1159. return toRPCErr(err)
  1160. }
  1161. func (as *addrConnStream) finish(err error) {
  1162. as.mu.Lock()
  1163. if as.finished {
  1164. as.mu.Unlock()
  1165. return
  1166. }
  1167. as.finished = true
  1168. if err == io.EOF {
  1169. // Ending a stream with EOF indicates a success.
  1170. err = nil
  1171. }
  1172. if as.s != nil {
  1173. as.t.CloseStream(as.s, err)
  1174. }
  1175. if err != nil {
  1176. as.ac.incrCallsFailed()
  1177. } else {
  1178. as.ac.incrCallsSucceeded()
  1179. }
  1180. as.cancel()
  1181. as.mu.Unlock()
  1182. }
  1183. // ServerStream defines the server-side behavior of a streaming RPC.
  1184. //
  1185. // All errors returned from ServerStream methods are compatible with the
  1186. // status package.
  1187. type ServerStream interface {
  1188. // SetHeader sets the header metadata. It may be called multiple times.
  1189. // When call multiple times, all the provided metadata will be merged.
  1190. // All the metadata will be sent out when one of the following happens:
  1191. // - ServerStream.SendHeader() is called;
  1192. // - The first response is sent out;
  1193. // - An RPC status is sent out (error or success).
  1194. SetHeader(metadata.MD) error
  1195. // SendHeader sends the header metadata.
  1196. // The provided md and headers set by SetHeader() will be sent.
  1197. // It fails if called multiple times.
  1198. SendHeader(metadata.MD) error
  1199. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  1200. // When called more than once, all the provided metadata will be merged.
  1201. SetTrailer(metadata.MD)
  1202. // Context returns the context for this stream.
  1203. Context() context.Context
  1204. // SendMsg sends a message. On error, SendMsg aborts the stream and the
  1205. // error is returned directly.
  1206. //
  1207. // SendMsg blocks until:
  1208. // - There is sufficient flow control to schedule m with the transport, or
  1209. // - The stream is done, or
  1210. // - The stream breaks.
  1211. //
  1212. // SendMsg does not wait until the message is received by the client. An
  1213. // untimely stream closure may result in lost messages.
  1214. //
  1215. // It is safe to have a goroutine calling SendMsg and another goroutine
  1216. // calling RecvMsg on the same stream at the same time, but it is not safe
  1217. // to call SendMsg on the same stream in different goroutines.
  1218. SendMsg(m interface{}) error
  1219. // RecvMsg blocks until it receives a message into m or the stream is
  1220. // done. It returns io.EOF when the client has performed a CloseSend. On
  1221. // any non-EOF error, the stream is aborted and the error contains the
  1222. // RPC status.
  1223. //
  1224. // It is safe to have a goroutine calling SendMsg and another goroutine
  1225. // calling RecvMsg on the same stream at the same time, but it is not
  1226. // safe to call RecvMsg on the same stream in different goroutines.
  1227. RecvMsg(m interface{}) error
  1228. }
  1229. // serverStream implements a server side Stream.
  1230. type serverStream struct {
  1231. ctx context.Context
  1232. t transport.ServerTransport
  1233. s *transport.Stream
  1234. p *parser
  1235. codec baseCodec
  1236. cp Compressor
  1237. dc Decompressor
  1238. comp encoding.Compressor
  1239. decomp encoding.Compressor
  1240. maxReceiveMessageSize int
  1241. maxSendMessageSize int
  1242. trInfo *traceInfo
  1243. statsHandler stats.Handler
  1244. binlog *binarylog.MethodLogger
  1245. // serverHeaderBinlogged indicates whether server header has been logged. It
  1246. // will happen when one of the following two happens: stream.SendHeader(),
  1247. // stream.Send().
  1248. //
  1249. // It's only checked in send and sendHeader, doesn't need to be
  1250. // synchronized.
  1251. serverHeaderBinlogged bool
  1252. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  1253. }
  1254. func (ss *serverStream) Context() context.Context {
  1255. return ss.ctx
  1256. }
  1257. func (ss *serverStream) SetHeader(md metadata.MD) error {
  1258. if md.Len() == 0 {
  1259. return nil
  1260. }
  1261. return ss.s.SetHeader(md)
  1262. }
  1263. func (ss *serverStream) SendHeader(md metadata.MD) error {
  1264. err := ss.t.WriteHeader(ss.s, md)
  1265. if ss.binlog != nil && !ss.serverHeaderBinlogged {
  1266. h, _ := ss.s.Header()
  1267. ss.binlog.Log(&binarylog.ServerHeader{
  1268. Header: h,
  1269. })
  1270. ss.serverHeaderBinlogged = true
  1271. }
  1272. return err
  1273. }
  1274. func (ss *serverStream) SetTrailer(md metadata.MD) {
  1275. if md.Len() == 0 {
  1276. return
  1277. }
  1278. ss.s.SetTrailer(md)
  1279. }
  1280. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  1281. defer func() {
  1282. if ss.trInfo != nil {
  1283. ss.mu.Lock()
  1284. if ss.trInfo.tr != nil {
  1285. if err == nil {
  1286. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  1287. } else {
  1288. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1289. ss.trInfo.tr.SetError()
  1290. }
  1291. }
  1292. ss.mu.Unlock()
  1293. }
  1294. if err != nil && err != io.EOF {
  1295. st, _ := status.FromError(toRPCErr(err))
  1296. ss.t.WriteStatus(ss.s, st)
  1297. // Non-user specified status was sent out. This should be an error
  1298. // case (as a server side Cancel maybe).
  1299. //
  1300. // This is not handled specifically now. User will return a final
  1301. // status from the service handler, we will log that error instead.
  1302. // This behavior is similar to an interceptor.
  1303. }
  1304. if channelz.IsOn() && err == nil {
  1305. ss.t.IncrMsgSent()
  1306. }
  1307. }()
  1308. // load hdr, payload, data
  1309. hdr, payload, data, err := prepareMsg(m, ss.codec, ss.cp, ss.comp)
  1310. if err != nil {
  1311. return err
  1312. }
  1313. // TODO(dfawley): should we be checking len(data) instead?
  1314. if len(payload) > ss.maxSendMessageSize {
  1315. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize)
  1316. }
  1317. if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil {
  1318. return toRPCErr(err)
  1319. }
  1320. if ss.binlog != nil {
  1321. if !ss.serverHeaderBinlogged {
  1322. h, _ := ss.s.Header()
  1323. ss.binlog.Log(&binarylog.ServerHeader{
  1324. Header: h,
  1325. })
  1326. ss.serverHeaderBinlogged = true
  1327. }
  1328. ss.binlog.Log(&binarylog.ServerMessage{
  1329. Message: data,
  1330. })
  1331. }
  1332. if ss.statsHandler != nil {
  1333. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now()))
  1334. }
  1335. return nil
  1336. }
  1337. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  1338. defer func() {
  1339. if ss.trInfo != nil {
  1340. ss.mu.Lock()
  1341. if ss.trInfo.tr != nil {
  1342. if err == nil {
  1343. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  1344. } else if err != io.EOF {
  1345. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1346. ss.trInfo.tr.SetError()
  1347. }
  1348. }
  1349. ss.mu.Unlock()
  1350. }
  1351. if err != nil && err != io.EOF {
  1352. st, _ := status.FromError(toRPCErr(err))
  1353. ss.t.WriteStatus(ss.s, st)
  1354. // Non-user specified status was sent out. This should be an error
  1355. // case (as a server side Cancel maybe).
  1356. //
  1357. // This is not handled specifically now. User will return a final
  1358. // status from the service handler, we will log that error instead.
  1359. // This behavior is similar to an interceptor.
  1360. }
  1361. if channelz.IsOn() && err == nil {
  1362. ss.t.IncrMsgRecv()
  1363. }
  1364. }()
  1365. var payInfo *payloadInfo
  1366. if ss.statsHandler != nil || ss.binlog != nil {
  1367. payInfo = &payloadInfo{}
  1368. }
  1369. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, payInfo, ss.decomp); err != nil {
  1370. if err == io.EOF {
  1371. if ss.binlog != nil {
  1372. ss.binlog.Log(&binarylog.ClientHalfClose{})
  1373. }
  1374. return err
  1375. }
  1376. if err == io.ErrUnexpectedEOF {
  1377. err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  1378. }
  1379. return toRPCErr(err)
  1380. }
  1381. if ss.statsHandler != nil {
  1382. ss.statsHandler.HandleRPC(ss.s.Context(), &stats.InPayload{
  1383. RecvTime: time.Now(),
  1384. Payload: m,
  1385. // TODO truncate large payload.
  1386. Data: payInfo.uncompressedBytes,
  1387. WireLength: payInfo.wireLength,
  1388. Length: len(payInfo.uncompressedBytes),
  1389. })
  1390. }
  1391. if ss.binlog != nil {
  1392. ss.binlog.Log(&binarylog.ClientMessage{
  1393. Message: payInfo.uncompressedBytes,
  1394. })
  1395. }
  1396. return nil
  1397. }
  1398. // MethodFromServerStream returns the method string for the input stream.
  1399. // The returned string is in the format of "/service/method".
  1400. func MethodFromServerStream(stream ServerStream) (string, bool) {
  1401. return Method(stream.Context())
  1402. }
  1403. // prepareMsg returns the hdr, payload and data
  1404. // using the compressors passed or using the
  1405. // passed preparedmsg
  1406. func prepareMsg(m interface{}, codec baseCodec, cp Compressor, comp encoding.Compressor) (hdr, payload, data []byte, err error) {
  1407. if preparedMsg, ok := m.(*PreparedMsg); ok {
  1408. return preparedMsg.hdr, preparedMsg.payload, preparedMsg.encodedData, nil
  1409. }
  1410. // The input interface is not a prepared msg.
  1411. // Marshal and Compress the data at this point
  1412. data, err = encode(codec, m)
  1413. if err != nil {
  1414. return nil, nil, nil, err
  1415. }
  1416. compData, err := compress(data, cp, comp)
  1417. if err != nil {
  1418. return nil, nil, nil, err
  1419. }
  1420. hdr, payload = msgHeader(data, compData)
  1421. return hdr, payload, data, nil
  1422. }