watch_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/clientv3"
  23. "github.com/coreos/etcd/integration"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. storagepb "github.com/coreos/etcd/storage/storagepb"
  26. )
  27. type watcherTest func(*testing.T, *watchctx)
  28. type watchctx struct {
  29. clus *integration.ClusterV3
  30. w clientv3.Watcher
  31. wclient *clientv3.Client
  32. kv clientv3.KV
  33. ch clientv3.WatchChan
  34. }
  35. func runWatchTest(t *testing.T, f watcherTest) {
  36. defer testutil.AfterTest(t)
  37. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  38. defer clus.Terminate(t)
  39. wclient := clus.RandClient()
  40. w := clientv3.NewWatcher(wclient)
  41. defer w.Close()
  42. // select a different client from wclient so puts succeed if
  43. // a test knocks out the watcher client
  44. kvclient := clus.RandClient()
  45. for kvclient == wclient {
  46. kvclient = clus.RandClient()
  47. }
  48. kv := clientv3.NewKV(kvclient)
  49. wctx := &watchctx{clus, w, wclient, kv, nil}
  50. f(t, wctx)
  51. }
  52. // TestWatchMultiWatcher modifies multiple keys and observes the changes.
  53. func TestWatchMultiWatcher(t *testing.T) {
  54. runWatchTest(t, testWatchMultiWatcher)
  55. }
  56. func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
  57. numKeyUpdates := 4
  58. keys := []string{"foo", "bar", "baz"}
  59. donec := make(chan struct{})
  60. readyc := make(chan struct{})
  61. for _, k := range keys {
  62. // key watcher
  63. go func(key string) {
  64. ch := wctx.w.Watch(context.TODO(), key)
  65. if ch == nil {
  66. t.Fatalf("expected watcher channel, got nil")
  67. }
  68. readyc <- struct{}{}
  69. for i := 0; i < numKeyUpdates; i++ {
  70. resp, ok := <-ch
  71. if !ok {
  72. t.Fatalf("watcher unexpectedly closed")
  73. }
  74. v := fmt.Sprintf("%s-%d", key, i)
  75. gotv := string(resp.Events[0].Kv.Value)
  76. if gotv != v {
  77. t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
  78. }
  79. }
  80. donec <- struct{}{}
  81. }(k)
  82. }
  83. // prefix watcher on "b" (bar and baz)
  84. go func() {
  85. prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
  86. if prefixc == nil {
  87. t.Fatalf("expected watcher channel, got nil")
  88. }
  89. readyc <- struct{}{}
  90. evs := []*storagepb.Event{}
  91. for i := 0; i < numKeyUpdates*2; i++ {
  92. resp, ok := <-prefixc
  93. if !ok {
  94. t.Fatalf("watcher unexpectedly closed")
  95. }
  96. evs = append(evs, resp.Events...)
  97. }
  98. // check response
  99. expected := []string{}
  100. bkeys := []string{"bar", "baz"}
  101. for _, k := range bkeys {
  102. for i := 0; i < numKeyUpdates; i++ {
  103. expected = append(expected, fmt.Sprintf("%s-%d", k, i))
  104. }
  105. }
  106. got := []string{}
  107. for _, ev := range evs {
  108. got = append(got, string(ev.Kv.Value))
  109. }
  110. sort.Strings(got)
  111. if reflect.DeepEqual(expected, got) == false {
  112. t.Errorf("got %v, expected %v", got, expected)
  113. }
  114. // ensure no extra data
  115. select {
  116. case resp, ok := <-prefixc:
  117. if !ok {
  118. t.Fatalf("watcher unexpectedly closed")
  119. }
  120. t.Fatalf("unexpected event %+v", resp)
  121. case <-time.After(time.Second):
  122. }
  123. donec <- struct{}{}
  124. }()
  125. // wait for watcher bring up
  126. for i := 0; i < len(keys)+1; i++ {
  127. <-readyc
  128. }
  129. // generate events
  130. ctx := context.TODO()
  131. for i := 0; i < numKeyUpdates; i++ {
  132. for _, k := range keys {
  133. v := fmt.Sprintf("%s-%d", k, i)
  134. if _, err := wctx.kv.Put(ctx, k, v); err != nil {
  135. t.Fatal(err)
  136. }
  137. }
  138. }
  139. // wait for watcher shutdown
  140. for i := 0; i < len(keys)+1; i++ {
  141. <-donec
  142. }
  143. }
  144. // TestWatchReconnRequest tests the send failure path when requesting a watcher.
  145. func TestWatchReconnRequest(t *testing.T) {
  146. runWatchTest(t, testWatchReconnRequest)
  147. }
  148. func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
  149. donec, stopc := make(chan struct{}), make(chan struct{}, 1)
  150. go func() {
  151. timer := time.After(2 * time.Second)
  152. defer close(donec)
  153. // take down watcher connection
  154. for {
  155. wctx.wclient.ActiveConnection().Close()
  156. select {
  157. case <-timer:
  158. // spinning on close may live lock reconnection
  159. return
  160. case <-stopc:
  161. return
  162. default:
  163. }
  164. }
  165. }()
  166. // should reconnect when requesting watch
  167. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  168. t.Fatalf("expected non-nil channel")
  169. }
  170. // wait for disconnections to stop
  171. stopc <- struct{}{}
  172. <-donec
  173. // ensure watcher works
  174. putAndWatch(t, wctx, "a", "a")
  175. }
  176. // TestWatchReconnInit tests watcher resumes correctly if connection lost
  177. // before any data was sent.
  178. func TestWatchReconnInit(t *testing.T) {
  179. runWatchTest(t, testWatchReconnInit)
  180. }
  181. func testWatchReconnInit(t *testing.T, wctx *watchctx) {
  182. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  183. t.Fatalf("expected non-nil channel")
  184. }
  185. // take down watcher connection
  186. wctx.wclient.ActiveConnection().Close()
  187. // watcher should recover
  188. putAndWatch(t, wctx, "a", "a")
  189. }
  190. // TestWatchReconnRunning tests watcher resumes correctly if connection lost
  191. // after data was sent.
  192. func TestWatchReconnRunning(t *testing.T) {
  193. runWatchTest(t, testWatchReconnRunning)
  194. }
  195. func testWatchReconnRunning(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. putAndWatch(t, wctx, "a", "a")
  200. // take down watcher connection
  201. wctx.wclient.ActiveConnection().Close()
  202. // watcher should recover
  203. putAndWatch(t, wctx, "a", "b")
  204. }
  205. // TestWatchCancelImmediate ensures a closed channel is returned
  206. // if the context is cancelled.
  207. func TestWatchCancelImmediate(t *testing.T) {
  208. runWatchTest(t, testWatchCancelImmediate)
  209. }
  210. func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
  211. ctx, cancel := context.WithCancel(context.Background())
  212. cancel()
  213. wch := wctx.w.Watch(ctx, "a")
  214. select {
  215. case wresp, ok := <-wch:
  216. if ok {
  217. t.Fatalf("read wch got %v; expected closed channel", wresp)
  218. }
  219. default:
  220. t.Fatalf("closed watcher channel should not block")
  221. }
  222. }
  223. // TestWatchCancelInit tests watcher closes correctly after no events.
  224. func TestWatchCancelInit(t *testing.T) {
  225. runWatchTest(t, testWatchCancelInit)
  226. }
  227. func testWatchCancelInit(t *testing.T, wctx *watchctx) {
  228. ctx, cancel := context.WithCancel(context.Background())
  229. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  230. t.Fatalf("expected non-nil watcher channel")
  231. }
  232. cancel()
  233. select {
  234. case <-time.After(time.Second):
  235. t.Fatalf("took too long to cancel")
  236. case _, ok := <-wctx.ch:
  237. if ok {
  238. t.Fatalf("expected watcher channel to close")
  239. }
  240. }
  241. }
  242. // TestWatchCancelRunning tests watcher closes correctly after events.
  243. func TestWatchCancelRunning(t *testing.T) {
  244. runWatchTest(t, testWatchCancelRunning)
  245. }
  246. func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
  247. ctx, cancel := context.WithCancel(context.Background())
  248. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  249. t.Fatalf("expected non-nil watcher channel")
  250. }
  251. if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
  252. t.Fatal(err)
  253. }
  254. cancel()
  255. select {
  256. case <-time.After(time.Second):
  257. t.Fatalf("took too long to cancel")
  258. case v, ok := <-wctx.ch:
  259. if !ok {
  260. // closed before getting put; OK
  261. break
  262. }
  263. // got the PUT; should close next
  264. select {
  265. case <-time.After(time.Second):
  266. t.Fatalf("took too long to close")
  267. case v, ok = <-wctx.ch:
  268. if ok {
  269. t.Fatalf("expected watcher channel to close, got %v", v)
  270. }
  271. }
  272. }
  273. }
  274. func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
  275. if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
  276. t.Fatal(err)
  277. }
  278. select {
  279. case <-time.After(5 * time.Second):
  280. t.Fatalf("watch timed out")
  281. case v, ok := <-wctx.ch:
  282. if !ok {
  283. t.Fatalf("unexpected watch close")
  284. }
  285. if string(v.Events[0].Kv.Value) != val {
  286. t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
  287. }
  288. }
  289. }
  290. func TestWatchInvalidFutureRevision(t *testing.T) {
  291. defer testutil.AfterTest(t)
  292. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  293. defer clus.Terminate(t)
  294. w := clientv3.NewWatcher(clus.RandClient())
  295. defer w.Close()
  296. rch := w.Watch(context.Background(), "foo", clientv3.WithRev(100))
  297. wresp, ok := <-rch // WatchResponse from canceled one
  298. if !ok {
  299. t.Fatalf("expected wresp 'open'(ok true), but got ok %v", ok)
  300. }
  301. if !wresp.Canceled {
  302. t.Fatalf("wresp.Canceled expected 'true', but got %v", wresp.Canceled)
  303. }
  304. _, ok = <-rch // ensure the channel is closed
  305. if ok != false {
  306. t.Fatalf("expected wresp 'closed'(ok false), but got ok %v", ok)
  307. }
  308. }