watcher_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcd3
  14. import (
  15. "errors"
  16. "fmt"
  17. "reflect"
  18. "sync"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/clientv3"
  22. "github.com/coreos/etcd/integration"
  23. "golang.org/x/net/context"
  24. "k8s.io/kubernetes/pkg/api"
  25. "k8s.io/kubernetes/pkg/api/testapi"
  26. "k8s.io/kubernetes/pkg/api/unversioned"
  27. "k8s.io/kubernetes/pkg/runtime"
  28. "k8s.io/kubernetes/pkg/storage"
  29. "k8s.io/kubernetes/pkg/util/wait"
  30. "k8s.io/kubernetes/pkg/watch"
  31. )
  32. func TestWatch(t *testing.T) {
  33. testWatch(t, false)
  34. }
  35. func TestWatchList(t *testing.T) {
  36. testWatch(t, true)
  37. }
  38. // It tests that
  39. // - first occurrence of objects should notify Add event
  40. // - update should trigger Modified event
  41. // - update that gets filtered should trigger Deleted event
  42. func testWatch(t *testing.T, recursive bool) {
  43. ctx, store, cluster := testSetup(t)
  44. defer cluster.Terminate(t)
  45. podFoo := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
  46. podBar := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}
  47. tests := []struct {
  48. key string
  49. filter func(runtime.Object) bool
  50. trigger func() []storage.MatchValue
  51. watchTests []*testWatchStruct
  52. }{{ // create a key
  53. key: "/somekey-1",
  54. watchTests: []*testWatchStruct{{podFoo, true, watch.Added}},
  55. filter: storage.EverythingFunc,
  56. trigger: storage.NoTriggerFunc,
  57. }, { // create a key but obj gets filtered
  58. key: "/somekey-2",
  59. watchTests: []*testWatchStruct{{podFoo, false, ""}},
  60. filter: func(runtime.Object) bool { return false },
  61. trigger: storage.NoTriggerFunc,
  62. }, { // create a key but obj gets filtered. Then update it with unfiltered obj
  63. key: "/somekey-3",
  64. watchTests: []*testWatchStruct{{podFoo, false, ""}, {podBar, true, watch.Added}},
  65. filter: func(obj runtime.Object) bool {
  66. pod := obj.(*api.Pod)
  67. return pod.Name == "bar"
  68. },
  69. trigger: storage.NoTriggerFunc,
  70. }, { // update
  71. key: "/somekey-4",
  72. watchTests: []*testWatchStruct{{podFoo, true, watch.Added}, {podBar, true, watch.Modified}},
  73. filter: storage.EverythingFunc,
  74. trigger: storage.NoTriggerFunc,
  75. }, { // delete because of being filtered
  76. key: "/somekey-5",
  77. watchTests: []*testWatchStruct{{podFoo, true, watch.Added}, {podBar, true, watch.Deleted}},
  78. filter: func(obj runtime.Object) bool {
  79. pod := obj.(*api.Pod)
  80. return pod.Name != "bar"
  81. },
  82. trigger: storage.NoTriggerFunc,
  83. }}
  84. for i, tt := range tests {
  85. filter := storage.NewSimpleFilter(tt.filter, tt.trigger)
  86. w, err := store.watch(ctx, tt.key, "0", filter, recursive)
  87. if err != nil {
  88. t.Fatalf("Watch failed: %v", err)
  89. }
  90. var prevObj *api.Pod
  91. for _, watchTest := range tt.watchTests {
  92. out := &api.Pod{}
  93. key := tt.key
  94. if recursive {
  95. key = key + "/item"
  96. }
  97. err := store.GuaranteedUpdate(ctx, key, out, true, nil, storage.SimpleUpdate(
  98. func(runtime.Object) (runtime.Object, error) {
  99. return watchTest.obj, nil
  100. }))
  101. if err != nil {
  102. t.Fatalf("GuaranteedUpdate failed: %v", err)
  103. }
  104. if watchTest.expectEvent {
  105. expectObj := out
  106. if watchTest.watchType == watch.Deleted {
  107. expectObj = prevObj
  108. expectObj.ResourceVersion = out.ResourceVersion
  109. }
  110. testCheckResult(t, i, watchTest.watchType, w, expectObj)
  111. }
  112. prevObj = out
  113. }
  114. w.Stop()
  115. testCheckStop(t, i, w)
  116. }
  117. }
  118. func TestDeleteTriggerWatch(t *testing.T) {
  119. ctx, store, cluster := testSetup(t)
  120. defer cluster.Terminate(t)
  121. key, storedObj := testPropogateStore(t, store, ctx, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}})
  122. w, err := store.Watch(ctx, key, storedObj.ResourceVersion, storage.Everything)
  123. if err != nil {
  124. t.Fatalf("Watch failed: %v", err)
  125. }
  126. if err := store.Delete(ctx, key, &api.Pod{}, nil); err != nil {
  127. t.Fatalf("Delete failed: %v", err)
  128. }
  129. testCheckEventType(t, watch.Deleted, w)
  130. }
  131. // TestWatchFromZero tests that
  132. // - watch from 0 should sync up and grab the object added before
  133. // - watch from non-0 should just watch changes after given version
  134. func TestWatchFromZero(t *testing.T) {
  135. ctx, store, cluster := testSetup(t)
  136. defer cluster.Terminate(t)
  137. key, storedObj := testPropogateStore(t, store, ctx, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}})
  138. w, err := store.Watch(ctx, key, "0", storage.Everything)
  139. if err != nil {
  140. t.Fatalf("Watch failed: %v", err)
  141. }
  142. testCheckResult(t, 0, watch.Added, w, storedObj)
  143. }
  144. // TestWatchFromNoneZero tests that
  145. // - watch from non-0 should just watch changes after given version
  146. func TestWatchFromNoneZero(t *testing.T) {
  147. ctx, store, cluster := testSetup(t)
  148. defer cluster.Terminate(t)
  149. key, storedObj := testPropogateStore(t, store, ctx, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}})
  150. w, err := store.Watch(ctx, key, storedObj.ResourceVersion, storage.Everything)
  151. if err != nil {
  152. t.Fatalf("Watch failed: %v", err)
  153. }
  154. out := &api.Pod{}
  155. store.GuaranteedUpdate(ctx, key, out, true, nil, storage.SimpleUpdate(
  156. func(runtime.Object) (runtime.Object, error) {
  157. return &api.Pod{ObjectMeta: api.ObjectMeta{Name: "bar"}}, err
  158. }))
  159. testCheckResult(t, 0, watch.Modified, w, out)
  160. }
  161. func TestWatchError(t *testing.T) {
  162. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  163. defer cluster.Terminate(t)
  164. invalidStore := newStore(cluster.RandClient(), &testCodec{testapi.Default.Codec()}, "")
  165. ctx := context.Background()
  166. w, err := invalidStore.Watch(ctx, "/abc", "0", storage.Everything)
  167. if err != nil {
  168. t.Fatalf("Watch failed: %v", err)
  169. }
  170. validStore := newStore(cluster.RandClient(), testapi.Default.Codec(), "")
  171. validStore.GuaranteedUpdate(ctx, "/abc", &api.Pod{}, true, nil, storage.SimpleUpdate(
  172. func(runtime.Object) (runtime.Object, error) {
  173. return &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, nil
  174. }))
  175. testCheckEventType(t, watch.Error, w)
  176. }
  177. func TestWatchContextCancel(t *testing.T) {
  178. ctx, store, cluster := testSetup(t)
  179. defer cluster.Terminate(t)
  180. canceledCtx, cancel := context.WithCancel(ctx)
  181. cancel()
  182. w := store.watcher.createWatchChan(canceledCtx, "/abc", 0, false, storage.Everything)
  183. // When we do a client.Get with a canceled context, it will return error.
  184. // Nonetheless, when we try to send it over internal errChan, we should detect
  185. // it's context canceled and not send it.
  186. err := w.sync()
  187. w.ctx = ctx
  188. w.sendError(err)
  189. select {
  190. case err := <-w.errChan:
  191. t.Errorf("cancelling context shouldn't return any error. Err: %v", err)
  192. default:
  193. }
  194. }
  195. func TestWatchErrResultNotBlockAfterCancel(t *testing.T) {
  196. origCtx, store, cluster := testSetup(t)
  197. defer cluster.Terminate(t)
  198. ctx, cancel := context.WithCancel(origCtx)
  199. w := store.watcher.createWatchChan(ctx, "/abc", 0, false, storage.Everything)
  200. // make resutlChan and errChan blocking to ensure ordering.
  201. w.resultChan = make(chan watch.Event)
  202. w.errChan = make(chan error)
  203. // The event flow goes like:
  204. // - first we send an error, it should block on resultChan.
  205. // - Then we cancel ctx. The blocking on resultChan should be freed up
  206. // and run() goroutine should return.
  207. var wg sync.WaitGroup
  208. wg.Add(1)
  209. go func() {
  210. w.run()
  211. wg.Done()
  212. }()
  213. w.errChan <- fmt.Errorf("some error")
  214. cancel()
  215. wg.Wait()
  216. }
  217. func TestWatchDeleteEventObjectHaveLatestRV(t *testing.T) {
  218. ctx, store, cluster := testSetup(t)
  219. defer cluster.Terminate(t)
  220. key, storedObj := testPropogateStore(t, store, ctx, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}})
  221. w, err := store.Watch(ctx, key, storedObj.ResourceVersion, storage.Everything)
  222. if err != nil {
  223. t.Fatalf("Watch failed: %v", err)
  224. }
  225. etcdW := cluster.RandClient().Watch(ctx, "/", clientv3.WithPrefix())
  226. if err := store.Delete(ctx, key, &api.Pod{}, &storage.Preconditions{}); err != nil {
  227. t.Fatalf("Delete failed: %v", err)
  228. }
  229. e := <-w.ResultChan()
  230. watchedDeleteObj := e.Object.(*api.Pod)
  231. var wres clientv3.WatchResponse
  232. wres = <-etcdW
  233. watchedDeleteRev, err := storage.ParseWatchResourceVersion(watchedDeleteObj.ResourceVersion)
  234. if err != nil {
  235. t.Fatalf("ParseWatchResourceVersion failed: %v", err)
  236. }
  237. if int64(watchedDeleteRev) != wres.Events[0].Kv.ModRevision {
  238. t.Errorf("Object from delete event have version: %v, should be the same as etcd delete's mod rev: %d",
  239. watchedDeleteRev, wres.Events[0].Kv.ModRevision)
  240. }
  241. }
  242. type testWatchStruct struct {
  243. obj *api.Pod
  244. expectEvent bool
  245. watchType watch.EventType
  246. }
  247. type testCodec struct {
  248. runtime.Codec
  249. }
  250. func (c *testCodec) Decode(data []byte, defaults *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
  251. return nil, nil, errors.New("Expected decoding failure")
  252. }
  253. func testCheckEventType(t *testing.T, expectEventType watch.EventType, w watch.Interface) {
  254. select {
  255. case res := <-w.ResultChan():
  256. if res.Type != expectEventType {
  257. t.Errorf("event type want=%v, get=%v", expectEventType, res.Type)
  258. }
  259. case <-time.After(wait.ForeverTestTimeout):
  260. t.Errorf("time out after waiting %v on ResultChan", wait.ForeverTestTimeout)
  261. }
  262. }
  263. func testCheckResult(t *testing.T, i int, expectEventType watch.EventType, w watch.Interface, expectObj *api.Pod) {
  264. select {
  265. case res := <-w.ResultChan():
  266. if res.Type != expectEventType {
  267. t.Errorf("#%d: event type want=%v, get=%v", i, expectEventType, res.Type)
  268. return
  269. }
  270. if !reflect.DeepEqual(expectObj, res.Object) {
  271. t.Errorf("#%d: obj want=\n%#v\nget=\n%#v", i, expectObj, res.Object)
  272. }
  273. case <-time.After(wait.ForeverTestTimeout):
  274. t.Errorf("#%d: time out after waiting %v on ResultChan", i, wait.ForeverTestTimeout)
  275. }
  276. }
  277. func testCheckStop(t *testing.T, i int, w watch.Interface) {
  278. select {
  279. case e, ok := <-w.ResultChan():
  280. if ok {
  281. var obj string
  282. switch e.Object.(type) {
  283. case *api.Pod:
  284. obj = e.Object.(*api.Pod).Name
  285. case *unversioned.Status:
  286. obj = e.Object.(*unversioned.Status).Message
  287. }
  288. t.Errorf("#%d: ResultChan should have been closed. Event: %s. Object: %s", i, e.Type, obj)
  289. }
  290. case <-time.After(wait.ForeverTestTimeout):
  291. t.Errorf("#%d: time out after waiting 1s on ResultChan", i)
  292. }
  293. }