watch.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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. "google.golang.org/grpc"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/metadata"
  26. )
  27. const (
  28. EventTypeDelete = mvccpb.DELETE
  29. EventTypePut = mvccpb.PUT
  30. closeSendErrTimeout = 250 * time.Millisecond
  31. )
  32. type Event mvccpb.Event
  33. type WatchChan <-chan WatchResponse
  34. type Watcher interface {
  35. // Watch watches on a key or prefix. The watched events will be returned
  36. // through the returned channel. If revisions waiting to be sent over the
  37. // watch are compacted, then the watch will be canceled by the server, the
  38. // client will post a compacted error watch response, and the channel will close.
  39. Watch(ctx context.Context, key string, opts ...OpOption) WatchChan
  40. // Close closes the watcher and cancels all watch requests.
  41. Close() error
  42. }
  43. type WatchResponse struct {
  44. Header pb.ResponseHeader
  45. Events []*Event
  46. // CompactRevision is the minimum revision the watcher may receive.
  47. CompactRevision int64
  48. // Canceled is used to indicate watch failure.
  49. // If the watch failed and the stream was about to close, before the channel is closed,
  50. // the channel sends a final response that has Canceled set to true with a non-nil Err().
  51. Canceled bool
  52. // Created is used to indicate the creation of the watcher.
  53. Created bool
  54. closeErr error
  55. // cancelReason is a reason of canceling watch
  56. cancelReason string
  57. }
  58. // IsCreate returns true if the event tells that the key is newly created.
  59. func (e *Event) IsCreate() bool {
  60. return e.Type == EventTypePut && e.Kv.CreateRevision == e.Kv.ModRevision
  61. }
  62. // IsModify returns true if the event tells that a new value is put on existing key.
  63. func (e *Event) IsModify() bool {
  64. return e.Type == EventTypePut && e.Kv.CreateRevision != e.Kv.ModRevision
  65. }
  66. // Err is the error value if this WatchResponse holds an error.
  67. func (wr *WatchResponse) Err() error {
  68. switch {
  69. case wr.closeErr != nil:
  70. return v3rpc.Error(wr.closeErr)
  71. case wr.CompactRevision != 0:
  72. return v3rpc.ErrCompacted
  73. case wr.Canceled:
  74. if len(wr.cancelReason) != 0 {
  75. return v3rpc.Error(grpc.Errorf(codes.FailedPrecondition, "%s", wr.cancelReason))
  76. }
  77. return v3rpc.ErrFutureRev
  78. }
  79. return nil
  80. }
  81. // IsProgressNotify returns true if the WatchResponse is progress notification.
  82. func (wr *WatchResponse) IsProgressNotify() bool {
  83. return len(wr.Events) == 0 && !wr.Canceled && !wr.Created && wr.CompactRevision == 0 && wr.Header.Revision != 0
  84. }
  85. // watcher implements the Watcher interface
  86. type watcher struct {
  87. remote pb.WatchClient
  88. // mu protects the grpc streams map
  89. mu sync.RWMutex
  90. // streams holds all the active grpc streams keyed by ctx value.
  91. streams map[string]*watchGrpcStream
  92. }
  93. // watchGrpcStream tracks all watch resources attached to a single grpc stream.
  94. type watchGrpcStream struct {
  95. owner *watcher
  96. remote pb.WatchClient
  97. // ctx controls internal remote.Watch requests
  98. ctx context.Context
  99. // ctxKey is the key used when looking up this stream's context
  100. ctxKey string
  101. cancel context.CancelFunc
  102. // substreams holds all active watchers on this grpc stream
  103. substreams map[int64]*watcherStream
  104. // resuming holds all resuming watchers on this grpc stream
  105. resuming []*watcherStream
  106. // reqc sends a watch request from Watch() to the main goroutine
  107. reqc chan *watchRequest
  108. // respc receives data from the watch client
  109. respc chan *pb.WatchResponse
  110. // donec closes to broadcast shutdown
  111. donec chan struct{}
  112. // errc transmits errors from grpc Recv to the watch stream reconn logic
  113. errc chan error
  114. // closingc gets the watcherStream of closing watchers
  115. closingc chan *watcherStream
  116. // wg is Done when all substream goroutines have exited
  117. wg sync.WaitGroup
  118. // resumec closes to signal that all substreams should begin resuming
  119. resumec chan struct{}
  120. // closeErr is the error that closed the watch stream
  121. closeErr error
  122. }
  123. // watchRequest is issued by the subscriber to start a new watcher
  124. type watchRequest struct {
  125. ctx context.Context
  126. key string
  127. end string
  128. rev int64
  129. // send created notification event if this field is true
  130. createdNotify bool
  131. // progressNotify is for progress updates
  132. progressNotify bool
  133. // filters is the list of events to filter out
  134. filters []pb.WatchCreateRequest_FilterType
  135. // get the previous key-value pair before the event happens
  136. prevKV bool
  137. // retc receives a chan WatchResponse once the watcher is established
  138. retc chan chan WatchResponse
  139. }
  140. // watcherStream represents a registered watcher
  141. type watcherStream struct {
  142. // initReq is the request that initiated this request
  143. initReq watchRequest
  144. // outc publishes watch responses to subscriber
  145. outc chan WatchResponse
  146. // recvc buffers watch responses before publishing
  147. recvc chan *WatchResponse
  148. // donec closes when the watcherStream goroutine stops.
  149. donec chan struct{}
  150. // closing is set to true when stream should be scheduled to shutdown.
  151. closing bool
  152. // id is the registered watch id on the grpc stream
  153. id int64
  154. // buf holds all events received from etcd but not yet consumed by the client
  155. buf []*WatchResponse
  156. }
  157. func NewWatcher(c *Client) Watcher {
  158. return NewWatchFromWatchClient(pb.NewWatchClient(c.conn))
  159. }
  160. func NewWatchFromWatchClient(wc pb.WatchClient) Watcher {
  161. return &watcher{
  162. remote: wc,
  163. streams: make(map[string]*watchGrpcStream),
  164. }
  165. }
  166. // never closes
  167. var valCtxCh = make(chan struct{})
  168. var zeroTime = time.Unix(0, 0)
  169. // ctx with only the values; never Done
  170. type valCtx struct{ context.Context }
  171. func (vc *valCtx) Deadline() (time.Time, bool) { return zeroTime, false }
  172. func (vc *valCtx) Done() <-chan struct{} { return valCtxCh }
  173. func (vc *valCtx) Err() error { return nil }
  174. func (w *watcher) newWatcherGrpcStream(inctx context.Context) *watchGrpcStream {
  175. ctx, cancel := context.WithCancel(&valCtx{inctx})
  176. wgs := &watchGrpcStream{
  177. owner: w,
  178. remote: w.remote,
  179. ctx: ctx,
  180. ctxKey: streamKeyFromCtx(inctx),
  181. cancel: cancel,
  182. substreams: make(map[int64]*watcherStream),
  183. respc: make(chan *pb.WatchResponse),
  184. reqc: make(chan *watchRequest),
  185. donec: make(chan struct{}),
  186. errc: make(chan error, 1),
  187. closingc: make(chan *watcherStream),
  188. resumec: make(chan struct{}),
  189. }
  190. go wgs.run()
  191. return wgs
  192. }
  193. // Watch posts a watch request to run() and waits for a new watcher channel
  194. func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
  195. ow := opWatch(key, opts...)
  196. var filters []pb.WatchCreateRequest_FilterType
  197. if ow.filterPut {
  198. filters = append(filters, pb.WatchCreateRequest_NOPUT)
  199. }
  200. if ow.filterDelete {
  201. filters = append(filters, pb.WatchCreateRequest_NODELETE)
  202. }
  203. wr := &watchRequest{
  204. ctx: ctx,
  205. createdNotify: ow.createdNotify,
  206. key: string(ow.key),
  207. end: string(ow.end),
  208. rev: ow.rev,
  209. progressNotify: ow.progressNotify,
  210. filters: filters,
  211. prevKV: ow.prevKV,
  212. retc: make(chan chan WatchResponse, 1),
  213. }
  214. ok := false
  215. ctxKey := streamKeyFromCtx(ctx)
  216. // find or allocate appropriate grpc watch stream
  217. w.mu.Lock()
  218. if w.streams == nil {
  219. // closed
  220. w.mu.Unlock()
  221. ch := make(chan WatchResponse)
  222. close(ch)
  223. return ch
  224. }
  225. wgs := w.streams[ctxKey]
  226. if wgs == nil {
  227. wgs = w.newWatcherGrpcStream(ctx)
  228. w.streams[ctxKey] = wgs
  229. }
  230. donec := wgs.donec
  231. reqc := wgs.reqc
  232. w.mu.Unlock()
  233. // couldn't create channel; return closed channel
  234. closeCh := make(chan WatchResponse, 1)
  235. // submit request
  236. select {
  237. case reqc <- wr:
  238. ok = true
  239. case <-wr.ctx.Done():
  240. case <-donec:
  241. if wgs.closeErr != nil {
  242. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  243. break
  244. }
  245. // retry; may have dropped stream from no ctxs
  246. return w.Watch(ctx, key, opts...)
  247. }
  248. // receive channel
  249. if ok {
  250. select {
  251. case ret := <-wr.retc:
  252. return ret
  253. case <-ctx.Done():
  254. case <-donec:
  255. if wgs.closeErr != nil {
  256. closeCh <- WatchResponse{closeErr: wgs.closeErr}
  257. break
  258. }
  259. // retry; may have dropped stream from no ctxs
  260. return w.Watch(ctx, key, opts...)
  261. }
  262. }
  263. close(closeCh)
  264. return closeCh
  265. }
  266. func (w *watcher) Close() (err error) {
  267. w.mu.Lock()
  268. streams := w.streams
  269. w.streams = nil
  270. w.mu.Unlock()
  271. for _, wgs := range streams {
  272. if werr := wgs.close(); werr != nil {
  273. err = werr
  274. }
  275. }
  276. return err
  277. }
  278. func (w *watchGrpcStream) close() (err error) {
  279. w.cancel()
  280. <-w.donec
  281. select {
  282. case err = <-w.errc:
  283. default:
  284. }
  285. return toErr(w.ctx, err)
  286. }
  287. func (w *watcher) closeStream(wgs *watchGrpcStream) {
  288. w.mu.Lock()
  289. close(wgs.donec)
  290. wgs.cancel()
  291. if w.streams != nil {
  292. delete(w.streams, wgs.ctxKey)
  293. }
  294. w.mu.Unlock()
  295. }
  296. func (w *watchGrpcStream) addSubstream(resp *pb.WatchResponse, ws *watcherStream) {
  297. if resp.WatchId == -1 {
  298. // failed; no channel
  299. close(ws.recvc)
  300. return
  301. }
  302. ws.id = resp.WatchId
  303. w.substreams[ws.id] = ws
  304. }
  305. func (w *watchGrpcStream) sendCloseSubstream(ws *watcherStream, resp *WatchResponse) {
  306. select {
  307. case ws.outc <- *resp:
  308. case <-ws.initReq.ctx.Done():
  309. case <-time.After(closeSendErrTimeout):
  310. }
  311. close(ws.outc)
  312. }
  313. func (w *watchGrpcStream) closeSubstream(ws *watcherStream) {
  314. // send channel response in case stream was never established
  315. select {
  316. case ws.initReq.retc <- ws.outc:
  317. default:
  318. }
  319. // close subscriber's channel
  320. if closeErr := w.closeErr; closeErr != nil && ws.initReq.ctx.Err() == nil {
  321. go w.sendCloseSubstream(ws, &WatchResponse{closeErr: w.closeErr})
  322. } else if ws.outc != nil {
  323. close(ws.outc)
  324. }
  325. if ws.id != -1 {
  326. delete(w.substreams, ws.id)
  327. return
  328. }
  329. for i := range w.resuming {
  330. if w.resuming[i] == ws {
  331. w.resuming[i] = nil
  332. return
  333. }
  334. }
  335. }
  336. // run is the root of the goroutines for managing a watcher client
  337. func (w *watchGrpcStream) run() {
  338. var wc pb.Watch_WatchClient
  339. var closeErr error
  340. // substreams marked to close but goroutine still running; needed for
  341. // avoiding double-closing recvc on grpc stream teardown
  342. closing := make(map[*watcherStream]struct{})
  343. defer func() {
  344. w.closeErr = closeErr
  345. // shutdown substreams and resuming substreams
  346. for _, ws := range w.substreams {
  347. if _, ok := closing[ws]; !ok {
  348. close(ws.recvc)
  349. closing[ws] = struct{}{}
  350. }
  351. }
  352. for _, ws := range w.resuming {
  353. if _, ok := closing[ws]; ws != nil && !ok {
  354. close(ws.recvc)
  355. closing[ws] = struct{}{}
  356. }
  357. }
  358. w.joinSubstreams()
  359. for range closing {
  360. w.closeSubstream(<-w.closingc)
  361. }
  362. w.wg.Wait()
  363. w.owner.closeStream(w)
  364. }()
  365. // start a stream with the etcd grpc server
  366. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  367. return
  368. }
  369. cancelSet := make(map[int64]struct{})
  370. for {
  371. select {
  372. // Watch() requested
  373. case wreq := <-w.reqc:
  374. outc := make(chan WatchResponse, 1)
  375. ws := &watcherStream{
  376. initReq: *wreq,
  377. id: -1,
  378. outc: outc,
  379. // unbufffered so resumes won't cause repeat events
  380. recvc: make(chan *WatchResponse),
  381. }
  382. ws.donec = make(chan struct{})
  383. w.wg.Add(1)
  384. go w.serveSubstream(ws, w.resumec)
  385. // queue up for watcher creation/resume
  386. w.resuming = append(w.resuming, ws)
  387. if len(w.resuming) == 1 {
  388. // head of resume queue, can register a new watcher
  389. wc.Send(ws.initReq.toPB())
  390. }
  391. // New events from the watch client
  392. case pbresp := <-w.respc:
  393. switch {
  394. case pbresp.Created:
  395. // response to head of queue creation
  396. if ws := w.resuming[0]; ws != nil {
  397. w.addSubstream(pbresp, ws)
  398. w.dispatchEvent(pbresp)
  399. w.resuming[0] = nil
  400. }
  401. if ws := w.nextResume(); ws != nil {
  402. wc.Send(ws.initReq.toPB())
  403. }
  404. case pbresp.Canceled && pbresp.CompactRevision == 0:
  405. delete(cancelSet, pbresp.WatchId)
  406. if ws, ok := w.substreams[pbresp.WatchId]; ok {
  407. // signal to stream goroutine to update closingc
  408. close(ws.recvc)
  409. closing[ws] = struct{}{}
  410. }
  411. default:
  412. // dispatch to appropriate watch stream
  413. if ok := w.dispatchEvent(pbresp); ok {
  414. break
  415. }
  416. // watch response on unexpected watch id; cancel id
  417. if _, ok := cancelSet[pbresp.WatchId]; ok {
  418. break
  419. }
  420. cancelSet[pbresp.WatchId] = struct{}{}
  421. cr := &pb.WatchRequest_CancelRequest{
  422. CancelRequest: &pb.WatchCancelRequest{
  423. WatchId: pbresp.WatchId,
  424. },
  425. }
  426. req := &pb.WatchRequest{RequestUnion: cr}
  427. wc.Send(req)
  428. }
  429. // watch client failed to recv; spawn another if possible
  430. case err := <-w.errc:
  431. if isHaltErr(w.ctx, err) || toErr(w.ctx, err) == v3rpc.ErrNoLeader {
  432. closeErr = err
  433. return
  434. }
  435. if wc, closeErr = w.newWatchClient(); closeErr != nil {
  436. return
  437. }
  438. if ws := w.nextResume(); ws != nil {
  439. wc.Send(ws.initReq.toPB())
  440. }
  441. cancelSet = make(map[int64]struct{})
  442. case <-w.ctx.Done():
  443. return
  444. case ws := <-w.closingc:
  445. w.closeSubstream(ws)
  446. delete(closing, ws)
  447. if len(w.substreams)+len(w.resuming) == 0 {
  448. // no more watchers on this stream, shutdown
  449. return
  450. }
  451. }
  452. }
  453. }
  454. // nextResume chooses the next resuming to register with the grpc stream. Abandoned
  455. // streams are marked as nil in the queue since the head must wait for its inflight registration.
  456. func (w *watchGrpcStream) nextResume() *watcherStream {
  457. for len(w.resuming) != 0 {
  458. if w.resuming[0] != nil {
  459. return w.resuming[0]
  460. }
  461. w.resuming = w.resuming[1:len(w.resuming)]
  462. }
  463. return nil
  464. }
  465. // dispatchEvent sends a WatchResponse to the appropriate watcher stream
  466. func (w *watchGrpcStream) dispatchEvent(pbresp *pb.WatchResponse) bool {
  467. events := make([]*Event, len(pbresp.Events))
  468. for i, ev := range pbresp.Events {
  469. events[i] = (*Event)(ev)
  470. }
  471. wr := &WatchResponse{
  472. Header: *pbresp.Header,
  473. Events: events,
  474. CompactRevision: pbresp.CompactRevision,
  475. Created: pbresp.Created,
  476. Canceled: pbresp.Canceled,
  477. cancelReason: pbresp.CancelReason,
  478. }
  479. ws, ok := w.substreams[pbresp.WatchId]
  480. if !ok {
  481. return false
  482. }
  483. select {
  484. case ws.recvc <- wr:
  485. case <-ws.donec:
  486. return false
  487. }
  488. return true
  489. }
  490. // serveWatchClient forwards messages from the grpc stream to run()
  491. func (w *watchGrpcStream) serveWatchClient(wc pb.Watch_WatchClient) {
  492. for {
  493. resp, err := wc.Recv()
  494. if err != nil {
  495. select {
  496. case w.errc <- err:
  497. case <-w.donec:
  498. }
  499. return
  500. }
  501. select {
  502. case w.respc <- resp:
  503. case <-w.donec:
  504. return
  505. }
  506. }
  507. }
  508. // serveSubstream forwards watch responses from run() to the subscriber
  509. func (w *watchGrpcStream) serveSubstream(ws *watcherStream, resumec chan struct{}) {
  510. if ws.closing {
  511. panic("created substream goroutine but substream is closing")
  512. }
  513. // nextRev is the minimum expected next revision
  514. nextRev := ws.initReq.rev
  515. resuming := false
  516. defer func() {
  517. if !resuming {
  518. ws.closing = true
  519. }
  520. close(ws.donec)
  521. if !resuming {
  522. w.closingc <- ws
  523. }
  524. w.wg.Done()
  525. }()
  526. emptyWr := &WatchResponse{}
  527. for {
  528. curWr := emptyWr
  529. outc := ws.outc
  530. if len(ws.buf) > 0 {
  531. curWr = ws.buf[0]
  532. } else {
  533. outc = nil
  534. }
  535. select {
  536. case outc <- *curWr:
  537. if ws.buf[0].Err() != nil {
  538. return
  539. }
  540. ws.buf[0] = nil
  541. ws.buf = ws.buf[1:]
  542. case wr, ok := <-ws.recvc:
  543. if !ok {
  544. // shutdown from closeSubstream
  545. return
  546. }
  547. if wr.Created {
  548. if ws.initReq.retc != nil {
  549. ws.initReq.retc <- ws.outc
  550. // to prevent next write from taking the slot in buffered channel
  551. // and posting duplicate create events
  552. ws.initReq.retc = nil
  553. // send first creation event only if requested
  554. if ws.initReq.createdNotify {
  555. ws.outc <- *wr
  556. }
  557. // once the watch channel is returned, a current revision
  558. // watch must resume at the store revision. This is necessary
  559. // for the following case to work as expected:
  560. // wch := m1.Watch("a")
  561. // m2.Put("a", "b")
  562. // <-wch
  563. // If the revision is only bound on the first observed event,
  564. // if wch is disconnected before the Put is issued, then reconnects
  565. // after it is committed, it'll miss the Put.
  566. if ws.initReq.rev == 0 {
  567. nextRev = wr.Header.Revision
  568. }
  569. }
  570. } else {
  571. // current progress of watch; <= store revision
  572. nextRev = wr.Header.Revision
  573. }
  574. if len(wr.Events) > 0 {
  575. nextRev = wr.Events[len(wr.Events)-1].Kv.ModRevision + 1
  576. }
  577. ws.initReq.rev = nextRev
  578. // created event is already sent above,
  579. // watcher should not post duplicate events
  580. if wr.Created {
  581. continue
  582. }
  583. // TODO pause channel if buffer gets too large
  584. ws.buf = append(ws.buf, wr)
  585. case <-w.ctx.Done():
  586. return
  587. case <-ws.initReq.ctx.Done():
  588. return
  589. case <-resumec:
  590. resuming = true
  591. return
  592. }
  593. }
  594. // lazily send cancel message if events on missing id
  595. }
  596. func (w *watchGrpcStream) newWatchClient() (pb.Watch_WatchClient, error) {
  597. // mark all substreams as resuming
  598. close(w.resumec)
  599. w.resumec = make(chan struct{})
  600. w.joinSubstreams()
  601. for _, ws := range w.substreams {
  602. ws.id = -1
  603. w.resuming = append(w.resuming, ws)
  604. }
  605. // strip out nils, if any
  606. var resuming []*watcherStream
  607. for _, ws := range w.resuming {
  608. if ws != nil {
  609. resuming = append(resuming, ws)
  610. }
  611. }
  612. w.resuming = resuming
  613. w.substreams = make(map[int64]*watcherStream)
  614. // connect to grpc stream while accepting watcher cancelation
  615. stopc := make(chan struct{})
  616. donec := w.waitCancelSubstreams(stopc)
  617. wc, err := w.openWatchClient()
  618. close(stopc)
  619. <-donec
  620. // serve all non-closing streams, even if there's a client error
  621. // so that the teardown path can shutdown the streams as expected.
  622. for _, ws := range w.resuming {
  623. if ws.closing {
  624. continue
  625. }
  626. ws.donec = make(chan struct{})
  627. w.wg.Add(1)
  628. go w.serveSubstream(ws, w.resumec)
  629. }
  630. if err != nil {
  631. return nil, v3rpc.Error(err)
  632. }
  633. // receive data from new grpc stream
  634. go w.serveWatchClient(wc)
  635. return wc, nil
  636. }
  637. func (w *watchGrpcStream) waitCancelSubstreams(stopc <-chan struct{}) <-chan struct{} {
  638. var wg sync.WaitGroup
  639. wg.Add(len(w.resuming))
  640. donec := make(chan struct{})
  641. for i := range w.resuming {
  642. go func(ws *watcherStream) {
  643. defer wg.Done()
  644. if ws.closing {
  645. if ws.initReq.ctx.Err() != nil && ws.outc != nil {
  646. close(ws.outc)
  647. ws.outc = nil
  648. }
  649. return
  650. }
  651. select {
  652. case <-ws.initReq.ctx.Done():
  653. // closed ws will be removed from resuming
  654. ws.closing = true
  655. close(ws.outc)
  656. ws.outc = nil
  657. w.wg.Add(1)
  658. go func() {
  659. defer w.wg.Done()
  660. w.closingc <- ws
  661. }()
  662. case <-stopc:
  663. }
  664. }(w.resuming[i])
  665. }
  666. go func() {
  667. defer close(donec)
  668. wg.Wait()
  669. }()
  670. return donec
  671. }
  672. // joinSubstream waits for all substream goroutines to complete
  673. func (w *watchGrpcStream) joinSubstreams() {
  674. for _, ws := range w.substreams {
  675. <-ws.donec
  676. }
  677. for _, ws := range w.resuming {
  678. if ws != nil {
  679. <-ws.donec
  680. }
  681. }
  682. }
  683. // openWatchClient retries opening a watchclient until retryConnection fails
  684. func (w *watchGrpcStream) openWatchClient() (ws pb.Watch_WatchClient, err error) {
  685. for {
  686. select {
  687. case <-w.ctx.Done():
  688. if err == nil {
  689. return nil, w.ctx.Err()
  690. }
  691. return nil, err
  692. default:
  693. }
  694. if ws, err = w.remote.Watch(w.ctx, grpc.FailFast(false)); ws != nil && err == nil {
  695. break
  696. }
  697. if isHaltErr(w.ctx, err) {
  698. return nil, v3rpc.Error(err)
  699. }
  700. }
  701. return ws, nil
  702. }
  703. // toPB converts an internal watch request structure to its protobuf messagefunc (wr *watchRequest)
  704. func (wr *watchRequest) toPB() *pb.WatchRequest {
  705. req := &pb.WatchCreateRequest{
  706. StartRevision: wr.rev,
  707. Key: []byte(wr.key),
  708. RangeEnd: []byte(wr.end),
  709. ProgressNotify: wr.progressNotify,
  710. Filters: wr.filters,
  711. PrevKv: wr.prevKV,
  712. }
  713. cr := &pb.WatchRequest_CreateRequest{CreateRequest: req}
  714. return &pb.WatchRequest{RequestUnion: cr}
  715. }
  716. func streamKeyFromCtx(ctx context.Context) string {
  717. if md, ok := metadata.FromOutgoingContext(ctx); ok {
  718. return fmt.Sprintf("%+v", md)
  719. }
  720. return ""
  721. }