watch.go 12 KB

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