watch_test.go 13 KB

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