watch.go 25 KB

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