watch.go 12 KB

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