v3_watch_test.go 28 KB

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