watch.go 14 KB

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