watch.go 16 KB

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