stream.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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. func (cs *clientStream) newAttemptLocked(sh stats.Handler, trInfo *traceInfo) error {
  309. cs.attempt = &csAttempt{
  310. cs: cs,
  311. dc: cs.cc.dopts.dc,
  312. statsHandler: sh,
  313. trInfo: trInfo,
  314. }
  315. if err := cs.ctx.Err(); err != nil {
  316. return toRPCErr(err)
  317. }
  318. t, done, err := cs.cc.getTransport(cs.ctx, cs.callInfo.failFast, cs.callHdr.Method)
  319. if err != nil {
  320. return err
  321. }
  322. if trInfo != nil {
  323. trInfo.firstLine.SetRemoteAddr(t.RemoteAddr())
  324. }
  325. cs.attempt.t = t
  326. cs.attempt.done = done
  327. return nil
  328. }
  329. func (a *csAttempt) newStream() error {
  330. cs := a.cs
  331. cs.callHdr.PreviousAttempts = cs.numRetries
  332. s, err := a.t.NewStream(cs.ctx, cs.callHdr)
  333. if err != nil {
  334. return toRPCErr(err)
  335. }
  336. cs.attempt.s = s
  337. cs.attempt.p = &parser{r: s}
  338. return nil
  339. }
  340. // clientStream implements a client side Stream.
  341. type clientStream struct {
  342. callHdr *transport.CallHdr
  343. opts []CallOption
  344. callInfo *callInfo
  345. cc *ClientConn
  346. desc *StreamDesc
  347. codec baseCodec
  348. cp Compressor
  349. comp encoding.Compressor
  350. cancel context.CancelFunc // cancels all attempts
  351. sentLast bool // sent an end stream
  352. beginTime time.Time
  353. methodConfig *MethodConfig
  354. ctx context.Context // the application's context, wrapped by stats/tracing
  355. retryThrottler *retryThrottler // The throttler active when the RPC began.
  356. binlog *binarylog.MethodLogger // Binary logger, can be nil.
  357. // serverHeaderBinlogged is a boolean for whether server header has been
  358. // logged. Server header will be logged when the first time one of those
  359. // happens: stream.Header(), stream.Recv().
  360. //
  361. // It's only read and used by Recv() and Header(), so it doesn't need to be
  362. // synchronized.
  363. serverHeaderBinlogged bool
  364. mu sync.Mutex
  365. firstAttempt bool // if true, transparent retry is valid
  366. numRetries int // exclusive of transparent retry attempt(s)
  367. numRetriesSincePushback int // retries since pushback; to reset backoff
  368. finished bool // TODO: replace with atomic cmpxchg or sync.Once?
  369. attempt *csAttempt // the active client stream attempt
  370. // TODO(hedging): hedging will have multiple attempts simultaneously.
  371. committed bool // active attempt committed for retry?
  372. buffer []func(a *csAttempt) error // operations to replay on retry
  373. bufferSize int // current size of buffer
  374. }
  375. // csAttempt implements a single transport stream attempt within a
  376. // clientStream.
  377. type csAttempt struct {
  378. cs *clientStream
  379. t transport.ClientTransport
  380. s *transport.Stream
  381. p *parser
  382. done func(balancer.DoneInfo)
  383. finished bool
  384. dc Decompressor
  385. decomp encoding.Compressor
  386. decompSet bool
  387. mu sync.Mutex // guards trInfo.tr
  388. // trInfo may be nil (if EnableTracing is false).
  389. // trInfo.tr is set when created (if EnableTracing is true),
  390. // and cleared when the finish method is called.
  391. trInfo *traceInfo
  392. statsHandler stats.Handler
  393. }
  394. func (cs *clientStream) commitAttemptLocked() {
  395. cs.committed = true
  396. cs.buffer = nil
  397. }
  398. func (cs *clientStream) commitAttempt() {
  399. cs.mu.Lock()
  400. cs.commitAttemptLocked()
  401. cs.mu.Unlock()
  402. }
  403. // shouldRetry returns nil if the RPC should be retried; otherwise it returns
  404. // the error that should be returned by the operation.
  405. func (cs *clientStream) shouldRetry(err error) error {
  406. if cs.attempt.s == nil && !cs.callInfo.failFast {
  407. // In the event of any error from NewStream (attempt.s == nil), we
  408. // never attempted to write anything to the wire, so we can retry
  409. // indefinitely for non-fail-fast RPCs.
  410. return nil
  411. }
  412. if cs.finished || cs.committed {
  413. // RPC is finished or committed; cannot retry.
  414. return err
  415. }
  416. // Wait for the trailers.
  417. if cs.attempt.s != nil {
  418. <-cs.attempt.s.Done()
  419. }
  420. if cs.firstAttempt && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) {
  421. // First attempt, stream unprocessed: transparently retry.
  422. cs.firstAttempt = false
  423. return nil
  424. }
  425. cs.firstAttempt = false
  426. if cs.cc.dopts.disableRetry {
  427. return err
  428. }
  429. pushback := 0
  430. hasPushback := false
  431. if cs.attempt.s != nil {
  432. if to, toErr := cs.attempt.s.TrailersOnly(); toErr != nil || !to {
  433. return err
  434. }
  435. // TODO(retry): Move down if the spec changes to not check server pushback
  436. // before considering this a failure for throttling.
  437. sps := cs.attempt.s.Trailer()["grpc-retry-pushback-ms"]
  438. if len(sps) == 1 {
  439. var e error
  440. if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 {
  441. grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0])
  442. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  443. return err
  444. }
  445. hasPushback = true
  446. } else if len(sps) > 1 {
  447. grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps)
  448. cs.retryThrottler.throttle() // This counts as a failure for throttling.
  449. return err
  450. }
  451. }
  452. var code codes.Code
  453. if cs.attempt.s != nil {
  454. code = cs.attempt.s.Status().Code()
  455. } else {
  456. code = status.Convert(err).Code()
  457. }
  458. rp := cs.methodConfig.retryPolicy
  459. if rp == nil || !rp.retryableStatusCodes[code] {
  460. return err
  461. }
  462. // Note: the ordering here is important; we count this as a failure
  463. // only if the code matched a retryable code.
  464. if cs.retryThrottler.throttle() {
  465. return err
  466. }
  467. if cs.numRetries+1 >= rp.maxAttempts {
  468. return err
  469. }
  470. var dur time.Duration
  471. if hasPushback {
  472. dur = time.Millisecond * time.Duration(pushback)
  473. cs.numRetriesSincePushback = 0
  474. } else {
  475. fact := math.Pow(rp.backoffMultiplier, float64(cs.numRetriesSincePushback))
  476. cur := float64(rp.initialBackoff) * fact
  477. if max := float64(rp.maxBackoff); cur > max {
  478. cur = max
  479. }
  480. dur = time.Duration(grpcrand.Int63n(int64(cur)))
  481. cs.numRetriesSincePushback++
  482. }
  483. // TODO(dfawley): we could eagerly fail here if dur puts us past the
  484. // deadline, but unsure if it is worth doing.
  485. t := time.NewTimer(dur)
  486. select {
  487. case <-t.C:
  488. cs.numRetries++
  489. return nil
  490. case <-cs.ctx.Done():
  491. t.Stop()
  492. return status.FromContextError(cs.ctx.Err()).Err()
  493. }
  494. }
  495. // Returns nil if a retry was performed and succeeded; error otherwise.
  496. func (cs *clientStream) retryLocked(lastErr error) error {
  497. for {
  498. cs.attempt.finish(lastErr)
  499. if err := cs.shouldRetry(lastErr); err != nil {
  500. cs.commitAttemptLocked()
  501. return err
  502. }
  503. if err := cs.newAttemptLocked(nil, nil); err != nil {
  504. return err
  505. }
  506. if lastErr = cs.replayBufferLocked(); lastErr == nil {
  507. return nil
  508. }
  509. }
  510. }
  511. func (cs *clientStream) Context() context.Context {
  512. cs.commitAttempt()
  513. // No need to lock before using attempt, since we know it is committed and
  514. // cannot change.
  515. return cs.attempt.s.Context()
  516. }
  517. func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error {
  518. cs.mu.Lock()
  519. for {
  520. if cs.committed {
  521. cs.mu.Unlock()
  522. return op(cs.attempt)
  523. }
  524. a := cs.attempt
  525. cs.mu.Unlock()
  526. err := op(a)
  527. cs.mu.Lock()
  528. if a != cs.attempt {
  529. // We started another attempt already.
  530. continue
  531. }
  532. if err == io.EOF {
  533. <-a.s.Done()
  534. }
  535. if err == nil || (err == io.EOF && a.s.Status().Code() == codes.OK) {
  536. onSuccess()
  537. cs.mu.Unlock()
  538. return err
  539. }
  540. if err := cs.retryLocked(err); err != nil {
  541. cs.mu.Unlock()
  542. return err
  543. }
  544. }
  545. }
  546. func (cs *clientStream) Header() (metadata.MD, error) {
  547. var m metadata.MD
  548. err := cs.withRetry(func(a *csAttempt) error {
  549. var err error
  550. m, err = a.s.Header()
  551. return toRPCErr(err)
  552. }, cs.commitAttemptLocked)
  553. if err != nil {
  554. cs.finish(err)
  555. return nil, err
  556. }
  557. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  558. // Only log if binary log is on and header has not been logged.
  559. logEntry := &binarylog.ServerHeader{
  560. OnClientSide: true,
  561. Header: m,
  562. PeerAddr: nil,
  563. }
  564. if peer, ok := peer.FromContext(cs.Context()); ok {
  565. logEntry.PeerAddr = peer.Addr
  566. }
  567. cs.binlog.Log(logEntry)
  568. cs.serverHeaderBinlogged = true
  569. }
  570. return m, err
  571. }
  572. func (cs *clientStream) Trailer() metadata.MD {
  573. // On RPC failure, we never need to retry, because usage requires that
  574. // RecvMsg() returned a non-nil error before calling this function is valid.
  575. // We would have retried earlier if necessary.
  576. //
  577. // Commit the attempt anyway, just in case users are not following those
  578. // directions -- it will prevent races and should not meaningfully impact
  579. // performance.
  580. cs.commitAttempt()
  581. if cs.attempt.s == nil {
  582. return nil
  583. }
  584. return cs.attempt.s.Trailer()
  585. }
  586. func (cs *clientStream) replayBufferLocked() error {
  587. a := cs.attempt
  588. for _, f := range cs.buffer {
  589. if err := f(a); err != nil {
  590. return err
  591. }
  592. }
  593. return nil
  594. }
  595. func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error) {
  596. // Note: we still will buffer if retry is disabled (for transparent retries).
  597. if cs.committed {
  598. return
  599. }
  600. cs.bufferSize += sz
  601. if cs.bufferSize > cs.callInfo.maxRetryRPCBufferSize {
  602. cs.commitAttemptLocked()
  603. return
  604. }
  605. cs.buffer = append(cs.buffer, op)
  606. }
  607. func (cs *clientStream) SendMsg(m interface{}) (err error) {
  608. defer func() {
  609. if err != nil && err != io.EOF {
  610. // Call finish on the client stream for errors generated by this SendMsg
  611. // call, as these indicate problems created by this client. (Transport
  612. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  613. // error will be returned from RecvMsg eventually in that case, or be
  614. // retried.)
  615. cs.finish(err)
  616. }
  617. }()
  618. if cs.sentLast {
  619. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  620. }
  621. if !cs.desc.ClientStreams {
  622. cs.sentLast = true
  623. }
  624. // load hdr, payload, data
  625. hdr, payload, data, err := prepareMsg(m, cs.codec, cs.cp, cs.comp)
  626. if err != nil {
  627. return err
  628. }
  629. // TODO(dfawley): should we be checking len(data) instead?
  630. if len(payload) > *cs.callInfo.maxSendMessageSize {
  631. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.callInfo.maxSendMessageSize)
  632. }
  633. msgBytes := data // Store the pointer before setting to nil. For binary logging.
  634. op := func(a *csAttempt) error {
  635. err := a.sendMsg(m, hdr, payload, data)
  636. // nil out the message and uncomp when replaying; they are only needed for
  637. // stats which is disabled for subsequent attempts.
  638. m, data = nil, nil
  639. return err
  640. }
  641. err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+len(payload), op) })
  642. if cs.binlog != nil && err == nil {
  643. cs.binlog.Log(&binarylog.ClientMessage{
  644. OnClientSide: true,
  645. Message: msgBytes,
  646. })
  647. }
  648. return
  649. }
  650. func (cs *clientStream) RecvMsg(m interface{}) error {
  651. if cs.binlog != nil && !cs.serverHeaderBinlogged {
  652. // Call Header() to binary log header if it's not already logged.
  653. cs.Header()
  654. }
  655. var recvInfo *payloadInfo
  656. if cs.binlog != nil {
  657. recvInfo = &payloadInfo{}
  658. }
  659. err := cs.withRetry(func(a *csAttempt) error {
  660. return a.recvMsg(m, recvInfo)
  661. }, cs.commitAttemptLocked)
  662. if cs.binlog != nil && err == nil {
  663. cs.binlog.Log(&binarylog.ServerMessage{
  664. OnClientSide: true,
  665. Message: recvInfo.uncompressedBytes,
  666. })
  667. }
  668. if err != nil || !cs.desc.ServerStreams {
  669. // err != nil or non-server-streaming indicates end of stream.
  670. cs.finish(err)
  671. if cs.binlog != nil {
  672. // finish will not log Trailer. Log Trailer here.
  673. logEntry := &binarylog.ServerTrailer{
  674. OnClientSide: true,
  675. Trailer: cs.Trailer(),
  676. Err: err,
  677. }
  678. if logEntry.Err == io.EOF {
  679. logEntry.Err = nil
  680. }
  681. if peer, ok := peer.FromContext(cs.Context()); ok {
  682. logEntry.PeerAddr = peer.Addr
  683. }
  684. cs.binlog.Log(logEntry)
  685. }
  686. }
  687. return err
  688. }
  689. func (cs *clientStream) CloseSend() error {
  690. if cs.sentLast {
  691. // TODO: return an error and finish the stream instead, due to API misuse?
  692. return nil
  693. }
  694. cs.sentLast = true
  695. op := func(a *csAttempt) error {
  696. a.t.Write(a.s, nil, nil, &transport.Options{Last: true})
  697. // Always return nil; io.EOF is the only error that might make sense
  698. // instead, but there is no need to signal the client to call RecvMsg
  699. // as the only use left for the stream after CloseSend is to call
  700. // RecvMsg. This also matches historical behavior.
  701. return nil
  702. }
  703. cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op) })
  704. if cs.binlog != nil {
  705. cs.binlog.Log(&binarylog.ClientHalfClose{
  706. OnClientSide: true,
  707. })
  708. }
  709. // We never returned an error here for reasons.
  710. return nil
  711. }
  712. func (cs *clientStream) finish(err error) {
  713. if err == io.EOF {
  714. // Ending a stream with EOF indicates a success.
  715. err = nil
  716. }
  717. cs.mu.Lock()
  718. if cs.finished {
  719. cs.mu.Unlock()
  720. return
  721. }
  722. cs.finished = true
  723. cs.commitAttemptLocked()
  724. cs.mu.Unlock()
  725. // For binary logging. only log cancel in finish (could be caused by RPC ctx
  726. // canceled or ClientConn closed). Trailer will be logged in RecvMsg.
  727. //
  728. // Only one of cancel or trailer needs to be logged. In the cases where
  729. // users don't call RecvMsg, users must have already canceled the RPC.
  730. if cs.binlog != nil && status.Code(err) == codes.Canceled {
  731. cs.binlog.Log(&binarylog.Cancel{
  732. OnClientSide: true,
  733. })
  734. }
  735. if err == nil {
  736. cs.retryThrottler.successfulRPC()
  737. }
  738. if channelz.IsOn() {
  739. if err != nil {
  740. cs.cc.incrCallsFailed()
  741. } else {
  742. cs.cc.incrCallsSucceeded()
  743. }
  744. }
  745. if cs.attempt != nil {
  746. cs.attempt.finish(err)
  747. }
  748. // after functions all rely upon having a stream.
  749. if cs.attempt.s != nil {
  750. for _, o := range cs.opts {
  751. o.after(cs.callInfo)
  752. }
  753. }
  754. cs.cancel()
  755. }
  756. func (a *csAttempt) sendMsg(m interface{}, hdr, payld, data []byte) error {
  757. cs := a.cs
  758. if a.trInfo != nil {
  759. a.mu.Lock()
  760. if a.trInfo.tr != nil {
  761. a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  762. }
  763. a.mu.Unlock()
  764. }
  765. if err := a.t.Write(a.s, hdr, payld, &transport.Options{Last: !cs.desc.ClientStreams}); err != nil {
  766. if !cs.desc.ClientStreams {
  767. // For non-client-streaming RPCs, we return nil instead of EOF on error
  768. // because the generated code requires it. finish is not called; RecvMsg()
  769. // will call it with the stream's status independently.
  770. return nil
  771. }
  772. return io.EOF
  773. }
  774. if a.statsHandler != nil {
  775. a.statsHandler.HandleRPC(cs.ctx, outPayload(true, m, data, payld, time.Now()))
  776. }
  777. if channelz.IsOn() {
  778. a.t.IncrMsgSent()
  779. }
  780. return nil
  781. }
  782. func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) {
  783. cs := a.cs
  784. if a.statsHandler != nil && payInfo == nil {
  785. payInfo = &payloadInfo{}
  786. }
  787. if !a.decompSet {
  788. // Block until we receive headers containing received message encoding.
  789. if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  790. if a.dc == nil || a.dc.Type() != ct {
  791. // No configured decompressor, or it does not match the incoming
  792. // message encoding; attempt to find a registered compressor that does.
  793. a.dc = nil
  794. a.decomp = encoding.GetCompressor(ct)
  795. }
  796. } else {
  797. // No compression is used; disable our decompressor.
  798. a.dc = nil
  799. }
  800. // Only initialize this state once per stream.
  801. a.decompSet = true
  802. }
  803. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, payInfo, a.decomp)
  804. if err != nil {
  805. if err == io.EOF {
  806. if statusErr := a.s.Status().Err(); statusErr != nil {
  807. return statusErr
  808. }
  809. return io.EOF // indicates successful end of stream.
  810. }
  811. return toRPCErr(err)
  812. }
  813. if a.trInfo != nil {
  814. a.mu.Lock()
  815. if a.trInfo.tr != nil {
  816. a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  817. }
  818. a.mu.Unlock()
  819. }
  820. if a.statsHandler != nil {
  821. a.statsHandler.HandleRPC(cs.ctx, &stats.InPayload{
  822. Client: true,
  823. RecvTime: time.Now(),
  824. Payload: m,
  825. // TODO truncate large payload.
  826. Data: payInfo.uncompressedBytes,
  827. WireLength: payInfo.wireLength,
  828. Length: len(payInfo.uncompressedBytes),
  829. })
  830. }
  831. if channelz.IsOn() {
  832. a.t.IncrMsgRecv()
  833. }
  834. if cs.desc.ServerStreams {
  835. // Subsequent messages should be received by subsequent RecvMsg calls.
  836. return nil
  837. }
  838. // Special handling for non-server-stream rpcs.
  839. // This recv expects EOF or errors, so we don't collect inPayload.
  840. err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.callInfo.maxReceiveMessageSize, nil, a.decomp)
  841. if err == nil {
  842. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  843. }
  844. if err == io.EOF {
  845. return a.s.Status().Err() // non-server streaming Recv returns nil on success
  846. }
  847. return toRPCErr(err)
  848. }
  849. func (a *csAttempt) finish(err error) {
  850. a.mu.Lock()
  851. if a.finished {
  852. a.mu.Unlock()
  853. return
  854. }
  855. a.finished = true
  856. if err == io.EOF {
  857. // Ending a stream with EOF indicates a success.
  858. err = nil
  859. }
  860. var tr metadata.MD
  861. if a.s != nil {
  862. a.t.CloseStream(a.s, err)
  863. tr = a.s.Trailer()
  864. }
  865. if a.done != nil {
  866. br := false
  867. if a.s != nil {
  868. br = a.s.BytesReceived()
  869. }
  870. a.done(balancer.DoneInfo{
  871. Err: err,
  872. Trailer: tr,
  873. BytesSent: a.s != nil,
  874. BytesReceived: br,
  875. ServerLoad: balancerload.Parse(tr),
  876. })
  877. }
  878. if a.statsHandler != nil {
  879. end := &stats.End{
  880. Client: true,
  881. BeginTime: a.cs.beginTime,
  882. EndTime: time.Now(),
  883. Trailer: tr,
  884. Error: err,
  885. }
  886. a.statsHandler.HandleRPC(a.cs.ctx, end)
  887. }
  888. if a.trInfo != nil && a.trInfo.tr != nil {
  889. if err == nil {
  890. a.trInfo.tr.LazyPrintf("RPC: [OK]")
  891. } else {
  892. a.trInfo.tr.LazyPrintf("RPC: [%v]", err)
  893. a.trInfo.tr.SetError()
  894. }
  895. a.trInfo.tr.Finish()
  896. a.trInfo.tr = nil
  897. }
  898. a.mu.Unlock()
  899. }
  900. // newClientStream creates a ClientStream with the specified transport, on the
  901. // given addrConn.
  902. //
  903. // It's expected that the given transport is either the same one in addrConn, or
  904. // is already closed. To avoid race, transport is specified separately, instead
  905. // of using ac.transpot.
  906. //
  907. // Main difference between this and ClientConn.NewStream:
  908. // - no retry
  909. // - no service config (or wait for service config)
  910. // - no tracing or stats
  911. func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method string, t transport.ClientTransport, ac *addrConn, opts ...CallOption) (_ ClientStream, err error) {
  912. if t == nil {
  913. // TODO: return RPC error here?
  914. return nil, errors.New("transport provided is nil")
  915. }
  916. // defaultCallInfo contains unnecessary info(i.e. failfast, maxRetryRPCBufferSize), so we just initialize an empty struct.
  917. c := &callInfo{}
  918. // Possible context leak:
  919. // The cancel function for the child context we create will only be called
  920. // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if
  921. // an error is generated by SendMsg.
  922. // https://github.com/grpc/grpc-go/issues/1818.
  923. ctx, cancel := context.WithCancel(ctx)
  924. defer func() {
  925. if err != nil {
  926. cancel()
  927. }
  928. }()
  929. for _, o := range opts {
  930. if err := o.before(c); err != nil {
  931. return nil, toRPCErr(err)
  932. }
  933. }
  934. c.maxReceiveMessageSize = getMaxSize(nil, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize)
  935. c.maxSendMessageSize = getMaxSize(nil, c.maxSendMessageSize, defaultServerMaxSendMessageSize)
  936. if err := setCallInfoCodec(c); err != nil {
  937. return nil, err
  938. }
  939. callHdr := &transport.CallHdr{
  940. Host: ac.cc.authority,
  941. Method: method,
  942. ContentSubtype: c.contentSubtype,
  943. }
  944. // Set our outgoing compression according to the UseCompressor CallOption, if
  945. // set. In that case, also find the compressor from the encoding package.
  946. // Otherwise, use the compressor configured by the WithCompressor DialOption,
  947. // if set.
  948. var cp Compressor
  949. var comp encoding.Compressor
  950. if ct := c.compressorType; ct != "" {
  951. callHdr.SendCompress = ct
  952. if ct != encoding.Identity {
  953. comp = encoding.GetCompressor(ct)
  954. if comp == nil {
  955. return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct)
  956. }
  957. }
  958. } else if ac.cc.dopts.cp != nil {
  959. callHdr.SendCompress = ac.cc.dopts.cp.Type()
  960. cp = ac.cc.dopts.cp
  961. }
  962. if c.creds != nil {
  963. callHdr.Creds = c.creds
  964. }
  965. // Use a special addrConnStream to avoid retry.
  966. as := &addrConnStream{
  967. callHdr: callHdr,
  968. ac: ac,
  969. ctx: ctx,
  970. cancel: cancel,
  971. opts: opts,
  972. callInfo: c,
  973. desc: desc,
  974. codec: c.codec,
  975. cp: cp,
  976. comp: comp,
  977. t: t,
  978. }
  979. as.callInfo.stream = as
  980. s, err := as.t.NewStream(as.ctx, as.callHdr)
  981. if err != nil {
  982. err = toRPCErr(err)
  983. return nil, err
  984. }
  985. as.s = s
  986. as.p = &parser{r: s}
  987. ac.incrCallsStarted()
  988. if desc != unaryStreamDesc {
  989. // Listen on cc and stream contexts to cleanup when the user closes the
  990. // ClientConn or cancels the stream context. In all other cases, an error
  991. // should already be injected into the recv buffer by the transport, which
  992. // the client will eventually receive, and then we will cancel the stream's
  993. // context in clientStream.finish.
  994. go func() {
  995. select {
  996. case <-ac.ctx.Done():
  997. as.finish(status.Error(codes.Canceled, "grpc: the SubConn is closing"))
  998. case <-ctx.Done():
  999. as.finish(toRPCErr(ctx.Err()))
  1000. }
  1001. }()
  1002. }
  1003. return as, nil
  1004. }
  1005. type addrConnStream struct {
  1006. s *transport.Stream
  1007. ac *addrConn
  1008. callHdr *transport.CallHdr
  1009. cancel context.CancelFunc
  1010. opts []CallOption
  1011. callInfo *callInfo
  1012. t transport.ClientTransport
  1013. ctx context.Context
  1014. sentLast bool
  1015. desc *StreamDesc
  1016. codec baseCodec
  1017. cp Compressor
  1018. comp encoding.Compressor
  1019. decompSet bool
  1020. dc Decompressor
  1021. decomp encoding.Compressor
  1022. p *parser
  1023. mu sync.Mutex
  1024. finished bool
  1025. }
  1026. func (as *addrConnStream) Header() (metadata.MD, error) {
  1027. m, err := as.s.Header()
  1028. if err != nil {
  1029. as.finish(toRPCErr(err))
  1030. }
  1031. return m, err
  1032. }
  1033. func (as *addrConnStream) Trailer() metadata.MD {
  1034. return as.s.Trailer()
  1035. }
  1036. func (as *addrConnStream) CloseSend() error {
  1037. if as.sentLast {
  1038. // TODO: return an error and finish the stream instead, due to API misuse?
  1039. return nil
  1040. }
  1041. as.sentLast = true
  1042. as.t.Write(as.s, nil, nil, &transport.Options{Last: true})
  1043. // Always return nil; io.EOF is the only error that might make sense
  1044. // instead, but there is no need to signal the client to call RecvMsg
  1045. // as the only use left for the stream after CloseSend is to call
  1046. // RecvMsg. This also matches historical behavior.
  1047. return nil
  1048. }
  1049. func (as *addrConnStream) Context() context.Context {
  1050. return as.s.Context()
  1051. }
  1052. func (as *addrConnStream) SendMsg(m interface{}) (err error) {
  1053. defer func() {
  1054. if err != nil && err != io.EOF {
  1055. // Call finish on the client stream for errors generated by this SendMsg
  1056. // call, as these indicate problems created by this client. (Transport
  1057. // errors are converted to an io.EOF error in csAttempt.sendMsg; the real
  1058. // error will be returned from RecvMsg eventually in that case, or be
  1059. // retried.)
  1060. as.finish(err)
  1061. }
  1062. }()
  1063. if as.sentLast {
  1064. return status.Errorf(codes.Internal, "SendMsg called after CloseSend")
  1065. }
  1066. if !as.desc.ClientStreams {
  1067. as.sentLast = true
  1068. }
  1069. // load hdr, payload, data
  1070. hdr, payld, _, err := prepareMsg(m, as.codec, as.cp, as.comp)
  1071. if err != nil {
  1072. return err
  1073. }
  1074. // TODO(dfawley): should we be checking len(data) instead?
  1075. if len(payld) > *as.callInfo.maxSendMessageSize {
  1076. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payld), *as.callInfo.maxSendMessageSize)
  1077. }
  1078. if err := as.t.Write(as.s, hdr, payld, &transport.Options{Last: !as.desc.ClientStreams}); err != nil {
  1079. if !as.desc.ClientStreams {
  1080. // For non-client-streaming RPCs, we return nil instead of EOF on error
  1081. // because the generated code requires it. finish is not called; RecvMsg()
  1082. // will call it with the stream's status independently.
  1083. return nil
  1084. }
  1085. return io.EOF
  1086. }
  1087. if channelz.IsOn() {
  1088. as.t.IncrMsgSent()
  1089. }
  1090. return nil
  1091. }
  1092. func (as *addrConnStream) RecvMsg(m interface{}) (err error) {
  1093. defer func() {
  1094. if err != nil || !as.desc.ServerStreams {
  1095. // err != nil or non-server-streaming indicates end of stream.
  1096. as.finish(err)
  1097. }
  1098. }()
  1099. if !as.decompSet {
  1100. // Block until we receive headers containing received message encoding.
  1101. if ct := as.s.RecvCompress(); ct != "" && ct != encoding.Identity {
  1102. if as.dc == nil || as.dc.Type() != ct {
  1103. // No configured decompressor, or it does not match the incoming
  1104. // message encoding; attempt to find a registered compressor that does.
  1105. as.dc = nil
  1106. as.decomp = encoding.GetCompressor(ct)
  1107. }
  1108. } else {
  1109. // No compression is used; disable our decompressor.
  1110. as.dc = nil
  1111. }
  1112. // Only initialize this state once per stream.
  1113. as.decompSet = true
  1114. }
  1115. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1116. if err != nil {
  1117. if err == io.EOF {
  1118. if statusErr := as.s.Status().Err(); statusErr != nil {
  1119. return statusErr
  1120. }
  1121. return io.EOF // indicates successful end of stream.
  1122. }
  1123. return toRPCErr(err)
  1124. }
  1125. if channelz.IsOn() {
  1126. as.t.IncrMsgRecv()
  1127. }
  1128. if as.desc.ServerStreams {
  1129. // Subsequent messages should be received by subsequent RecvMsg calls.
  1130. return nil
  1131. }
  1132. // Special handling for non-server-stream rpcs.
  1133. // This recv expects EOF or errors, so we don't collect inPayload.
  1134. err = recv(as.p, as.codec, as.s, as.dc, m, *as.callInfo.maxReceiveMessageSize, nil, as.decomp)
  1135. if err == nil {
  1136. return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>"))
  1137. }
  1138. if err == io.EOF {
  1139. return as.s.Status().Err() // non-server streaming Recv returns nil on success
  1140. }
  1141. return toRPCErr(err)
  1142. }
  1143. func (as *addrConnStream) finish(err error) {
  1144. as.mu.Lock()
  1145. if as.finished {
  1146. as.mu.Unlock()
  1147. return
  1148. }
  1149. as.finished = true
  1150. if err == io.EOF {
  1151. // Ending a stream with EOF indicates a success.
  1152. err = nil
  1153. }
  1154. if as.s != nil {
  1155. as.t.CloseStream(as.s, err)
  1156. }
  1157. if err != nil {
  1158. as.ac.incrCallsFailed()
  1159. } else {
  1160. as.ac.incrCallsSucceeded()
  1161. }
  1162. as.cancel()
  1163. as.mu.Unlock()
  1164. }
  1165. // ServerStream defines the server-side behavior of a streaming RPC.
  1166. //
  1167. // All errors returned from ServerStream methods are compatible with the
  1168. // status package.
  1169. type ServerStream interface {
  1170. // SetHeader sets the header metadata. It may be called multiple times.
  1171. // When call multiple times, all the provided metadata will be merged.
  1172. // All the metadata will be sent out when one of the following happens:
  1173. // - ServerStream.SendHeader() is called;
  1174. // - The first response is sent out;
  1175. // - An RPC status is sent out (error or success).
  1176. SetHeader(metadata.MD) error
  1177. // SendHeader sends the header metadata.
  1178. // The provided md and headers set by SetHeader() will be sent.
  1179. // It fails if called multiple times.
  1180. SendHeader(metadata.MD) error
  1181. // SetTrailer sets the trailer metadata which will be sent with the RPC status.
  1182. // When called more than once, all the provided metadata will be merged.
  1183. SetTrailer(metadata.MD)
  1184. // Context returns the context for this stream.
  1185. Context() context.Context
  1186. // SendMsg sends a message. On error, SendMsg aborts the stream and the
  1187. // error is returned directly.
  1188. //
  1189. // SendMsg blocks until:
  1190. // - There is sufficient flow control to schedule m with the transport, or
  1191. // - The stream is done, or
  1192. // - The stream breaks.
  1193. //
  1194. // SendMsg does not wait until the message is received by the client. An
  1195. // untimely stream closure may result in lost messages.
  1196. //
  1197. // It is safe to have a goroutine calling SendMsg and another goroutine
  1198. // calling RecvMsg on the same stream at the same time, but it is not safe
  1199. // to call SendMsg on the same stream in different goroutines.
  1200. SendMsg(m interface{}) error
  1201. // RecvMsg blocks until it receives a message into m or the stream is
  1202. // done. It returns io.EOF when the client has performed a CloseSend. On
  1203. // any non-EOF error, the stream is aborted and the error contains the
  1204. // RPC status.
  1205. //
  1206. // It is safe to have a goroutine calling SendMsg and another goroutine
  1207. // calling RecvMsg on the same stream at the same time, but it is not
  1208. // safe to call RecvMsg on the same stream in different goroutines.
  1209. RecvMsg(m interface{}) error
  1210. }
  1211. // serverStream implements a server side Stream.
  1212. type serverStream struct {
  1213. ctx context.Context
  1214. t transport.ServerTransport
  1215. s *transport.Stream
  1216. p *parser
  1217. codec baseCodec
  1218. cp Compressor
  1219. dc Decompressor
  1220. comp encoding.Compressor
  1221. decomp encoding.Compressor
  1222. maxReceiveMessageSize int
  1223. maxSendMessageSize int
  1224. trInfo *traceInfo
  1225. statsHandler stats.Handler
  1226. binlog *binarylog.MethodLogger
  1227. // serverHeaderBinlogged indicates whether server header has been logged. It
  1228. // will happen when one of the following two happens: stream.SendHeader(),
  1229. // stream.Send().
  1230. //
  1231. // It's only checked in send and sendHeader, doesn't need to be
  1232. // synchronized.
  1233. serverHeaderBinlogged bool
  1234. mu sync.Mutex // protects trInfo.tr after the service handler runs.
  1235. }
  1236. func (ss *serverStream) Context() context.Context {
  1237. return ss.ctx
  1238. }
  1239. func (ss *serverStream) SetHeader(md metadata.MD) error {
  1240. if md.Len() == 0 {
  1241. return nil
  1242. }
  1243. return ss.s.SetHeader(md)
  1244. }
  1245. func (ss *serverStream) SendHeader(md metadata.MD) error {
  1246. err := ss.t.WriteHeader(ss.s, md)
  1247. if ss.binlog != nil && !ss.serverHeaderBinlogged {
  1248. h, _ := ss.s.Header()
  1249. ss.binlog.Log(&binarylog.ServerHeader{
  1250. Header: h,
  1251. })
  1252. ss.serverHeaderBinlogged = true
  1253. }
  1254. return err
  1255. }
  1256. func (ss *serverStream) SetTrailer(md metadata.MD) {
  1257. if md.Len() == 0 {
  1258. return
  1259. }
  1260. ss.s.SetTrailer(md)
  1261. }
  1262. func (ss *serverStream) SendMsg(m interface{}) (err error) {
  1263. defer func() {
  1264. if ss.trInfo != nil {
  1265. ss.mu.Lock()
  1266. if ss.trInfo.tr != nil {
  1267. if err == nil {
  1268. ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true)
  1269. } else {
  1270. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1271. ss.trInfo.tr.SetError()
  1272. }
  1273. }
  1274. ss.mu.Unlock()
  1275. }
  1276. if err != nil && err != io.EOF {
  1277. st, _ := status.FromError(toRPCErr(err))
  1278. ss.t.WriteStatus(ss.s, st)
  1279. // Non-user specified status was sent out. This should be an error
  1280. // case (as a server side Cancel maybe).
  1281. //
  1282. // This is not handled specifically now. User will return a final
  1283. // status from the service handler, we will log that error instead.
  1284. // This behavior is similar to an interceptor.
  1285. }
  1286. if channelz.IsOn() && err == nil {
  1287. ss.t.IncrMsgSent()
  1288. }
  1289. }()
  1290. // load hdr, payload, data
  1291. hdr, payload, data, err := prepareMsg(m, ss.codec, ss.cp, ss.comp)
  1292. if err != nil {
  1293. return err
  1294. }
  1295. // TODO(dfawley): should we be checking len(data) instead?
  1296. if len(payload) > ss.maxSendMessageSize {
  1297. return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize)
  1298. }
  1299. if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil {
  1300. return toRPCErr(err)
  1301. }
  1302. if ss.binlog != nil {
  1303. if !ss.serverHeaderBinlogged {
  1304. h, _ := ss.s.Header()
  1305. ss.binlog.Log(&binarylog.ServerHeader{
  1306. Header: h,
  1307. })
  1308. ss.serverHeaderBinlogged = true
  1309. }
  1310. ss.binlog.Log(&binarylog.ServerMessage{
  1311. Message: data,
  1312. })
  1313. }
  1314. if ss.statsHandler != nil {
  1315. ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now()))
  1316. }
  1317. return nil
  1318. }
  1319. func (ss *serverStream) RecvMsg(m interface{}) (err error) {
  1320. defer func() {
  1321. if ss.trInfo != nil {
  1322. ss.mu.Lock()
  1323. if ss.trInfo.tr != nil {
  1324. if err == nil {
  1325. ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true)
  1326. } else if err != io.EOF {
  1327. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1328. ss.trInfo.tr.SetError()
  1329. }
  1330. }
  1331. ss.mu.Unlock()
  1332. }
  1333. if err != nil && err != io.EOF {
  1334. st, _ := status.FromError(toRPCErr(err))
  1335. ss.t.WriteStatus(ss.s, st)
  1336. // Non-user specified status was sent out. This should be an error
  1337. // case (as a server side Cancel maybe).
  1338. //
  1339. // This is not handled specifically now. User will return a final
  1340. // status from the service handler, we will log that error instead.
  1341. // This behavior is similar to an interceptor.
  1342. }
  1343. if channelz.IsOn() && err == nil {
  1344. ss.t.IncrMsgRecv()
  1345. }
  1346. }()
  1347. var payInfo *payloadInfo
  1348. if ss.statsHandler != nil || ss.binlog != nil {
  1349. payInfo = &payloadInfo{}
  1350. }
  1351. if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, payInfo, ss.decomp); err != nil {
  1352. if err == io.EOF {
  1353. if ss.binlog != nil {
  1354. ss.binlog.Log(&binarylog.ClientHalfClose{})
  1355. }
  1356. return err
  1357. }
  1358. if err == io.ErrUnexpectedEOF {
  1359. err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
  1360. }
  1361. return toRPCErr(err)
  1362. }
  1363. if ss.statsHandler != nil {
  1364. ss.statsHandler.HandleRPC(ss.s.Context(), &stats.InPayload{
  1365. RecvTime: time.Now(),
  1366. Payload: m,
  1367. // TODO truncate large payload.
  1368. Data: payInfo.uncompressedBytes,
  1369. WireLength: payInfo.wireLength,
  1370. Length: len(payInfo.uncompressedBytes),
  1371. })
  1372. }
  1373. if ss.binlog != nil {
  1374. ss.binlog.Log(&binarylog.ClientMessage{
  1375. Message: payInfo.uncompressedBytes,
  1376. })
  1377. }
  1378. return nil
  1379. }
  1380. // MethodFromServerStream returns the method string for the input stream.
  1381. // The returned string is in the format of "/service/method".
  1382. func MethodFromServerStream(stream ServerStream) (string, bool) {
  1383. return Method(stream.Context())
  1384. }
  1385. // prepareMsg returns the hdr, payload and data
  1386. // using the compressors passed or using the
  1387. // passed preparedmsg
  1388. func prepareMsg(m interface{}, codec baseCodec, cp Compressor, comp encoding.Compressor) (hdr, payload, data []byte, err error) {
  1389. if preparedMsg, ok := m.(*PreparedMsg); ok {
  1390. return preparedMsg.hdr, preparedMsg.payload, preparedMsg.encodedData, nil
  1391. }
  1392. // The input interface is not a prepared msg.
  1393. // Marshal and Compress the data at this point
  1394. data, err = encode(codec, m)
  1395. if err != nil {
  1396. return nil, nil, nil, err
  1397. }
  1398. compData, err := compress(data, cp, comp)
  1399. if err != nil {
  1400. return nil, nil, nil, err
  1401. }
  1402. hdr, payload = msgHeader(data, compData)
  1403. return hdr, payload, data, nil
  1404. }