watch_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 integration
  15. import (
  16. "fmt"
  17. "reflect"
  18. "sort"
  19. "sync/atomic"
  20. "testing"
  21. "time"
  22. "github.com/coreos/etcd/clientv3"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  25. "github.com/coreos/etcd/integration"
  26. "github.com/coreos/etcd/pkg/testutil"
  27. storagepb "github.com/coreos/etcd/storage/storagepb"
  28. "golang.org/x/net/context"
  29. )
  30. type watcherTest func(*testing.T, *watchctx)
  31. type watchctx struct {
  32. clus *integration.ClusterV3
  33. w clientv3.Watcher
  34. wclient *clientv3.Client
  35. kv clientv3.KV
  36. ch clientv3.WatchChan
  37. }
  38. func runWatchTest(t *testing.T, f watcherTest) {
  39. defer testutil.AfterTest(t)
  40. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  41. defer clus.Terminate(t)
  42. wclient := clus.RandClient()
  43. w := clientv3.NewWatcher(wclient)
  44. defer w.Close()
  45. // select a different client from wclient so puts succeed if
  46. // a test knocks out the watcher client
  47. kvclient := clus.RandClient()
  48. for kvclient == wclient {
  49. kvclient = clus.RandClient()
  50. }
  51. kv := clientv3.NewKV(kvclient)
  52. wctx := &watchctx{clus, w, wclient, kv, nil}
  53. f(t, wctx)
  54. }
  55. // TestWatchMultiWatcher modifies multiple keys and observes the changes.
  56. func TestWatchMultiWatcher(t *testing.T) {
  57. runWatchTest(t, testWatchMultiWatcher)
  58. }
  59. func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
  60. numKeyUpdates := 4
  61. keys := []string{"foo", "bar", "baz"}
  62. donec := make(chan struct{})
  63. readyc := make(chan struct{})
  64. for _, k := range keys {
  65. // key watcher
  66. go func(key string) {
  67. ch := wctx.w.Watch(context.TODO(), key)
  68. if ch == nil {
  69. t.Fatalf("expected watcher channel, got nil")
  70. }
  71. readyc <- struct{}{}
  72. for i := 0; i < numKeyUpdates; i++ {
  73. resp, ok := <-ch
  74. if !ok {
  75. t.Fatalf("watcher unexpectedly closed")
  76. }
  77. v := fmt.Sprintf("%s-%d", key, i)
  78. gotv := string(resp.Events[0].Kv.Value)
  79. if gotv != v {
  80. t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
  81. }
  82. }
  83. donec <- struct{}{}
  84. }(k)
  85. }
  86. // prefix watcher on "b" (bar and baz)
  87. go func() {
  88. prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
  89. if prefixc == nil {
  90. t.Fatalf("expected watcher channel, got nil")
  91. }
  92. readyc <- struct{}{}
  93. evs := []*storagepb.Event{}
  94. for i := 0; i < numKeyUpdates*2; i++ {
  95. resp, ok := <-prefixc
  96. if !ok {
  97. t.Fatalf("watcher unexpectedly closed")
  98. }
  99. evs = append(evs, resp.Events...)
  100. }
  101. // check response
  102. expected := []string{}
  103. bkeys := []string{"bar", "baz"}
  104. for _, k := range bkeys {
  105. for i := 0; i < numKeyUpdates; i++ {
  106. expected = append(expected, fmt.Sprintf("%s-%d", k, i))
  107. }
  108. }
  109. got := []string{}
  110. for _, ev := range evs {
  111. got = append(got, string(ev.Kv.Value))
  112. }
  113. sort.Strings(got)
  114. if reflect.DeepEqual(expected, got) == false {
  115. t.Errorf("got %v, expected %v", got, expected)
  116. }
  117. // ensure no extra data
  118. select {
  119. case resp, ok := <-prefixc:
  120. if !ok {
  121. t.Fatalf("watcher unexpectedly closed")
  122. }
  123. t.Fatalf("unexpected event %+v", resp)
  124. case <-time.After(time.Second):
  125. }
  126. donec <- struct{}{}
  127. }()
  128. // wait for watcher bring up
  129. for i := 0; i < len(keys)+1; i++ {
  130. <-readyc
  131. }
  132. // generate events
  133. ctx := context.TODO()
  134. for i := 0; i < numKeyUpdates; i++ {
  135. for _, k := range keys {
  136. v := fmt.Sprintf("%s-%d", k, i)
  137. if _, err := wctx.kv.Put(ctx, k, v); err != nil {
  138. t.Fatal(err)
  139. }
  140. }
  141. }
  142. // wait for watcher shutdown
  143. for i := 0; i < len(keys)+1; i++ {
  144. <-donec
  145. }
  146. }
  147. // TestWatchRange tests watcher creates ranges
  148. func TestWatchRange(t *testing.T) {
  149. runWatchTest(t, testWatchReconnInit)
  150. }
  151. func testWatchRange(t *testing.T, wctx *watchctx) {
  152. if wctx.ch = wctx.w.Watch(context.TODO(), "a", clientv3.WithRange("c")); wctx.ch == nil {
  153. t.Fatalf("expected non-nil channel")
  154. }
  155. putAndWatch(t, wctx, "a", "a")
  156. putAndWatch(t, wctx, "b", "b")
  157. putAndWatch(t, wctx, "bar", "bar")
  158. }
  159. // TestWatchReconnRequest tests the send failure path when requesting a watcher.
  160. func TestWatchReconnRequest(t *testing.T) {
  161. runWatchTest(t, testWatchReconnRequest)
  162. }
  163. func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
  164. donec, stopc := make(chan struct{}), make(chan struct{}, 1)
  165. go func() {
  166. timer := time.After(2 * time.Second)
  167. defer close(donec)
  168. // take down watcher connection
  169. for {
  170. wctx.wclient.ActiveConnection().Close()
  171. select {
  172. case <-timer:
  173. // spinning on close may live lock reconnection
  174. return
  175. case <-stopc:
  176. return
  177. default:
  178. }
  179. }
  180. }()
  181. // should reconnect when requesting watch
  182. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  183. t.Fatalf("expected non-nil channel")
  184. }
  185. // wait for disconnections to stop
  186. stopc <- struct{}{}
  187. <-donec
  188. // ensure watcher works
  189. putAndWatch(t, wctx, "a", "a")
  190. }
  191. // TestWatchReconnInit tests watcher resumes correctly if connection lost
  192. // before any data was sent.
  193. func TestWatchReconnInit(t *testing.T) {
  194. runWatchTest(t, testWatchReconnInit)
  195. }
  196. func testWatchReconnInit(t *testing.T, wctx *watchctx) {
  197. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  198. t.Fatalf("expected non-nil channel")
  199. }
  200. // take down watcher connection
  201. wctx.wclient.ActiveConnection().Close()
  202. // watcher should recover
  203. putAndWatch(t, wctx, "a", "a")
  204. }
  205. // TestWatchReconnRunning tests watcher resumes correctly if connection lost
  206. // after data was sent.
  207. func TestWatchReconnRunning(t *testing.T) {
  208. runWatchTest(t, testWatchReconnRunning)
  209. }
  210. func testWatchReconnRunning(t *testing.T, wctx *watchctx) {
  211. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  212. t.Fatalf("expected non-nil channel")
  213. }
  214. putAndWatch(t, wctx, "a", "a")
  215. // take down watcher connection
  216. wctx.wclient.ActiveConnection().Close()
  217. // watcher should recover
  218. putAndWatch(t, wctx, "a", "b")
  219. }
  220. // TestWatchCancelImmediate ensures a closed channel is returned
  221. // if the context is cancelled.
  222. func TestWatchCancelImmediate(t *testing.T) {
  223. runWatchTest(t, testWatchCancelImmediate)
  224. }
  225. func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
  226. ctx, cancel := context.WithCancel(context.Background())
  227. cancel()
  228. wch := wctx.w.Watch(ctx, "a")
  229. select {
  230. case wresp, ok := <-wch:
  231. if ok {
  232. t.Fatalf("read wch got %v; expected closed channel", wresp)
  233. }
  234. default:
  235. t.Fatalf("closed watcher channel should not block")
  236. }
  237. }
  238. // TestWatchCancelInit tests watcher closes correctly after no events.
  239. func TestWatchCancelInit(t *testing.T) {
  240. runWatchTest(t, testWatchCancelInit)
  241. }
  242. func testWatchCancelInit(t *testing.T, wctx *watchctx) {
  243. ctx, cancel := context.WithCancel(context.Background())
  244. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  245. t.Fatalf("expected non-nil watcher channel")
  246. }
  247. cancel()
  248. select {
  249. case <-time.After(time.Second):
  250. t.Fatalf("took too long to cancel")
  251. case _, ok := <-wctx.ch:
  252. if ok {
  253. t.Fatalf("expected watcher channel to close")
  254. }
  255. }
  256. }
  257. // TestWatchCancelRunning tests watcher closes correctly after events.
  258. func TestWatchCancelRunning(t *testing.T) {
  259. runWatchTest(t, testWatchCancelRunning)
  260. }
  261. func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
  262. ctx, cancel := context.WithCancel(context.Background())
  263. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  264. t.Fatalf("expected non-nil watcher channel")
  265. }
  266. if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
  267. t.Fatal(err)
  268. }
  269. cancel()
  270. select {
  271. case <-time.After(time.Second):
  272. t.Fatalf("took too long to cancel")
  273. case v, ok := <-wctx.ch:
  274. if !ok {
  275. // closed before getting put; OK
  276. break
  277. }
  278. // got the PUT; should close next
  279. select {
  280. case <-time.After(time.Second):
  281. t.Fatalf("took too long to close")
  282. case v, ok = <-wctx.ch:
  283. if ok {
  284. t.Fatalf("expected watcher channel to close, got %v", v)
  285. }
  286. }
  287. }
  288. }
  289. func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
  290. if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
  291. t.Fatal(err)
  292. }
  293. select {
  294. case <-time.After(5 * time.Second):
  295. t.Fatalf("watch timed out")
  296. case v, ok := <-wctx.ch:
  297. if !ok {
  298. t.Fatalf("unexpected watch close")
  299. }
  300. if string(v.Events[0].Kv.Value) != val {
  301. t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
  302. }
  303. }
  304. }
  305. // TestWatchCompactRevision ensures the CompactRevision error is given on a
  306. // compaction event ahead of a watcher.
  307. func TestWatchCompactRevision(t *testing.T) {
  308. defer testutil.AfterTest(t)
  309. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  310. defer clus.Terminate(t)
  311. // set some keys
  312. kv := clientv3.NewKV(clus.RandClient())
  313. for i := 0; i < 5; i++ {
  314. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  315. t.Fatal(err)
  316. }
  317. }
  318. w := clientv3.NewWatcher(clus.RandClient())
  319. defer w.Close()
  320. if err := kv.Compact(context.TODO(), 4); err != nil {
  321. t.Fatal(err)
  322. }
  323. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(2))
  324. // get compacted error message
  325. wresp, ok := <-wch
  326. if !ok {
  327. t.Fatalf("expected wresp, but got closed channel")
  328. }
  329. if wresp.Err() != rpctypes.ErrCompacted {
  330. t.Fatalf("wresp.Err() expected ErrCompacteed, but got %v", wresp.Err())
  331. }
  332. // ensure the channel is closed
  333. if wresp, ok = <-wch; ok {
  334. t.Fatalf("expected closed channel, but got %v", wresp)
  335. }
  336. }
  337. func TestWatchWithProgressNotify(t *testing.T) { testWatchWithProgressNotify(t, true) }
  338. func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }
  339. func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
  340. defer testutil.AfterTest(t)
  341. // accelerate report interval so test terminates quickly
  342. oldpi := v3rpc.ProgressReportIntervalMilliseconds
  343. // using atomics to avoid race warnings
  344. atomic.StoreInt32(&v3rpc.ProgressReportIntervalMilliseconds, 3*1000)
  345. pi := 3 * time.Second
  346. defer func() { v3rpc.ProgressReportIntervalMilliseconds = oldpi }()
  347. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  348. defer clus.Terminate(t)
  349. wc := clientv3.NewWatcher(clus.RandClient())
  350. defer wc.Close()
  351. opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
  352. if watchOnPut {
  353. opts = append(opts, clientv3.WithPrefix())
  354. }
  355. rch := wc.Watch(context.Background(), "foo", opts...)
  356. select {
  357. case resp := <-rch: // wait for notification
  358. if len(resp.Events) != 0 {
  359. t.Fatalf("resp.Events expected none, got %+v", resp.Events)
  360. }
  361. case <-time.After(2 * pi):
  362. t.Fatalf("watch response expected in %v, but timed out", pi)
  363. }
  364. kvc := clientv3.NewKV(clus.RandClient())
  365. if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
  366. t.Fatal(err)
  367. }
  368. select {
  369. case resp := <-rch:
  370. if resp.Header.Revision != 2 {
  371. t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
  372. }
  373. if watchOnPut { // wait for put if watch on the put key
  374. ev := []*storagepb.Event{{Type: storagepb.PUT,
  375. Kv: &storagepb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
  376. if !reflect.DeepEqual(ev, resp.Events) {
  377. t.Fatalf("expected %+v, got %+v", ev, resp.Events)
  378. }
  379. } else if len(resp.Events) != 0 { // wait for notification otherwise
  380. t.Fatalf("expected no events, but got %+v", resp.Events)
  381. }
  382. case <-time.After(2 * pi):
  383. t.Fatalf("watch response expected in %v, but timed out", pi)
  384. }
  385. }