watch.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. v3rpc "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. mvccpb "github.com/coreos/etcd/mvcc/mvccpb"
  22. "golang.org/x/net/context"
  23. "google.golang.org/grpc"
  24. )
  25. const (
  26. EventTypeDelete = mvccpb.DELETE
  27. EventTypePut = mvccpb.PUT
  28. closeSendErrTimeout = 250 * time.Millisecond
  29. )
  30. type Event mvccpb.Event
  31. type WatchChan <-chan WatchResponse
  32. type Watcher interface {
  33. // Watch watches on a key or prefix. The watched events will be returned
  34. // through the returned channel.
  35. // If the watch is slow or the required rev is compacted, the watch request
  36. // might be canceled from the server-side and the chan will be closed.
  37. // 'opts' can be: 'WithRev' and/or 'WithPrefix'.
  38. Watch(ctx context.Context, key string, opts ...OpOption) WatchChan
  39. // Close closes the watcher and cancels all watch requests.
  40. Close() error
  41. }
  42. type WatchResponse struct {
  43. Header pb.ResponseHeader
  44. Events []*Event
  45. // CompactRevision is the minimum revision the watcher may receive.
  46. CompactRevision int64
  47. // Canceled is used to indicate watch failure.
  48. // If the watch failed and the stream was about to close, before the channel is closed,
  49. // the channel sends a final response that has Canceled set to true with a non-nil Err().
  50. Canceled bool
  51. // Created is used to indicate the creation of the watcher.
  52. Created bool
  53. closeErr error
  54. }
  55. // IsCreate returns true if the event tells that the key is newly created.
  56. func (e *Event) IsCreate() bool {
  57. return e.Type == EventTypePut && e.Kv.CreateRevision == e.Kv.ModRevision
  58. }
  59. // IsModify returns true if the event tells that a new value is put on existing key.
  60. func (e *Event) IsModify() bool {
  61. return e.Type == EventTypePut && e.Kv.CreateRevision != e.Kv.ModRevision
  62. }
  63. // Err is the error value if this WatchResponse holds an error.
  64. func (wr *WatchResponse) Err() error {
  65. switch {
  66. case wr.closeErr != nil:
  67. return v3rpc.Error(wr.closeErr)
  68. case wr.CompactRevision != 0:
  69. return v3rpc.ErrCompacted
  70. case wr.Canceled:
  71. return v3rpc.ErrFutureRev
  72. }
  73. return nil
  74. }
  75. // IsProgressNotify returns true if the WatchResponse is progress notification.
  76. func (wr *WatchResponse) IsProgressNotify() bool {
  77. return len(wr.Events) == 0 && !wr.Canceled && !wr.Created && wr.CompactRevision == 0 && wr.Header.Revision != 0
  78. }
  79. // watcher implements the Watcher interface
  80. type watcher struct {
  81. remote pb.WatchClient
  82. // mu protects the grpc streams map
  83. mu sync.RWMutex
  84. // streams holds all the active grpc streams keyed by ctx value.
  85. streams map[string]*watchGrpcStream
  86. }
  87. // watchGrpcStream tracks all watch resources attached to a single grpc stream.
  88. type watchGrpcStream struct {
  89. owner *watcher
  90. remote pb.WatchClient
  91. // ctx controls internal remote.Watch requests
  92. ctx context.Context
  93. // ctxKey is the key used when looking up this stream's context
  94. ctxKey string
  95. cancel context.CancelFunc
  96. // substreams holds all active watchers on this grpc stream
  97. substreams map[int64]*watcherStream
  98. // resuming holds all resuming watchers on this grpc stream
  99. resuming []*watcherStream
  100. // reqc sends a watch request from Watch() to the main goroutine
  101. reqc chan *watchRequest
  102. // respc receives data from the watch client
  103. respc chan *pb.WatchResponse
  104. // donec closes to broadcast shutdown
  105. donec chan struct{}
  106. // errc transmits errors from grpc Recv to the watch stream reconn logic
  107. errc chan error
  108. // closingc gets the watcherStream of closing watchers
  109. closingc chan *watcherStream
  110. // resumec closes to signal that all substreams should begin resuming
  111. resumec chan struct{}
  112. // closeErr is the error that closed the watch stream
  113. closeErr error
  114. }
  115. // watchRequest is issued by the subscriber to start a new watcher
  116. type watchRequest struct {
  117. ctx context.Context
  118. key string
  119. end string
  120. rev int64
  121. // send created notification event if this field is true
  122. createdNotify bool
  123. // progressNotify is for progress updates
  124. progressNotify bool
  125. // filters is the list of events to filter out
  126. filters []pb.WatchCreateRequest_FilterType
  127. // get the previous key-value pair before the event happens
  128. prevKV bool
  129. // retc receives a chan WatchResponse once the watcher is established
  130. retc chan chan WatchResponse
  131. }
  132. // watcherStream represents a registered watcher
  133. type watcherStream struct {
  134. // initReq is the request that initiated this request
  135. initReq watchRequest
  136. // outc publishes watch responses to subscriber
  137. outc chan WatchResponse
  138. // recvc buffers watch responses before publishing
  139. recvc chan *WatchResponse
  140. // donec closes when the watcherStream goroutine stops.
  141. donec chan struct{}
  142. // closing is set to true when stream should be scheduled to shutdown.
  143. closing bool
  144. // id is the registered watch id on the grpc stream
  145. id int64
  146. // buf holds all events received from etcd but not yet consumed by the client
  147. buf []*WatchResponse
  148. }
  149. func NewWatcher(c *Client) Watcher {
  150. return NewWatchFromWatchClient(pb.NewWatchClient(c.conn))
  151. }
  152. func NewWatchFromWatchClient(wc pb.WatchClient) Watcher {
  153. return &watcher{
  154. remote: wc,
  155. streams: make(map[string]*watchGrpcStream),
  156. }
  157. }
  158. // never closes
  159. var valCtxCh = make(chan struct{})
  160. var zeroTime = time.Unix(0, 0)
  161. // ctx with only the values; never Done
  162. type valCtx struct{ context.Context }
  163. func (vc *valCtx) Deadline() (time.Time, bool) { return zeroTime, false }
  164. func (vc *valCtx) Done() <-chan struct{} { return valCtxCh }
  165. func (vc *valCtx) Err() error { return nil }
  166. func (w *watcher) newWatcherGrpcStream(inctx context.Context) *watchGrpcStream {
  167. ctx, cancel := context.WithCancel(&valCtx{inctx})
  168. wgs := &watchGrpcStream{
  169. owner: w,
  170. remote: w.remote,
  171. ctx: ctx,
  172. ctxKey: fmt.Sprintf("%v", inctx),
  173. cancel: cancel,
  174. substreams: make(map[int64]*watcherStream),
  175. respc: make(chan *pb.WatchResponse),
  176. reqc: make(chan *watchRequest),
  177. donec: make(chan struct{}),
  178. errc: make(chan error, 1),
  179. closingc: make(chan *watcherStream),
  180. resumec: make(chan struct{}),
  181. }
  182. go wgs.run()
  183. return wgs
  184. }
  185. // Watch posts a watch request to run() and waits for a new watcher channel
  186. func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
  187. ow := opWatch(key, opts...)
  188. var filters []pb.WatchCreateRequest_FilterType
  189. if ow.filterPut {
  190. filters = append(filters, pb.WatchCreateRequest_NOPUT)
  191. }
  192. if ow.filterDelete {
  193. filters = append(filters, pb.WatchCreateRequest_NODELETE)
  194. }
  195. wr := &watchRequest{
  196. ctx: ctx,
  197. createdNotify: ow.createdNotify,
  198. key: string(ow.key),
  199. end: string(ow.end),
  200. rev: ow.rev,
  201. progressNotify: ow.progressNotify,
  202. filters: filters,
  203. prevKV: ow.prevKV,
  204. retc: make(chan chan WatchResponse, 1),
  205. }
  206. ok := false
  207. ctxKey := fmt.Sprintf("%v", ctx)
  208. // find or allocate appropriate grpc watch stream
  209. w.mu.Lock()
  210. if w.streams == nil {
  211. // closed
  212. w.mu.Unlock()
  213. ch := make(chan WatchResponse)
  214. close(ch)
  215. return ch
  216. }
  217. wgs := w.streams[ctxKey]
  218. if wgs == nil {
  219. wgs = w.newWatcherGrpcStream(ctx)
  220. w.streams[ctxKey] = wgs
  221. }
  222. donec := wgs.donec
  223. reqc := wgs.reqc
  224. w.mu.Unlock()
  225. // couldn't create channel; return closed channel
  226. closeCh := make(chan WatchResponse, 1)
  227. // submit request
  228. select {
  229. case reqc <- wr:
  230. ok = true
  231. case <-wr.ctx.Done():
  232. case <-donec:
  233. if wgs.closeErr != nil {
  234. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  235. break
  236. }
  237. // retry; may have dropped stream from no ctxs
  238. return w.Watch(ctx, key, opts...)
  239. }
  240. // receive channel
  241. if ok {
  242. select {
  243. case ret := <-wr.retc:
  244. return ret
  245. case <-ctx.Done():
  246. case <-donec:
  247. if wgs.closeErr != nil {
  248. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  249. break
  250. }
  251. // retry; may have dropped stream from no ctxs
  252. return w.Watch(ctx, key, opts...)
  253. }
  254. }
  255. close(closeCh)
  256. return closeCh
  257. }
  258. func (w *watcher) Close() (err error) {
  259. w.mu.Lock()
  260. streams := w.streams
  261. w.streams = nil
  262. w.mu.Unlock()
  263. for _, wgs := range streams {
  264. if werr := wgs.Close(); werr != nil {
  265. err = werr
  266. }
  267. }
  268. return err
  269. }
  270. func (w *watchGrpcStream) Close() (err error) {
  271. w.cancel()
  272. <-w.donec
  273. select {
  274. case err = <-w.errc:
  275. default:
  276. }
  277. return toErr(w.ctx, err)
  278. }
  279. func (w *watcher) closeStream(wgs *watchGrpcStream) {
  280. w.mu.Lock()
  281. close(wgs.donec)
  282. wgs.cancel()
  283. if w.streams != nil {
  284. delete(w.streams, wgs.ctxKey)
  285. }
  286. w.mu.Unlock()
  287. }
  288. func (w *watchGrpcStream) addSubstream(resp *pb.WatchResponse, ws *watcherStream) {
  289. if resp.WatchId == -1 {
  290. // failed; no channel
  291. close(ws.recvc)
  292. return
  293. }
  294. ws.id = resp.WatchId
  295. w.substreams[ws.id] = ws
  296. }
  297. func (w *watchGrpcStream) sendCloseSubstream(ws *watcherStream, resp *WatchResponse) {
  298. select {
  299. case ws.outc <- *resp:
  300. case <-ws.initReq.ctx.Done():
  301. case <-time.After(closeSendErrTimeout):
  302. }
  303. close(ws.outc)
  304. }
  305. func (w *watchGrpcStream) closeSubstream(ws *watcherStream) {
  306. // send channel response in case stream was never established
  307. select {
  308. case ws.initReq.retc <- ws.outc:
  309. default:
  310. }
  311. // close subscriber's channel
  312. if closeErr := w.closeErr; closeErr != nil && ws.initReq.ctx.Err() == nil {
  313. go w.sendCloseSubstream(ws, &WatchResponse{closeErr: w.closeErr})
  314. } else if ws.outc != nil {
  315. close(ws.outc)
  316. }
  317. if ws.id != -1 {
  318. delete(w.substreams, ws.id)
  319. return
  320. }
  321. for i := range w.resuming {
  322. if w.resuming[i] == ws {
  323. w.resuming[i] = nil
  324. return
  325. }
  326. }
  327. }
  328. // run is the root of the goroutines for managing a watcher client
  329. func (w *watchGrpcStream) run() {
  330. var wc pb.Watch_WatchClient
  331. var closeErr error
  332. // substreams marked to close but goroutine still running; needed for
  333. // avoiding double-closing recvc on grpc stream teardown
  334. closing := make(map[*watcherStream]struct{})
  335. defer func() {
  336. w.closeErr = closeErr
  337. // shutdown substreams and resuming substreams
  338. for _, ws := range w.substreams {
  339. if _, ok := closing[ws]; !ok {
  340. close(ws.recvc)
  341. closing[ws] = struct{}{}
  342. }
  343. }
  344. for _, ws := range w.resuming {
  345. if _, ok := closing[ws]; ws != nil && !ok {
  346. close(ws.recvc)
  347. closing[ws] = struct{}{}
  348. }
  349. }
  350. w.joinSubstreams()
  351. for range closing {
  352. w.closeSubstream(<-w.closingc)
  353. }
  354. w.owner.closeStream(w)
  355. }()
  356. // start a stream with the etcd grpc server
  357. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  358. return
  359. }
  360. cancelSet := make(map[int64]struct{})
  361. for {
  362. select {
  363. // Watch() requested
  364. case wreq := <-w.reqc:
  365. outc := make(chan WatchResponse, 1)
  366. ws := &watcherStream{
  367. initReq: *wreq,
  368. id: -1,
  369. outc: outc,
  370. // unbufffered so resumes won't cause repeat events
  371. recvc: make(chan *WatchResponse),
  372. }
  373. ws.donec = make(chan struct{})
  374. go w.serveSubstream(ws, w.resumec)
  375. // queue up for watcher creation/resume
  376. w.resuming = append(w.resuming, ws)
  377. if len(w.resuming) == 1 {
  378. // head of resume queue, can register a new watcher
  379. wc.Send(ws.initReq.toPB())
  380. }
  381. // New events from the watch client
  382. case pbresp := <-w.respc:
  383. switch {
  384. case pbresp.Created:
  385. // response to head of queue creation
  386. if ws := w.resuming[0]; ws != nil {
  387. w.addSubstream(pbresp, ws)
  388. w.dispatchEvent(pbresp)
  389. w.resuming[0] = nil
  390. }
  391. if ws := w.nextResume(); ws != nil {
  392. wc.Send(ws.initReq.toPB())
  393. }
  394. case pbresp.Canceled:
  395. delete(cancelSet, pbresp.WatchId)
  396. if ws, ok := w.substreams[pbresp.WatchId]; ok {
  397. // signal to stream goroutine to update closingc
  398. close(ws.recvc)
  399. closing[ws] = struct{}{}
  400. }
  401. default:
  402. // dispatch to appropriate watch stream
  403. if ok := w.dispatchEvent(pbresp); ok {
  404. break
  405. }
  406. // watch response on unexpected watch id; cancel id
  407. if _, ok := cancelSet[pbresp.WatchId]; ok {
  408. break
  409. }
  410. cancelSet[pbresp.WatchId] = struct{}{}
  411. cr := &pb.WatchRequest_CancelRequest{
  412. CancelRequest: &pb.WatchCancelRequest{
  413. WatchId: pbresp.WatchId,
  414. },
  415. }
  416. req := &pb.WatchRequest{RequestUnion: cr}
  417. wc.Send(req)
  418. }
  419. // watch client failed to recv; spawn another if possible
  420. case err := <-w.errc:
  421. if isHaltErr(w.ctx, err) || toErr(w.ctx, err) == v3rpc.ErrNoLeader {
  422. closeErr = err
  423. return
  424. }
  425. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  426. return
  427. }
  428. if ws := w.nextResume(); ws != nil {
  429. wc.Send(ws.initReq.toPB())
  430. }
  431. cancelSet = make(map[int64]struct{})
  432. case <-w.ctx.Done():
  433. return
  434. case ws := <-w.closingc:
  435. w.closeSubstream(ws)
  436. delete(closing, ws)
  437. if len(w.substreams)+len(w.resuming) == 0 {
  438. // no more watchers on this stream, shutdown
  439. return
  440. }
  441. }
  442. }
  443. }
  444. // nextResume chooses the next resuming to register with the grpc stream. Abandoned
  445. // streams are marked as nil in the queue since the head must wait for its inflight registration.
  446. func (w *watchGrpcStream) nextResume() *watcherStream {
  447. for len(w.resuming) != 0 {
  448. if w.resuming[0] != nil {
  449. return w.resuming[0]
  450. }
  451. w.resuming = w.resuming[1:len(w.resuming)]
  452. }
  453. return nil
  454. }
  455. // dispatchEvent sends a WatchResponse to the appropriate watcher stream
  456. func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
  457. ws, ok := w.substreams[pbresp.WatchId]
  458. if !ok {
  459. return false
  460. }
  461. events := make([]*Event, len(pbresp.Events))
  462. for i, ev := range pbresp.Events {
  463. events[i] = (*Event)(ev)
  464. }
  465. wr := &WatchResponse{
  466. Header: *pbresp.Header,
  467. Events: events,
  468. CompactRevision: pbresp.CompactRevision,
  469. Created: pbresp.Created,
  470. Canceled: pbresp.Canceled,
  471. }
  472. select {
  473. case ws.recvc <- wr:
  474. case <-ws.donec:
  475. return false
  476. }
  477. return true
  478. }
  479. // serveWatchClient forwards messages from the grpc stream to run()
  480. func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) {
  481. for {
  482. resp, err := wc.Recv()
  483. if err != nil {
  484. select {
  485. case w.errc <- err:
  486. case <-w.donec:
  487. }
  488. return
  489. }
  490. select {
  491. case w.respc <- resp:
  492. case <-w.donec:
  493. return
  494. }
  495. }
  496. }
  497. // serveSubstream forwards watch responses from run() to the subscriber
  498. func (w *watchGrpcStream) serveSubstream(ws *watcherStream, resumec chan struct{}) {
  499. if ws.closing {
  500. panic("created substream goroutine but substream is closing")
  501. }
  502. // nextRev is the minimum expected next revision
  503. nextRev := ws.initReq.rev
  504. resuming := false
  505. defer func() {
  506. if !resuming {
  507. ws.closing = true
  508. }
  509. close(ws.donec)
  510. if !resuming {
  511. w.closingc <- ws
  512. }
  513. }()
  514. emptyWr := &WatchResponse{}
  515. for {
  516. curWr := emptyWr
  517. outc := ws.outc
  518. if len(ws.buf) > 0 {
  519. curWr = ws.buf[0]
  520. } else {
  521. outc = nil
  522. }
  523. select {
  524. case outc <- *curWr:
  525. if ws.buf[0].Err() != nil {
  526. return
  527. }
  528. ws.buf[0] = nil
  529. ws.buf = ws.buf[1:]
  530. case wr, ok := <-ws.recvc:
  531. if !ok {
  532. // shutdown from closeSubstream
  533. return
  534. }
  535. if wr.Created {
  536. if ws.initReq.retc != nil {
  537. ws.initReq.retc <- ws.outc
  538. // to prevent next write from taking the slot in buffered channel
  539. // and posting duplicate create events
  540. ws.initReq.retc = nil
  541. // send first creation event only if requested
  542. if ws.initReq.createdNotify {
  543. ws.outc <- *wr
  544. }
  545. }
  546. }
  547. nextRev = wr.Header.Revision
  548. if len(wr.Events) > 0 {
  549. nextRev = wr.Events[len(wr.Events)-1].Kv.ModRevision + 1
  550. }
  551. ws.initReq.rev = nextRev
  552. // created event is already sent above,
  553. // watcher should not post duplicate events
  554. if wr.Created {
  555. continue
  556. }
  557. // TODO pause channel if buffer gets too large
  558. ws.buf = append(ws.buf, wr)
  559. case <-w.ctx.Done():
  560. return
  561. case <-ws.initReq.ctx.Done():
  562. return
  563. case <-resumec:
  564. resuming = true
  565. return
  566. }
  567. }
  568. // lazily send cancel message if events on missing id
  569. }
  570. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  571. // mark all substreams as resuming
  572. close(w.resumec)
  573. w.resumec = make(chan struct{})
  574. w.joinSubstreams()
  575. for _, ws := range w.substreams {
  576. ws.id = -1
  577. w.resuming = append(w.resuming, ws)
  578. }
  579. // strip out nils, if any
  580. var resuming []*watcherStream
  581. for _, ws := range w.resuming {
  582. if ws != nil {
  583. resuming = append(resuming, ws)
  584. }
  585. }
  586. w.resuming = resuming
  587. w.substreams = make(map[int64]*watcherStream)
  588. // connect to grpc stream while accepting watcher cancelation
  589. stopc := make(chan struct{})
  590. donec := w.waitCancelSubstreams(stopc)
  591. wc, err := w.openWatchClient()
  592. close(stopc)
  593. <-donec
  594. // serve all non-closing streams, even if there's a client error
  595. // so that the teardown path can shutdown the streams as expected.
  596. for _, ws := range w.resuming {
  597. if ws.closing {
  598. continue
  599. }
  600. ws.donec = make(chan struct{})
  601. go w.serveSubstream(ws, w.resumec)
  602. }
  603. if err != nil {
  604. return nil, v3rpc.Error(err)
  605. }
  606. // receive data from new grpc stream
  607. go w.serveWatchClient(wc)
  608. return wc, nil
  609. }
  610. func (w *watchGrpcStream) waitCancelSubstreams(stopc <-chan struct{}) <-chan struct{} {
  611. var wg sync.WaitGroup
  612. wg.Add(len(w.resuming))
  613. donec := make(chan struct{})
  614. for i := range w.resuming {
  615. go func(ws *watcherStream) {
  616. defer wg.Done()
  617. if ws.closing {
  618. return
  619. }
  620. select {
  621. case <-ws.initReq.ctx.Done():
  622. // closed ws will be removed from resuming
  623. ws.closing = true
  624. close(ws.outc)
  625. ws.outc = nil
  626. go func() { w.closingc <- ws }()
  627. case <-stopc:
  628. }
  629. }(w.resuming[i])
  630. }
  631. go func() {
  632. defer close(donec)
  633. wg.Wait()
  634. }()
  635. return donec
  636. }
  637. // joinSubstream waits for all substream goroutines to complete
  638. func (w *watchGrpcStream) joinSubstreams() {
  639. for _, ws := range w.substreams {
  640. <-ws.donec
  641. }
  642. for _, ws := range w.resuming {
  643. if ws != nil {
  644. <-ws.donec
  645. }
  646. }
  647. }
  648. // openWatchClient retries opening a watchclient until retryConnection fails
  649. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  650. for {
  651. select {
  652. case <-w.ctx.Done():
  653. if err == nil {
  654. return nil, w.ctx.Err()
  655. }
  656. return nil, err
  657. default:
  658. }
  659. if ws, err = w.remote.Watch(w.ctx, grpc.FailFast(false)); ws != nil && err == nil {
  660. break
  661. }
  662. if isHaltErr(w.ctx, err) {
  663. return nil, v3rpc.Error(err)
  664. }
  665. }
  666. return ws, nil
  667. }
  668. // toPB converts an internal watch request structure to its protobuf messagefunc (wr *watchRequest)
  669. func (wr *watchRequest) toPB() *pb.WatchRequest {
  670. req := &pb.WatchCreateRequest{
  671. StartRevision: wr.rev,
  672. Key: []byte(wr.key),
  673. RangeEnd: []byte(wr.end),
  674. ProgressNotify: wr.progressNotify,
  675. Filters: wr.filters,
  676. PrevKv: wr.prevKV,
  677. }
  678. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  679. return &pb.WatchRequest{RequestUnion: cr}
  680. }