stream.go 47 KB

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