watch.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. var closeErr error
  448. emptyWr := &WatchResponse{}
  449. wrs := []*WatchResponse{}
  450. resuming := false
  451. closing := false
  452. for !closing {
  453. curWr := emptyWr
  454. outc := ws.outc
  455. if len(wrs) > 0 {
  456. curWr = wrs[0]
  457. } else {
  458. outc = nil
  459. }
  460. select {
  461. case outc <- *curWr:
  462. if wrs[0].Err() != nil {
  463. closing = true
  464. break
  465. }
  466. var newRev int64
  467. if len(wrs[0].Events) > 0 {
  468. newRev = wrs[0].Events[len(wrs[0].Events)-1].Kv.ModRevision
  469. } else {
  470. newRev = wrs[0].Header.Revision
  471. }
  472. if newRev != ws.lastRev {
  473. ws.lastRev = newRev
  474. }
  475. wrs[0] = nil
  476. wrs = wrs[1:]
  477. case wr, ok := <-ws.recvc:
  478. if !ok {
  479. // shutdown from closeStream
  480. return
  481. }
  482. // resume up to last seen event if disconnected
  483. if resuming && wr.Err() == nil {
  484. resuming = false
  485. // trim events already seen
  486. for i := 0; i < len(wr.Events); i++ {
  487. if wr.Events[i].Kv.ModRevision > ws.lastRev {
  488. wr.Events = wr.Events[i:]
  489. break
  490. }
  491. }
  492. // only forward new events
  493. if wr.Events[0].Kv.ModRevision == ws.lastRev {
  494. break
  495. }
  496. }
  497. resuming = false
  498. // TODO don't keep buffering if subscriber stops reading
  499. wrs = append(wrs, wr)
  500. case resumeRev := <-ws.resumec:
  501. wrs = nil
  502. resuming = true
  503. if resumeRev == -1 {
  504. // pause serving stream while resume gets set up
  505. break
  506. }
  507. if resumeRev != ws.lastRev {
  508. panic("unexpected resume revision")
  509. }
  510. case <-w.donec:
  511. closing = true
  512. closeErr = w.closeErr
  513. case <-ws.initReq.ctx.Done():
  514. closing = true
  515. }
  516. }
  517. // try to send off close error
  518. if closeErr != nil {
  519. select {
  520. case ws.outc <- WatchResponse{closeErr: w.closeErr}:
  521. case <-w.donec:
  522. case <-time.After(closeSendErrTimeout):
  523. }
  524. }
  525. w.mu.Lock()
  526. w.closeStream(ws)
  527. w.mu.Unlock()
  528. // lazily send cancel message if events on missing id
  529. }
  530. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  531. ws, rerr := w.resume()
  532. if rerr != nil {
  533. return nil, rerr
  534. }
  535. go w.serveWatchClient(ws)
  536. return ws, nil
  537. }
  538. // resume creates a new WatchClient with all current watchers reestablished
  539. func (w *watchGrpcStream) resume() (ws pb.Watch_WatchClient, err error) {
  540. for {
  541. if ws, err = w.openWatchClient(); err != nil {
  542. break
  543. } else if err = w.resumeWatchers(ws); err == nil {
  544. break
  545. }
  546. }
  547. return ws, v3rpc.Error(err)
  548. }
  549. // openWatchClient retries opening a watchclient until retryConnection fails
  550. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  551. for {
  552. select {
  553. case <-w.stopc:
  554. if err == nil {
  555. err = context.Canceled
  556. }
  557. return nil, err
  558. default:
  559. }
  560. if ws, err = w.remote.Watch(w.ctx); ws != nil && err == nil {
  561. break
  562. }
  563. if isHaltErr(w.ctx, err) {
  564. return nil, v3rpc.Error(err)
  565. }
  566. }
  567. return ws, nil
  568. }
  569. // resumeWatchers rebuilds every registered watcher on a new client
  570. func (w *watchGrpcStream) resumeWatchers(wc pb.Watch_WatchClient) error {
  571. w.mu.RLock()
  572. streams := make([]*watcherStream, 0, len(w.streams))
  573. for _, ws := range w.streams {
  574. streams = append(streams, ws)
  575. }
  576. w.mu.RUnlock()
  577. for _, ws := range streams {
  578. // pause serveStream
  579. ws.resumec <- -1
  580. // reconstruct watcher from initial request
  581. if ws.lastRev != 0 {
  582. ws.initReq.rev = ws.lastRev
  583. }
  584. if err := wc.Send(ws.initReq.toPB()); err != nil {
  585. return err
  586. }
  587. // wait for request ack
  588. resp, err := wc.Recv()
  589. if err != nil {
  590. return err
  591. } else if len(resp.Events) != 0 || !resp.Created {
  592. return fmt.Errorf("watcher: unexpected response (%+v)", resp)
  593. }
  594. // id may be different since new remote watcher; update map
  595. w.mu.Lock()
  596. delete(w.streams, ws.id)
  597. ws.id = resp.WatchId
  598. w.streams[ws.id] = ws
  599. w.mu.Unlock()
  600. // unpause serveStream
  601. ws.resumec <- ws.lastRev
  602. }
  603. return nil
  604. }
  605. // toPB converts an internal watch request structure to its protobuf messagefunc (wr *watchRequest)
  606. func (wr *watchRequest) toPB() *pb.WatchRequest {
  607. req := &pb.WatchCreateRequest{
  608. StartRevision: wr.rev,
  609. Key: []byte(wr.key),
  610. RangeEnd: []byte(wr.end),
  611. ProgressNotify: wr.progressNotify,
  612. }
  613. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  614. return &pb.WatchRequest{RequestUnion: cr}
  615. }