watch.go 22 KB

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