stream.go 45 KB

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