watch.go 19 KB

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