watch.go 13 KB

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