watch.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. // wg is Done when all substream goroutines have exited
  111. wg sync.WaitGroup
  112. // resumec closes to signal that all substreams should begin resuming
  113. resumec chan struct{}
  114. // closeErr is the error that closed the watch stream
  115. closeErr error
  116. }
  117. // watchRequest is issued by the subscriber to start a new watcher
  118. type watchRequest struct {
  119. ctx context.Context
  120. key string
  121. end string
  122. rev int64
  123. // send created notification event if this field is true
  124. createdNotify bool
  125. // progressNotify is for progress updates
  126. progressNotify bool
  127. // filters is the list of events to filter out
  128. filters []pb.WatchCreateRequest_FilterType
  129. // get the previous key-value pair before the event happens
  130. prevKV bool
  131. // retc receives a chan WatchResponse once the watcher is established
  132. retc chan chan WatchResponse
  133. }
  134. // watcherStream represents a registered watcher
  135. type watcherStream struct {
  136. // initReq is the request that initiated this request
  137. initReq watchRequest
  138. // outc publishes watch responses to subscriber
  139. outc chan WatchResponse
  140. // recvc buffers watch responses before publishing
  141. recvc chan *WatchResponse
  142. // donec closes when the watcherStream goroutine stops.
  143. donec chan struct{}
  144. // closing is set to true when stream should be scheduled to shutdown.
  145. closing bool
  146. // id is the registered watch id on the grpc stream
  147. id int64
  148. // buf holds all events received from etcd but not yet consumed by the client
  149. buf []*WatchResponse
  150. }
  151. func NewWatcher(c *Client) Watcher {
  152. return NewWatchFromWatchClient(pb.NewWatchClient(c.conn))
  153. }
  154. func NewWatchFromWatchClient(wc pb.WatchClient) Watcher {
  155. return &watcher{
  156. remote: wc,
  157. streams: make(map[string]*watchGrpcStream),
  158. }
  159. }
  160. // never closes
  161. var valCtxCh = make(chan struct{})
  162. var zeroTime = time.Unix(0, 0)
  163. // ctx with only the values; never Done
  164. type valCtx struct{ context.Context }
  165. func (vc *valCtx) Deadline() (time.Time, bool) { return zeroTime, false }
  166. func (vc *valCtx) Done() <-chan struct{} { return valCtxCh }
  167. func (vc *valCtx) Err() error { return nil }
  168. func (w *watcher) newWatcherGrpcStream(inctx context.Context) *watchGrpcStream {
  169. ctx, cancel := context.WithCancel(&valCtx{inctx})
  170. wgs := &watchGrpcStream{
  171. owner: w,
  172. remote: w.remote,
  173. ctx: ctx,
  174. ctxKey: fmt.Sprintf("%v", inctx),
  175. cancel: cancel,
  176. substreams: make(map[int64]*watcherStream),
  177. respc: make(chan *pb.WatchResponse),
  178. reqc: make(chan *watchRequest),
  179. donec: make(chan struct{}),
  180. errc: make(chan error, 1),
  181. closingc: make(chan *watcherStream),
  182. resumec: make(chan struct{}),
  183. }
  184. go wgs.run()
  185. return wgs
  186. }
  187. // Watch posts a watch request to run() and waits for a new watcher channel
  188. func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
  189. ow := opWatch(key, opts...)
  190. var filters []pb.WatchCreateRequest_FilterType
  191. if ow.filterPut {
  192. filters = append(filters, pb.WatchCreateRequest_NOPUT)
  193. }
  194. if ow.filterDelete {
  195. filters = append(filters, pb.WatchCreateRequest_NODELETE)
  196. }
  197. wr := &watchRequest{
  198. ctx: ctx,
  199. createdNotify: ow.createdNotify,
  200. key: string(ow.key),
  201. end: string(ow.end),
  202. rev: ow.rev,
  203. progressNotify: ow.progressNotify,
  204. filters: filters,
  205. prevKV: ow.prevKV,
  206. retc: make(chan chan WatchResponse, 1),
  207. }
  208. ok := false
  209. ctxKey := fmt.Sprintf("%v", ctx)
  210. // find or allocate appropriate grpc watch stream
  211. w.mu.Lock()
  212. if w.streams == nil {
  213. // closed
  214. w.mu.Unlock()
  215. ch := make(chan WatchResponse)
  216. close(ch)
  217. return ch
  218. }
  219. wgs := w.streams[ctxKey]
  220. if wgs == nil {
  221. wgs = w.newWatcherGrpcStream(ctx)
  222. w.streams[ctxKey] = wgs
  223. }
  224. donec := wgs.donec
  225. reqc := wgs.reqc
  226. w.mu.Unlock()
  227. // couldn't create channel; return closed channel
  228. closeCh := make(chan WatchResponse, 1)
  229. // submit request
  230. select {
  231. case reqc <- wr:
  232. ok = true
  233. case <-wr.ctx.Done():
  234. case <-donec:
  235. if wgs.closeErr != nil {
  236. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  237. break
  238. }
  239. // retry; may have dropped stream from no ctxs
  240. return w.Watch(ctx, key, opts...)
  241. }
  242. // receive channel
  243. if ok {
  244. select {
  245. case ret := <-wr.retc:
  246. return ret
  247. case <-ctx.Done():
  248. case <-donec:
  249. if wgs.closeErr != nil {
  250. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  251. break
  252. }
  253. // retry; may have dropped stream from no ctxs
  254. return w.Watch(ctx, key, opts...)
  255. }
  256. }
  257. close(closeCh)
  258. return closeCh
  259. }
  260. func (w *watcher) Close() (err error) {
  261. w.mu.Lock()
  262. streams := w.streams
  263. w.streams = nil
  264. w.mu.Unlock()
  265. for _, wgs := range streams {
  266. if werr := wgs.Close(); werr != nil {
  267. err = werr
  268. }
  269. }
  270. return err
  271. }
  272. func (w *watchGrpcStream) Close() (err error) {
  273. w.cancel()
  274. <-w.donec
  275. select {
  276. case err = <-w.errc:
  277. default:
  278. }
  279. return toErr(w.ctx, err)
  280. }
  281. func (w *watcher) closeStream(wgs *watchGrpcStream) {
  282. w.mu.Lock()
  283. close(wgs.donec)
  284. wgs.cancel()
  285. if w.streams != nil {
  286. delete(w.streams, wgs.ctxKey)
  287. }
  288. w.mu.Unlock()
  289. }
  290. func (w *watchGrpcStream) addSubstream(resp *pb.WatchResponse, ws *watcherStream) {
  291. if resp.WatchId == -1 {
  292. // failed; no channel
  293. close(ws.recvc)
  294. return
  295. }
  296. ws.id = resp.WatchId
  297. w.substreams[ws.id] = ws
  298. }
  299. func (w *watchGrpcStream) sendCloseSubstream(ws *watcherStream, resp *WatchResponse) {
  300. select {
  301. case ws.outc <- *resp:
  302. case <-ws.initReq.ctx.Done():
  303. case <-time.After(closeSendErrTimeout):
  304. }
  305. close(ws.outc)
  306. }
  307. func (w *watchGrpcStream) closeSubstream(ws *watcherStream) {
  308. // send channel response in case stream was never established
  309. select {
  310. case ws.initReq.retc <- ws.outc:
  311. default:
  312. }
  313. // close subscriber's channel
  314. if closeErr := w.closeErr; closeErr != nil && ws.initReq.ctx.Err() == nil {
  315. go w.sendCloseSubstream(ws, &WatchResponse{closeErr: w.closeErr})
  316. } else if ws.outc != nil {
  317. close(ws.outc)
  318. }
  319. if ws.id != -1 {
  320. delete(w.substreams, ws.id)
  321. return
  322. }
  323. for i := range w.resuming {
  324. if w.resuming[i] == ws {
  325. w.resuming[i] = nil
  326. return
  327. }
  328. }
  329. }
  330. // run is the root of the goroutines for managing a watcher client
  331. func (w *watchGrpcStream) run() {
  332. var wc pb.Watch_WatchClient
  333. var closeErr error
  334. // substreams marked to close but goroutine still running; needed for
  335. // avoiding double-closing recvc on grpc stream teardown
  336. closing := make(map[*watcherStream]struct{})
  337. defer func() {
  338. w.closeErr = closeErr
  339. // shutdown substreams and resuming substreams
  340. for _, ws := range w.substreams {
  341. if _, ok := closing[ws]; !ok {
  342. close(ws.recvc)
  343. closing[ws] = struct{}{}
  344. }
  345. }
  346. for _, ws := range w.resuming {
  347. if _, ok := closing[ws]; ws != nil && !ok {
  348. close(ws.recvc)
  349. closing[ws] = struct{}{}
  350. }
  351. }
  352. w.joinSubstreams()
  353. for range closing {
  354. w.closeSubstream(<-w.closingc)
  355. }
  356. w.wg.Wait()
  357. w.owner.closeStream(w)
  358. }()
  359. // start a stream with the etcd grpc server
  360. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  361. return
  362. }
  363. cancelSet := make(map[int64]struct{})
  364. for {
  365. select {
  366. // Watch() requested
  367. case wreq := <-w.reqc:
  368. outc := make(chan WatchResponse, 1)
  369. ws := &watcherStream{
  370. initReq: *wreq,
  371. id: -1,
  372. outc: outc,
  373. // unbufffered so resumes won't cause repeat events
  374. recvc: make(chan *WatchResponse),
  375. }
  376. ws.donec = make(chan struct{})
  377. w.wg.Add(1)
  378. go w.serveSubstream(ws, w.resumec)
  379. // queue up for watcher creation/resume
  380. w.resuming = append(w.resuming, ws)
  381. if len(w.resuming) == 1 {
  382. // head of resume queue, can register a new watcher
  383. wc.Send(ws.initReq.toPB())
  384. }
  385. // New events from the watch client
  386. case pbresp := <-w.respc:
  387. switch {
  388. case pbresp.Created:
  389. // response to head of queue creation
  390. if ws := w.resuming[0]; ws != nil {
  391. w.addSubstream(pbresp, ws)
  392. w.dispatchEvent(pbresp)
  393. w.resuming[0] = nil
  394. }
  395. if ws := w.nextResume(); ws != nil {
  396. wc.Send(ws.initReq.toPB())
  397. }
  398. case pbresp.Canceled:
  399. delete(cancelSet, pbresp.WatchId)
  400. if ws, ok := w.substreams[pbresp.WatchId]; ok {
  401. // signal to stream goroutine to update closingc
  402. close(ws.recvc)
  403. closing[ws] = struct{}{}
  404. }
  405. default:
  406. // dispatch to appropriate watch stream
  407. if ok := w.dispatchEvent(pbresp); ok {
  408. break
  409. }
  410. // watch response on unexpected watch id; cancel id
  411. if _, ok := cancelSet[pbresp.WatchId]; ok {
  412. break
  413. }
  414. cancelSet[pbresp.WatchId] = struct{}{}
  415. cr := &pb.WatchRequest_CancelRequest{
  416. CancelRequest: &pb.WatchCancelRequest{
  417. WatchId: pbresp.WatchId,
  418. },
  419. }
  420. req := &pb.WatchRequest{RequestUnion: cr}
  421. wc.Send(req)
  422. }
  423. // watch client failed to recv; spawn another if possible
  424. case err := <-w.errc:
  425. if isHaltErr(w.ctx, err) || toErr(w.ctx, err) == v3rpc.ErrNoLeader {
  426. closeErr = err
  427. return
  428. }
  429. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  430. return
  431. }
  432. if ws := w.nextResume(); ws != nil {
  433. wc.Send(ws.initReq.toPB())
  434. }
  435. cancelSet = make(map[int64]struct{})
  436. case <-w.ctx.Done():
  437. return
  438. case ws := <-w.closingc:
  439. w.closeSubstream(ws)
  440. delete(closing, ws)
  441. if len(w.substreams)+len(w.resuming) == 0 {
  442. // no more watchers on this stream, shutdown
  443. return
  444. }
  445. }
  446. }
  447. }
  448. // nextResume chooses the next resuming to register with the grpc stream. Abandoned
  449. // streams are marked as nil in the queue since the head must wait for its inflight registration.
  450. func (w *watchGrpcStream) nextResume() *watcherStream {
  451. for len(w.resuming) != 0 {
  452. if w.resuming[0] != nil {
  453. return w.resuming[0]
  454. }
  455. w.resuming = w.resuming[1:len(w.resuming)]
  456. }
  457. return nil
  458. }
  459. // dispatchEvent sends a WatchResponse to the appropriate watcher stream
  460. func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
  461. ws, ok := w.substreams[pbresp.WatchId]
  462. if !ok {
  463. return false
  464. }
  465. events := make([]*Event, len(pbresp.Events))
  466. for i, ev := range pbresp.Events {
  467. events[i] = (*Event)(ev)
  468. }
  469. wr := &WatchResponse{
  470. Header: *pbresp.Header,
  471. Events: events,
  472. CompactRevision: pbresp.CompactRevision,
  473. Created: pbresp.Created,
  474. Canceled: pbresp.Canceled,
  475. }
  476. select {
  477. case ws.recvc <- wr:
  478. case <-ws.donec:
  479. return false
  480. }
  481. return true
  482. }
  483. // serveWatchClient forwards messages from the grpc stream to run()
  484. func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) {
  485. for {
  486. resp, err := wc.Recv()
  487. if err != nil {
  488. select {
  489. case w.errc <- err:
  490. case <-w.donec:
  491. }
  492. return
  493. }
  494. select {
  495. case w.respc <- resp:
  496. case <-w.donec:
  497. return
  498. }
  499. }
  500. }
  501. // serveSubstream forwards watch responses from run() to the subscriber
  502. func (w *watchGrpcStream) serveSubstream(ws *watcherStream, resumec chan struct{}) {
  503. if ws.closing {
  504. panic("created substream goroutine but substream is closing")
  505. }
  506. // nextRev is the minimum expected next revision
  507. nextRev := ws.initReq.rev
  508. resuming := false
  509. defer func() {
  510. if !resuming {
  511. ws.closing = true
  512. }
  513. close(ws.donec)
  514. if !resuming {
  515. w.closingc <- ws
  516. }
  517. w.wg.Done()
  518. }()
  519. emptyWr := &WatchResponse{}
  520. for {
  521. curWr := emptyWr
  522. outc := ws.outc
  523. if len(ws.buf) > 0 {
  524. curWr = ws.buf[0]
  525. } else {
  526. outc = nil
  527. }
  528. select {
  529. case outc <- *curWr:
  530. if ws.buf[0].Err() != nil {
  531. return
  532. }
  533. ws.buf[0] = nil
  534. ws.buf = ws.buf[1:]
  535. case wr, ok := <-ws.recvc:
  536. if !ok {
  537. // shutdown from closeSubstream
  538. return
  539. }
  540. if wr.Created {
  541. if ws.initReq.retc != nil {
  542. ws.initReq.retc <- ws.outc
  543. // to prevent next write from taking the slot in buffered channel
  544. // and posting duplicate create events
  545. ws.initReq.retc = nil
  546. // send first creation event only if requested
  547. if ws.initReq.createdNotify {
  548. ws.outc <- *wr
  549. }
  550. // once the watch channel is returned, a current revision
  551. // watch must resume at the store revision. This is necessary
  552. // for the following case to work as expected:
  553. // wch := m1.Watch("a")
  554. // m2.Put("a", "b")
  555. // <-wch
  556. // If the revision is only bound on the first observed event,
  557. // if wch is disconnected before the Put is issued, then reconnects
  558. // after it is committed, it'll miss the Put.
  559. if ws.initReq.rev == 0 {
  560. nextRev = wr.Header.Revision
  561. }
  562. }
  563. } else {
  564. // current progress of watch; <= store revision
  565. nextRev = wr.Header.Revision
  566. }
  567. if len(wr.Events) > 0 {
  568. nextRev = wr.Events[len(wr.Events)-1].Kv.ModRevision + 1
  569. }
  570. ws.initReq.rev = nextRev
  571. // created event is already sent above,
  572. // watcher should not post duplicate events
  573. if wr.Created {
  574. continue
  575. }
  576. // TODO pause channel if buffer gets too large
  577. ws.buf = append(ws.buf, wr)
  578. case <-w.ctx.Done():
  579. return
  580. case <-ws.initReq.ctx.Done():
  581. return
  582. case <-resumec:
  583. resuming = true
  584. return
  585. }
  586. }
  587. // lazily send cancel message if events on missing id
  588. }
  589. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  590. // mark all substreams as resuming
  591. close(w.resumec)
  592. w.resumec = make(chan struct{})
  593. w.joinSubstreams()
  594. for _, ws := range w.substreams {
  595. ws.id = -1
  596. w.resuming = append(w.resuming, ws)
  597. }
  598. // strip out nils, if any
  599. var resuming []*watcherStream
  600. for _, ws := range w.resuming {
  601. if ws != nil {
  602. resuming = append(resuming, ws)
  603. }
  604. }
  605. w.resuming = resuming
  606. w.substreams = make(map[int64]*watcherStream)
  607. // connect to grpc stream while accepting watcher cancelation
  608. stopc := make(chan struct{})
  609. donec := w.waitCancelSubstreams(stopc)
  610. wc, err := w.openWatchClient()
  611. close(stopc)
  612. <-donec
  613. // serve all non-closing streams, even if there's a client error
  614. // so that the teardown path can shutdown the streams as expected.
  615. for _, ws := range w.resuming {
  616. if ws.closing {
  617. continue
  618. }
  619. ws.donec = make(chan struct{})
  620. w.wg.Add(1)
  621. go w.serveSubstream(ws, w.resumec)
  622. }
  623. if err != nil {
  624. return nil, v3rpc.Error(err)
  625. }
  626. // receive data from new grpc stream
  627. go w.serveWatchClient(wc)
  628. return wc, nil
  629. }
  630. func (w *watchGrpcStream) waitCancelSubstreams(stopc <-chan struct{}) <-chan struct{} {
  631. var wg sync.WaitGroup
  632. wg.Add(len(w.resuming))
  633. donec := make(chan struct{})
  634. for i := range w.resuming {
  635. go func(ws *watcherStream) {
  636. defer wg.Done()
  637. if ws.closing {
  638. if ws.initReq.ctx.Err() != nil && ws.outc != nil {
  639. close(ws.outc)
  640. ws.outc = nil
  641. }
  642. return
  643. }
  644. select {
  645. case <-ws.initReq.ctx.Done():
  646. // closed ws will be removed from resuming
  647. ws.closing = true
  648. close(ws.outc)
  649. ws.outc = nil
  650. go func() { w.closingc <- ws }()
  651. case <-stopc:
  652. }
  653. }(w.resuming[i])
  654. }
  655. go func() {
  656. defer close(donec)
  657. wg.Wait()
  658. }()
  659. return donec
  660. }
  661. // joinSubstream waits for all substream goroutines to complete
  662. func (w *watchGrpcStream) joinSubstreams() {
  663. for _, ws := range w.substreams {
  664. <-ws.donec
  665. }
  666. for _, ws := range w.resuming {
  667. if ws != nil {
  668. <-ws.donec
  669. }
  670. }
  671. }
  672. // openWatchClient retries opening a watchclient until retryConnection fails
  673. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  674. for {
  675. select {
  676. case <-w.ctx.Done():
  677. if err == nil {
  678. return nil, w.ctx.Err()
  679. }
  680. return nil, err
  681. default:
  682. }
  683. if ws, err = w.remote.Watch(w.ctx, grpc.FailFast(false)); ws != nil && err == nil {
  684. break
  685. }
  686. if isHaltErr(w.ctx, err) {
  687. return nil, v3rpc.Error(err)
  688. }
  689. }
  690. return ws, nil
  691. }
  692. // toPB converts an internal watch request structure to its protobuf messagefunc (wr *watchRequest)
  693. func (wr *watchRequest) toPB() *pb.WatchRequest {
  694. req := &pb.WatchCreateRequest{
  695. StartRevision: wr.rev,
  696. Key: []byte(wr.key),
  697. RangeEnd: []byte(wr.end),
  698. ProgressNotify: wr.progressNotify,
  699. Filters: wr.filters,
  700. PrevKv: wr.prevKV,
  701. }
  702. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  703. return &pb.WatchRequest{RequestUnion: cr}
  704. }