v3_watch_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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.package recipe
  14. package integration
  15. import (
  16. "bytes"
  17. "fmt"
  18. "reflect"
  19. "sort"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/pkg/testutil"
  27. "github.com/coreos/etcd/storage/storagepb"
  28. )
  29. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  30. func TestV3WatchFromCurrentRevision(t *testing.T) {
  31. defer testutil.AfterTest(t)
  32. tests := []struct {
  33. putKeys []string
  34. watchRequest *pb.WatchRequest
  35. wresps []*pb.WatchResponse
  36. }{
  37. // watch the key, matching
  38. {
  39. []string{"foo"},
  40. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  41. CreateRequest: &pb.WatchCreateRequest{
  42. Key: []byte("foo")}}},
  43. []*pb.WatchResponse{
  44. {
  45. Header: &pb.ResponseHeader{Revision: 2},
  46. Created: false,
  47. Events: []*storagepb.Event{
  48. {
  49. Type: storagepb.PUT,
  50. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  51. },
  52. },
  53. },
  54. },
  55. },
  56. // watch the key, non-matching
  57. {
  58. []string{"foo"},
  59. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  60. CreateRequest: &pb.WatchCreateRequest{
  61. Key: []byte("helloworld")}}},
  62. []*pb.WatchResponse{},
  63. },
  64. // watch the prefix, matching
  65. {
  66. []string{"fooLong"},
  67. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  68. CreateRequest: &pb.WatchCreateRequest{
  69. Key: []byte("foo"),
  70. RangeEnd: []byte("fop")}}},
  71. []*pb.WatchResponse{
  72. {
  73. Header: &pb.ResponseHeader{Revision: 2},
  74. Created: false,
  75. Events: []*storagepb.Event{
  76. {
  77. Type: storagepb.PUT,
  78. Kv: &storagepb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  79. },
  80. },
  81. },
  82. },
  83. },
  84. // watch the prefix, non-matching
  85. {
  86. []string{"foo"},
  87. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  88. CreateRequest: &pb.WatchCreateRequest{
  89. Key: []byte("helloworld"),
  90. RangeEnd: []byte("helloworle")}}},
  91. []*pb.WatchResponse{},
  92. },
  93. // watch full range, matching
  94. {
  95. []string{"fooLong"},
  96. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  97. CreateRequest: &pb.WatchCreateRequest{
  98. Key: []byte(""),
  99. RangeEnd: []byte("\x00")}}},
  100. []*pb.WatchResponse{
  101. {
  102. Header: &pb.ResponseHeader{Revision: 2},
  103. Created: false,
  104. Events: []*storagepb.Event{
  105. {
  106. Type: storagepb.PUT,
  107. Kv: &storagepb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  108. },
  109. },
  110. },
  111. },
  112. },
  113. // multiple puts, one watcher with matching key
  114. {
  115. []string{"foo", "foo", "foo"},
  116. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  117. CreateRequest: &pb.WatchCreateRequest{
  118. Key: []byte("foo")}}},
  119. []*pb.WatchResponse{
  120. {
  121. Header: &pb.ResponseHeader{Revision: 2},
  122. Created: false,
  123. Events: []*storagepb.Event{
  124. {
  125. Type: storagepb.PUT,
  126. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  127. },
  128. },
  129. },
  130. {
  131. Header: &pb.ResponseHeader{Revision: 3},
  132. Created: false,
  133. Events: []*storagepb.Event{
  134. {
  135. Type: storagepb.PUT,
  136. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  137. },
  138. },
  139. },
  140. {
  141. Header: &pb.ResponseHeader{Revision: 4},
  142. Created: false,
  143. Events: []*storagepb.Event{
  144. {
  145. Type: storagepb.PUT,
  146. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  147. },
  148. },
  149. },
  150. },
  151. },
  152. // multiple puts, one watcher with matching prefix
  153. {
  154. []string{"foo", "foo", "foo"},
  155. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  156. CreateRequest: &pb.WatchCreateRequest{
  157. Key: []byte("foo"),
  158. RangeEnd: []byte("fop")}}},
  159. []*pb.WatchResponse{
  160. {
  161. Header: &pb.ResponseHeader{Revision: 2},
  162. Created: false,
  163. Events: []*storagepb.Event{
  164. {
  165. Type: storagepb.PUT,
  166. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  167. },
  168. },
  169. },
  170. {
  171. Header: &pb.ResponseHeader{Revision: 3},
  172. Created: false,
  173. Events: []*storagepb.Event{
  174. {
  175. Type: storagepb.PUT,
  176. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  177. },
  178. },
  179. },
  180. {
  181. Header: &pb.ResponseHeader{Revision: 4},
  182. Created: false,
  183. Events: []*storagepb.Event{
  184. {
  185. Type: storagepb.PUT,
  186. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  187. },
  188. },
  189. },
  190. },
  191. },
  192. }
  193. for i, tt := range tests {
  194. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  195. wAPI := toGRPC(clus.RandClient()).Watch
  196. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  197. defer cancel()
  198. wStream, err := wAPI.Watch(ctx)
  199. if err != nil {
  200. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  201. }
  202. err = wStream.Send(tt.watchRequest)
  203. if err != nil {
  204. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  205. }
  206. // ensure watcher request created a new watcher
  207. cresp, err := wStream.Recv()
  208. if err != nil {
  209. t.Errorf("#%d: wStream.Recv error: %v", i, err)
  210. continue
  211. }
  212. if cresp.Created != true {
  213. t.Errorf("#%d: did not create watchid, got +%v", i, cresp)
  214. continue
  215. }
  216. if cresp.Canceled {
  217. t.Errorf("#%d: canceled watcher on create", i, cresp)
  218. continue
  219. }
  220. createdWatchId := cresp.WatchId
  221. if cresp.Header == nil || cresp.Header.Revision != 1 {
  222. t.Errorf("#%d: header revision got +%v, wanted revison 1", i, cresp)
  223. continue
  224. }
  225. // asynchronously create keys
  226. go func() {
  227. for _, k := range tt.putKeys {
  228. kvc := toGRPC(clus.RandClient()).KV
  229. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  230. if _, err := kvc.Put(context.TODO(), req); err != nil {
  231. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  232. }
  233. }
  234. }()
  235. // check stream results
  236. for j, wresp := range tt.wresps {
  237. resp, err := wStream.Recv()
  238. if err != nil {
  239. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  240. }
  241. if resp.Header == nil {
  242. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  243. }
  244. if resp.Header.Revision != wresp.Header.Revision {
  245. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  246. }
  247. if wresp.Created != resp.Created {
  248. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  249. }
  250. if resp.WatchId != createdWatchId {
  251. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  252. }
  253. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  254. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  255. }
  256. }
  257. rok, nr := waitResponse(wStream, 1*time.Second)
  258. if !rok {
  259. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  260. }
  261. // can't defer because tcp ports will be in use
  262. clus.Terminate(t)
  263. }
  264. }
  265. // TestV3WatchFutureRevision tests Watch APIs from a future revision.
  266. func TestV3WatchFutureRevision(t *testing.T) {
  267. defer testutil.AfterTest(t)
  268. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  269. defer clus.Terminate(t)
  270. wAPI := toGRPC(clus.RandClient()).Watch
  271. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  272. defer cancel()
  273. wStream, err := wAPI.Watch(ctx)
  274. if err != nil {
  275. t.Fatalf("wAPI.Watch error: %v", err)
  276. }
  277. wkey := []byte("foo")
  278. wrev := int64(10)
  279. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  280. CreateRequest: &pb.WatchCreateRequest{Key: wkey, StartRevision: wrev}}}
  281. err = wStream.Send(req)
  282. if err != nil {
  283. t.Fatalf("wStream.Send error: %v", err)
  284. }
  285. // ensure watcher request created a new watcher
  286. cresp, err := wStream.Recv()
  287. if err != nil {
  288. t.Fatalf("wStream.Recv error: %v", err)
  289. }
  290. if !cresp.Created {
  291. t.Fatal("create = %v, want %v", cresp.Created, true)
  292. }
  293. kvc := toGRPC(clus.RandClient()).KV
  294. for {
  295. req := &pb.PutRequest{Key: wkey, Value: []byte("bar")}
  296. resp, rerr := kvc.Put(context.TODO(), req)
  297. if rerr != nil {
  298. t.Fatalf("couldn't put key (%v)", rerr)
  299. }
  300. if resp.Header.Revision == wrev {
  301. break
  302. }
  303. }
  304. // ensure watcher request created a new watcher
  305. cresp, err = wStream.Recv()
  306. if err != nil {
  307. t.Fatalf("wStream.Recv error: %v", err)
  308. }
  309. if cresp.Header.Revision != wrev {
  310. t.Fatalf("revision = %d, want %d", cresp.Header.Revision, wrev)
  311. }
  312. if len(cresp.Events) != 1 {
  313. t.Fatalf("failed to receive events")
  314. }
  315. if cresp.Events[0].Kv.ModRevision != wrev {
  316. t.Errorf("mod revision = %d, want %d", cresp.Events[0].Kv.ModRevision, wrev)
  317. }
  318. }
  319. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  320. func TestV3WatchCancelSynced(t *testing.T) {
  321. defer testutil.AfterTest(t)
  322. testV3WatchCancel(t, 0)
  323. }
  324. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  325. func TestV3WatchCancelUnsynced(t *testing.T) {
  326. defer testutil.AfterTest(t)
  327. testV3WatchCancel(t, 1)
  328. }
  329. func testV3WatchCancel(t *testing.T, startRev int64) {
  330. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  331. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  332. defer cancel()
  333. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  334. if errW != nil {
  335. t.Fatalf("wAPI.Watch error: %v", errW)
  336. }
  337. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  338. CreateRequest: &pb.WatchCreateRequest{
  339. Key: []byte("foo"), StartRevision: startRev}}}
  340. if err := wStream.Send(wreq); err != nil {
  341. t.Fatalf("wStream.Send error: %v", err)
  342. }
  343. wresp, errR := wStream.Recv()
  344. if errR != nil {
  345. t.Errorf("wStream.Recv error: %v", errR)
  346. }
  347. if !wresp.Created {
  348. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  349. }
  350. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  351. CancelRequest: &pb.WatchCancelRequest{
  352. WatchId: wresp.WatchId}}}
  353. if err := wStream.Send(creq); err != nil {
  354. t.Fatalf("wStream.Send error: %v", err)
  355. }
  356. cresp, err := wStream.Recv()
  357. if err != nil {
  358. t.Errorf("wStream.Recv error: %v", err)
  359. }
  360. if !cresp.Canceled {
  361. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  362. }
  363. kvc := toGRPC(clus.RandClient()).KV
  364. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  365. t.Errorf("couldn't put key (%v)", err)
  366. }
  367. // watch got canceled, so this should block
  368. rok, nr := waitResponse(wStream, 1*time.Second)
  369. if !rok {
  370. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  371. }
  372. clus.Terminate(t)
  373. }
  374. // TestV3WatchCurrentPutOverlap ensures current watchers receive all events with
  375. // overlapping puts.
  376. func TestV3WatchCurrentPutOverlap(t *testing.T) {
  377. defer testutil.AfterTest(t)
  378. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  379. defer clus.Terminate(t)
  380. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  381. defer cancel()
  382. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  383. if wErr != nil {
  384. t.Fatalf("wAPI.Watch error: %v", wErr)
  385. }
  386. // last mod_revision that will be observed
  387. nrRevisions := 32
  388. // first revision already allocated as empty revision
  389. for i := 1; i < nrRevisions; i++ {
  390. go func() {
  391. kvc := toGRPC(clus.RandClient()).KV
  392. req := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  393. if _, err := kvc.Put(context.TODO(), req); err != nil {
  394. t.Fatalf("couldn't put key (%v)", err)
  395. }
  396. }()
  397. }
  398. // maps watcher to current expected revision
  399. progress := make(map[int64]int64)
  400. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  401. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}}}
  402. if err := wStream.Send(wreq); err != nil {
  403. t.Fatalf("first watch request failed (%v)", err)
  404. }
  405. more := true
  406. progress[-1] = 0 // watcher creation pending
  407. for more {
  408. resp, err := wStream.Recv()
  409. if err != nil {
  410. t.Fatalf("wStream.Recv error: %v", err)
  411. }
  412. if resp.Created {
  413. // accept events > header revision
  414. progress[resp.WatchId] = resp.Header.Revision + 1
  415. if resp.Header.Revision == int64(nrRevisions) {
  416. // covered all revisions; create no more watchers
  417. progress[-1] = int64(nrRevisions) + 1
  418. } else if err := wStream.Send(wreq); err != nil {
  419. t.Fatalf("watch request failed (%v)", err)
  420. }
  421. } else if len(resp.Events) == 0 {
  422. t.Fatalf("got events %v, want non-empty", resp.Events)
  423. } else {
  424. wRev, ok := progress[resp.WatchId]
  425. if !ok {
  426. t.Fatalf("got %+v, but watch id shouldn't exist ", resp)
  427. }
  428. if resp.Events[0].Kv.ModRevision != wRev {
  429. t.Fatalf("got %+v, wanted first revision %d", resp, wRev)
  430. }
  431. lastRev := resp.Events[len(resp.Events)-1].Kv.ModRevision
  432. progress[resp.WatchId] = lastRev + 1
  433. }
  434. more = false
  435. for _, v := range progress {
  436. if v <= int64(nrRevisions) {
  437. more = true
  438. break
  439. }
  440. }
  441. }
  442. if rok, nr := waitResponse(wStream, time.Second); !rok {
  443. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  444. }
  445. }
  446. // TestV3WatchEmptyKey ensures synced watchers see empty key PUTs as PUT events
  447. func TestV3WatchEmptyKey(t *testing.T) {
  448. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  449. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  450. defer cancel()
  451. ws, werr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  452. if werr != nil {
  453. t.Fatal(werr)
  454. }
  455. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  456. CreateRequest: &pb.WatchCreateRequest{
  457. Key: []byte("foo")}}}
  458. if err := ws.Send(req); err != nil {
  459. t.Fatal(err)
  460. }
  461. if _, err := ws.Recv(); err != nil {
  462. t.Fatal(err)
  463. }
  464. // put a key with empty value
  465. kvc := toGRPC(clus.RandClient()).KV
  466. preq := &pb.PutRequest{Key: []byte("foo")}
  467. if _, err := kvc.Put(context.TODO(), preq); err != nil {
  468. t.Fatal(err)
  469. }
  470. // check received PUT
  471. resp, rerr := ws.Recv()
  472. if rerr != nil {
  473. t.Fatal(rerr)
  474. }
  475. wevs := []*storagepb.Event{
  476. {
  477. Type: storagepb.PUT,
  478. Kv: &storagepb.KeyValue{Key: []byte("foo"), CreateRevision: 2, ModRevision: 2, Version: 1},
  479. },
  480. }
  481. if !reflect.DeepEqual(resp.Events, wevs) {
  482. t.Fatalf("got %v, expected %v", resp.Events, wevs)
  483. }
  484. clus.Terminate(t)
  485. }
  486. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  487. defer testutil.AfterTest(t)
  488. testV3WatchMultipleWatchers(t, 0)
  489. }
  490. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  491. defer testutil.AfterTest(t)
  492. testV3WatchMultipleWatchers(t, 1)
  493. }
  494. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  495. // and one watcher with matching prefix. It first puts the key
  496. // that matches all watchers, and another key that matches only
  497. // one watcher to test if it receives expected events.
  498. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  499. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  500. kvc := toGRPC(clus.RandClient()).KV
  501. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  502. defer cancel()
  503. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  504. if errW != nil {
  505. t.Fatalf("wAPI.Watch error: %v", errW)
  506. }
  507. watchKeyN := 4
  508. for i := 0; i < watchKeyN+1; i++ {
  509. var wreq *pb.WatchRequest
  510. if i < watchKeyN {
  511. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  512. CreateRequest: &pb.WatchCreateRequest{
  513. Key: []byte("foo"), StartRevision: startRev}}}
  514. } else {
  515. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  516. CreateRequest: &pb.WatchCreateRequest{
  517. Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev}}}
  518. }
  519. if err := wStream.Send(wreq); err != nil {
  520. t.Fatalf("wStream.Send error: %v", err)
  521. }
  522. }
  523. ids := make(map[int64]struct{})
  524. for i := 0; i < watchKeyN+1; i++ {
  525. wresp, err := wStream.Recv()
  526. if err != nil {
  527. t.Fatalf("wStream.Recv error: %v", err)
  528. }
  529. if !wresp.Created {
  530. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  531. }
  532. ids[wresp.WatchId] = struct{}{}
  533. }
  534. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  535. t.Fatalf("couldn't put key (%v)", err)
  536. }
  537. for i := 0; i < watchKeyN+1; i++ {
  538. wresp, err := wStream.Recv()
  539. if err != nil {
  540. t.Fatalf("wStream.Recv error: %v", err)
  541. }
  542. if _, ok := ids[wresp.WatchId]; !ok {
  543. t.Errorf("watchId %d is not created!", wresp.WatchId)
  544. } else {
  545. delete(ids, wresp.WatchId)
  546. }
  547. if len(wresp.Events) == 0 {
  548. t.Errorf("#%d: no events received", i)
  549. }
  550. for _, ev := range wresp.Events {
  551. if string(ev.Kv.Key) != "foo" {
  552. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  553. }
  554. if string(ev.Kv.Value) != "bar" {
  555. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  556. }
  557. }
  558. }
  559. // now put one key that has only one matching watcher
  560. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  561. t.Fatalf("couldn't put key (%v)", err)
  562. }
  563. wresp, err := wStream.Recv()
  564. if err != nil {
  565. t.Errorf("wStream.Recv error: %v", err)
  566. }
  567. if len(wresp.Events) != 1 {
  568. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  569. }
  570. if string(wresp.Events[0].Kv.Key) != "fo" {
  571. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  572. }
  573. // now Recv should block because there is no more events coming
  574. rok, nr := waitResponse(wStream, 1*time.Second)
  575. if !rok {
  576. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  577. }
  578. clus.Terminate(t)
  579. }
  580. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  581. defer testutil.AfterTest(t)
  582. testV3WatchMultipleEventsTxn(t, 0)
  583. }
  584. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  585. defer testutil.AfterTest(t)
  586. testV3WatchMultipleEventsTxn(t, 1)
  587. }
  588. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  589. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  590. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  591. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  592. defer cancel()
  593. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  594. if wErr != nil {
  595. t.Fatalf("wAPI.Watch error: %v", wErr)
  596. }
  597. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  598. CreateRequest: &pb.WatchCreateRequest{
  599. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev}}}
  600. if err := wStream.Send(wreq); err != nil {
  601. t.Fatalf("wStream.Send error: %v", err)
  602. }
  603. kvc := toGRPC(clus.RandClient()).KV
  604. txn := pb.TxnRequest{}
  605. for i := 0; i < 3; i++ {
  606. ru := &pb.RequestUnion{}
  607. ru.Request = &pb.RequestUnion_RequestPut{
  608. RequestPut: &pb.PutRequest{
  609. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  610. txn.Success = append(txn.Success, ru)
  611. }
  612. tresp, err := kvc.Txn(context.Background(), &txn)
  613. if err != nil {
  614. t.Fatalf("kvc.Txn error: %v", err)
  615. }
  616. if !tresp.Succeeded {
  617. t.Fatalf("kvc.Txn failed: %+v", tresp)
  618. }
  619. events := []*storagepb.Event{}
  620. for len(events) < 3 {
  621. resp, err := wStream.Recv()
  622. if err != nil {
  623. t.Errorf("wStream.Recv error: %v", err)
  624. }
  625. if resp.Created {
  626. continue
  627. }
  628. events = append(events, resp.Events...)
  629. }
  630. sort.Sort(eventsSortByKey(events))
  631. wevents := []*storagepb.Event{
  632. {
  633. Type: storagepb.PUT,
  634. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  635. },
  636. {
  637. Type: storagepb.PUT,
  638. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  639. },
  640. {
  641. Type: storagepb.PUT,
  642. Kv: &storagepb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  643. },
  644. }
  645. if !reflect.DeepEqual(events, wevents) {
  646. t.Errorf("events got = %+v, want = %+v", events, wevents)
  647. }
  648. rok, nr := waitResponse(wStream, 1*time.Second)
  649. if !rok {
  650. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  651. }
  652. // can't defer because tcp ports will be in use
  653. clus.Terminate(t)
  654. }
  655. type eventsSortByKey []*storagepb.Event
  656. func (evs eventsSortByKey) Len() int { return len(evs) }
  657. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  658. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  659. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  660. defer testutil.AfterTest(t)
  661. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  662. defer clus.Terminate(t)
  663. kvc := toGRPC(clus.RandClient()).KV
  664. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  665. t.Fatalf("couldn't put key (%v)", err)
  666. }
  667. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  668. t.Fatalf("couldn't put key (%v)", err)
  669. }
  670. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  671. defer cancel()
  672. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  673. if wErr != nil {
  674. t.Fatalf("wAPI.Watch error: %v", wErr)
  675. }
  676. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  677. CreateRequest: &pb.WatchCreateRequest{
  678. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1}}}
  679. if err := wStream.Send(wreq); err != nil {
  680. t.Fatalf("wStream.Send error: %v", err)
  681. }
  682. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  683. t.Fatalf("couldn't put key (%v)", err)
  684. }
  685. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  686. t.Fatalf("couldn't put key (%v)", err)
  687. }
  688. allWevents := []*storagepb.Event{
  689. {
  690. Type: storagepb.PUT,
  691. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  692. },
  693. {
  694. Type: storagepb.PUT,
  695. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  696. },
  697. {
  698. Type: storagepb.PUT,
  699. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  700. },
  701. {
  702. Type: storagepb.PUT,
  703. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  704. },
  705. }
  706. events := []*storagepb.Event{}
  707. for len(events) < 4 {
  708. resp, err := wStream.Recv()
  709. if err != nil {
  710. t.Errorf("wStream.Recv error: %v", err)
  711. }
  712. if resp.Created {
  713. continue
  714. }
  715. events = append(events, resp.Events...)
  716. // if PUT requests are committed by now, first receive would return
  717. // multiple events, but if not, it returns a single event. In SSD,
  718. // it should return 4 events at once.
  719. }
  720. if !reflect.DeepEqual(events, allWevents) {
  721. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  722. }
  723. rok, nr := waitResponse(wStream, 1*time.Second)
  724. if !rok {
  725. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  726. }
  727. }
  728. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  729. defer testutil.AfterTest(t)
  730. testV3WatchMultipleStreams(t, 0)
  731. }
  732. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  733. defer testutil.AfterTest(t)
  734. testV3WatchMultipleStreams(t, 1)
  735. }
  736. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  737. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  738. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  739. wAPI := toGRPC(clus.RandClient()).Watch
  740. kvc := toGRPC(clus.RandClient()).KV
  741. streams := make([]pb.Watch_WatchClient, 5)
  742. for i := range streams {
  743. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  744. defer cancel()
  745. wStream, errW := wAPI.Watch(ctx)
  746. if errW != nil {
  747. t.Fatalf("wAPI.Watch error: %v", errW)
  748. }
  749. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  750. CreateRequest: &pb.WatchCreateRequest{
  751. Key: []byte("foo"), StartRevision: startRev}}}
  752. if err := wStream.Send(wreq); err != nil {
  753. t.Fatalf("wStream.Send error: %v", err)
  754. }
  755. streams[i] = wStream
  756. }
  757. for _, wStream := range streams {
  758. wresp, err := wStream.Recv()
  759. if err != nil {
  760. t.Fatalf("wStream.Recv error: %v", err)
  761. }
  762. if !wresp.Created {
  763. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  764. }
  765. }
  766. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  767. t.Fatalf("couldn't put key (%v)", err)
  768. }
  769. var wg sync.WaitGroup
  770. wg.Add(len(streams))
  771. wevents := []*storagepb.Event{
  772. {
  773. Type: storagepb.PUT,
  774. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  775. },
  776. }
  777. for i := range streams {
  778. go func(i int) {
  779. defer wg.Done()
  780. wStream := streams[i]
  781. wresp, err := wStream.Recv()
  782. if err != nil {
  783. t.Fatalf("wStream.Recv error: %v", err)
  784. }
  785. if wresp.WatchId != 0 {
  786. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  787. }
  788. if !reflect.DeepEqual(wresp.Events, wevents) {
  789. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  790. }
  791. // now Recv should block because there is no more events coming
  792. rok, nr := waitResponse(wStream, 1*time.Second)
  793. if !rok {
  794. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  795. }
  796. }(i)
  797. }
  798. wg.Wait()
  799. clus.Terminate(t)
  800. }
  801. // waitResponse waits on the given stream for given duration.
  802. // If there is no more events, true and a nil response will be
  803. // returned closing the WatchClient stream. Or the response will
  804. // be returned.
  805. func waitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  806. rCh := make(chan *pb.WatchResponse)
  807. go func() {
  808. resp, _ := wc.Recv()
  809. rCh <- resp
  810. }()
  811. select {
  812. case nr := <-rCh:
  813. return false, nr
  814. case <-time.After(timeout):
  815. }
  816. wc.CloseSend()
  817. rv, ok := <-rCh
  818. if rv != nil || !ok {
  819. return false, rv
  820. }
  821. return true, nil
  822. }
  823. func TestWatchWithProgressNotify(t *testing.T) {
  824. testInterval := 3 * time.Second
  825. pi := v3rpc.ProgressReportInterval
  826. v3rpc.ProgressReportInterval = testInterval
  827. defer func() { v3rpc.ProgressReportInterval = pi }()
  828. defer testutil.AfterTest(t)
  829. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  830. defer clus.Terminate(t)
  831. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  832. defer cancel()
  833. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  834. if wErr != nil {
  835. t.Fatalf("wAPI.Watch error: %v", wErr)
  836. }
  837. // create two watchers, one with progressNotify set.
  838. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  839. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}}}
  840. if err := wStream.Send(wreq); err != nil {
  841. t.Fatalf("watch request failed (%v)", err)
  842. }
  843. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  844. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}}}
  845. if err := wStream.Send(wreq); err != nil {
  846. t.Fatalf("watch request failed (%v)", err)
  847. }
  848. // two creation + one notification
  849. for i := 0; i < 3; i++ {
  850. rok, resp := waitResponse(wStream, testInterval+time.Second)
  851. if resp.Created {
  852. continue
  853. }
  854. if rok {
  855. t.Errorf("failed to receive response from watch stream")
  856. }
  857. if resp.Header.Revision != 1 {
  858. t.Errorf("revision = %d, want 1", resp.Header.Revision)
  859. }
  860. if len(resp.Events) != 0 {
  861. t.Errorf("len(resp.Events) = %d, want 0", len(resp.Events))
  862. }
  863. }
  864. // no more notification
  865. rok, resp := waitResponse(wStream, testInterval+time.Second)
  866. if !rok {
  867. t.Errorf("unexpected pb.WatchResponse is received %+v", resp)
  868. }
  869. }