v3_watch_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  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. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  266. func TestV3WatchCancelSynced(t *testing.T) {
  267. defer testutil.AfterTest(t)
  268. testV3WatchCancel(t, 0)
  269. }
  270. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  271. func TestV3WatchCancelUnsynced(t *testing.T) {
  272. defer testutil.AfterTest(t)
  273. testV3WatchCancel(t, 1)
  274. }
  275. func testV3WatchCancel(t *testing.T, startRev int64) {
  276. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  277. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  278. defer cancel()
  279. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  280. if errW != nil {
  281. t.Fatalf("wAPI.Watch error: %v", errW)
  282. }
  283. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  284. CreateRequest: &pb.WatchCreateRequest{
  285. Key: []byte("foo"), StartRevision: startRev}}}
  286. if err := wStream.Send(wreq); err != nil {
  287. t.Fatalf("wStream.Send error: %v", err)
  288. }
  289. wresp, errR := wStream.Recv()
  290. if errR != nil {
  291. t.Errorf("wStream.Recv error: %v", errR)
  292. }
  293. if !wresp.Created {
  294. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  295. }
  296. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  297. CancelRequest: &pb.WatchCancelRequest{
  298. WatchId: wresp.WatchId}}}
  299. if err := wStream.Send(creq); err != nil {
  300. t.Fatalf("wStream.Send error: %v", err)
  301. }
  302. cresp, err := wStream.Recv()
  303. if err != nil {
  304. t.Errorf("wStream.Recv error: %v", err)
  305. }
  306. if !cresp.Canceled {
  307. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  308. }
  309. kvc := toGRPC(clus.RandClient()).KV
  310. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  311. t.Errorf("couldn't put key (%v)", err)
  312. }
  313. // watch got canceled, so this should block
  314. rok, nr := waitResponse(wStream, 1*time.Second)
  315. if !rok {
  316. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  317. }
  318. clus.Terminate(t)
  319. }
  320. // TestV3WatchCurrentPutOverlap ensures current watchers receive all events with
  321. // overlapping puts.
  322. func TestV3WatchCurrentPutOverlap(t *testing.T) {
  323. defer testutil.AfterTest(t)
  324. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  325. defer clus.Terminate(t)
  326. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  327. defer cancel()
  328. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  329. if wErr != nil {
  330. t.Fatalf("wAPI.Watch error: %v", wErr)
  331. }
  332. // last mod_revision that will be observed
  333. nrRevisions := 32
  334. // first revision already allocated as empty revision
  335. for i := 1; i < nrRevisions; i++ {
  336. go func() {
  337. kvc := toGRPC(clus.RandClient()).KV
  338. req := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  339. if _, err := kvc.Put(context.TODO(), req); err != nil {
  340. t.Fatalf("couldn't put key (%v)", err)
  341. }
  342. }()
  343. }
  344. // maps watcher to current expected revision
  345. progress := make(map[int64]int64)
  346. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  347. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}}}
  348. if err := wStream.Send(wreq); err != nil {
  349. t.Fatalf("first watch request failed (%v)", err)
  350. }
  351. more := true
  352. progress[-1] = 0 // watcher creation pending
  353. for more {
  354. resp, err := wStream.Recv()
  355. if err != nil {
  356. t.Fatalf("wStream.Recv error: %v", err)
  357. }
  358. if resp.Created {
  359. // accept events > header revision
  360. progress[resp.WatchId] = resp.Header.Revision + 1
  361. if resp.Header.Revision == int64(nrRevisions) {
  362. // covered all revisions; create no more watchers
  363. progress[-1] = int64(nrRevisions) + 1
  364. } else if err := wStream.Send(wreq); err != nil {
  365. t.Fatalf("watch request failed (%v)", err)
  366. }
  367. } else if len(resp.Events) == 0 {
  368. t.Fatalf("got events %v, want non-empty", resp.Events)
  369. } else {
  370. wRev, ok := progress[resp.WatchId]
  371. if !ok {
  372. t.Fatalf("got %+v, but watch id shouldn't exist ", resp)
  373. }
  374. if resp.Events[0].Kv.ModRevision != wRev {
  375. t.Fatalf("got %+v, wanted first revision %d", resp, wRev)
  376. }
  377. lastRev := resp.Events[len(resp.Events)-1].Kv.ModRevision
  378. progress[resp.WatchId] = lastRev + 1
  379. }
  380. more = false
  381. for _, v := range progress {
  382. if v <= int64(nrRevisions) {
  383. more = true
  384. break
  385. }
  386. }
  387. }
  388. if rok, nr := waitResponse(wStream, time.Second); !rok {
  389. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  390. }
  391. }
  392. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  393. defer testutil.AfterTest(t)
  394. testV3WatchMultipleWatchers(t, 0)
  395. }
  396. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  397. defer testutil.AfterTest(t)
  398. testV3WatchMultipleWatchers(t, 1)
  399. }
  400. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  401. // and one watcher with matching prefix. It first puts the key
  402. // that matches all watchers, and another key that matches only
  403. // one watcher to test if it receives expected events.
  404. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  405. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  406. kvc := toGRPC(clus.RandClient()).KV
  407. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  408. defer cancel()
  409. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  410. if errW != nil {
  411. t.Fatalf("wAPI.Watch error: %v", errW)
  412. }
  413. watchKeyN := 4
  414. for i := 0; i < watchKeyN+1; i++ {
  415. var wreq *pb.WatchRequest
  416. if i < watchKeyN {
  417. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  418. CreateRequest: &pb.WatchCreateRequest{
  419. Key: []byte("foo"), StartRevision: startRev}}}
  420. } else {
  421. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  422. CreateRequest: &pb.WatchCreateRequest{
  423. Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev}}}
  424. }
  425. if err := wStream.Send(wreq); err != nil {
  426. t.Fatalf("wStream.Send error: %v", err)
  427. }
  428. }
  429. ids := make(map[int64]struct{})
  430. for i := 0; i < watchKeyN+1; i++ {
  431. wresp, err := wStream.Recv()
  432. if err != nil {
  433. t.Fatalf("wStream.Recv error: %v", err)
  434. }
  435. if !wresp.Created {
  436. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  437. }
  438. ids[wresp.WatchId] = struct{}{}
  439. }
  440. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  441. t.Fatalf("couldn't put key (%v)", err)
  442. }
  443. for i := 0; i < watchKeyN+1; i++ {
  444. wresp, err := wStream.Recv()
  445. if err != nil {
  446. t.Fatalf("wStream.Recv error: %v", err)
  447. }
  448. if _, ok := ids[wresp.WatchId]; !ok {
  449. t.Errorf("watchId %d is not created!", wresp.WatchId)
  450. } else {
  451. delete(ids, wresp.WatchId)
  452. }
  453. if len(wresp.Events) == 0 {
  454. t.Errorf("#%d: no events received", i)
  455. }
  456. for _, ev := range wresp.Events {
  457. if string(ev.Kv.Key) != "foo" {
  458. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  459. }
  460. if string(ev.Kv.Value) != "bar" {
  461. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  462. }
  463. }
  464. }
  465. // now put one key that has only one matching watcher
  466. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  467. t.Fatalf("couldn't put key (%v)", err)
  468. }
  469. wresp, err := wStream.Recv()
  470. if err != nil {
  471. t.Errorf("wStream.Recv error: %v", err)
  472. }
  473. if len(wresp.Events) != 1 {
  474. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  475. }
  476. if string(wresp.Events[0].Kv.Key) != "fo" {
  477. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  478. }
  479. // now Recv should block because there is no more events coming
  480. rok, nr := waitResponse(wStream, 1*time.Second)
  481. if !rok {
  482. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  483. }
  484. clus.Terminate(t)
  485. }
  486. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  487. defer testutil.AfterTest(t)
  488. testV3WatchMultipleEventsTxn(t, 0)
  489. }
  490. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  491. defer testutil.AfterTest(t)
  492. testV3WatchMultipleEventsTxn(t, 1)
  493. }
  494. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  495. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  496. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  497. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  498. defer cancel()
  499. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  500. if wErr != nil {
  501. t.Fatalf("wAPI.Watch error: %v", wErr)
  502. }
  503. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  504. CreateRequest: &pb.WatchCreateRequest{
  505. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev}}}
  506. if err := wStream.Send(wreq); err != nil {
  507. t.Fatalf("wStream.Send error: %v", err)
  508. }
  509. kvc := toGRPC(clus.RandClient()).KV
  510. txn := pb.TxnRequest{}
  511. for i := 0; i < 3; i++ {
  512. ru := &pb.RequestUnion{}
  513. ru.Request = &pb.RequestUnion_RequestPut{
  514. RequestPut: &pb.PutRequest{
  515. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  516. txn.Success = append(txn.Success, ru)
  517. }
  518. tresp, err := kvc.Txn(context.Background(), &txn)
  519. if err != nil {
  520. t.Fatalf("kvc.Txn error: %v", err)
  521. }
  522. if !tresp.Succeeded {
  523. t.Fatalf("kvc.Txn failed: %+v", tresp)
  524. }
  525. events := []*storagepb.Event{}
  526. for len(events) < 3 {
  527. resp, err := wStream.Recv()
  528. if err != nil {
  529. t.Errorf("wStream.Recv error: %v", err)
  530. }
  531. if resp.Created {
  532. continue
  533. }
  534. events = append(events, resp.Events...)
  535. }
  536. sort.Sort(eventsSortByKey(events))
  537. wevents := []*storagepb.Event{
  538. {
  539. Type: storagepb.PUT,
  540. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  541. },
  542. {
  543. Type: storagepb.PUT,
  544. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  545. },
  546. {
  547. Type: storagepb.PUT,
  548. Kv: &storagepb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  549. },
  550. }
  551. if !reflect.DeepEqual(events, wevents) {
  552. t.Errorf("events got = %+v, want = %+v", events, wevents)
  553. }
  554. rok, nr := waitResponse(wStream, 1*time.Second)
  555. if !rok {
  556. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  557. }
  558. // can't defer because tcp ports will be in use
  559. clus.Terminate(t)
  560. }
  561. type eventsSortByKey []*storagepb.Event
  562. func (evs eventsSortByKey) Len() int { return len(evs) }
  563. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  564. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  565. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  566. defer testutil.AfterTest(t)
  567. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  568. defer clus.Terminate(t)
  569. kvc := toGRPC(clus.RandClient()).KV
  570. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  571. t.Fatalf("couldn't put key (%v)", err)
  572. }
  573. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  574. t.Fatalf("couldn't put key (%v)", err)
  575. }
  576. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  577. defer cancel()
  578. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  579. if wErr != nil {
  580. t.Fatalf("wAPI.Watch error: %v", wErr)
  581. }
  582. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  583. CreateRequest: &pb.WatchCreateRequest{
  584. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1}}}
  585. if err := wStream.Send(wreq); err != nil {
  586. t.Fatalf("wStream.Send error: %v", err)
  587. }
  588. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  589. t.Fatalf("couldn't put key (%v)", err)
  590. }
  591. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  592. t.Fatalf("couldn't put key (%v)", err)
  593. }
  594. allWevents := []*storagepb.Event{
  595. {
  596. Type: storagepb.PUT,
  597. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  598. },
  599. {
  600. Type: storagepb.PUT,
  601. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  602. },
  603. {
  604. Type: storagepb.PUT,
  605. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  606. },
  607. {
  608. Type: storagepb.PUT,
  609. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  610. },
  611. }
  612. events := []*storagepb.Event{}
  613. for len(events) < 4 {
  614. resp, err := wStream.Recv()
  615. if err != nil {
  616. t.Errorf("wStream.Recv error: %v", err)
  617. }
  618. if resp.Created {
  619. continue
  620. }
  621. events = append(events, resp.Events...)
  622. // if PUT requests are committed by now, first receive would return
  623. // multiple events, but if not, it returns a single event. In SSD,
  624. // it should return 4 events at once.
  625. }
  626. if !reflect.DeepEqual(events, allWevents) {
  627. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  628. }
  629. rok, nr := waitResponse(wStream, 1*time.Second)
  630. if !rok {
  631. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  632. }
  633. }
  634. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  635. defer testutil.AfterTest(t)
  636. testV3WatchMultipleStreams(t, 0)
  637. }
  638. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  639. defer testutil.AfterTest(t)
  640. testV3WatchMultipleStreams(t, 1)
  641. }
  642. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  643. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  644. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  645. wAPI := toGRPC(clus.RandClient()).Watch
  646. kvc := toGRPC(clus.RandClient()).KV
  647. streams := make([]pb.Watch_WatchClient, 5)
  648. for i := range streams {
  649. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  650. defer cancel()
  651. wStream, errW := wAPI.Watch(ctx)
  652. if errW != nil {
  653. t.Fatalf("wAPI.Watch error: %v", errW)
  654. }
  655. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  656. CreateRequest: &pb.WatchCreateRequest{
  657. Key: []byte("foo"), StartRevision: startRev}}}
  658. if err := wStream.Send(wreq); err != nil {
  659. t.Fatalf("wStream.Send error: %v", err)
  660. }
  661. streams[i] = wStream
  662. }
  663. for _, wStream := range streams {
  664. wresp, err := wStream.Recv()
  665. if err != nil {
  666. t.Fatalf("wStream.Recv error: %v", err)
  667. }
  668. if !wresp.Created {
  669. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  670. }
  671. }
  672. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  673. t.Fatalf("couldn't put key (%v)", err)
  674. }
  675. var wg sync.WaitGroup
  676. wg.Add(len(streams))
  677. wevents := []*storagepb.Event{
  678. {
  679. Type: storagepb.PUT,
  680. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  681. },
  682. }
  683. for i := range streams {
  684. go func(i int) {
  685. defer wg.Done()
  686. wStream := streams[i]
  687. wresp, err := wStream.Recv()
  688. if err != nil {
  689. t.Fatalf("wStream.Recv error: %v", err)
  690. }
  691. if wresp.WatchId != 0 {
  692. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  693. }
  694. if !reflect.DeepEqual(wresp.Events, wevents) {
  695. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  696. }
  697. // now Recv should block because there is no more events coming
  698. rok, nr := waitResponse(wStream, 1*time.Second)
  699. if !rok {
  700. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  701. }
  702. }(i)
  703. }
  704. wg.Wait()
  705. clus.Terminate(t)
  706. }
  707. // waitResponse waits on the given stream for given duration.
  708. // If there is no more events, true and a nil response will be
  709. // returned closing the WatchClient stream. Or the response will
  710. // be returned.
  711. func waitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  712. rCh := make(chan *pb.WatchResponse)
  713. go func() {
  714. resp, _ := wc.Recv()
  715. rCh <- resp
  716. }()
  717. select {
  718. case nr := <-rCh:
  719. return false, nr
  720. case <-time.After(timeout):
  721. }
  722. wc.CloseSend()
  723. rv, ok := <-rCh
  724. if rv != nil || !ok {
  725. return false, rv
  726. }
  727. return true, nil
  728. }
  729. // TestV3WatchFutureRevision ensures invalid future revision to Watch APIs
  730. // returns WatchResponse of true Created and true Canceled.
  731. func TestV3WatchInvalidFutureRevision(t *testing.T) {
  732. defer testutil.AfterTest(t)
  733. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  734. defer clus.Terminate(t)
  735. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  736. defer cancel()
  737. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  738. if wErr != nil {
  739. t.Fatalf("wAPI.Watch error: %v", wErr)
  740. }
  741. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  742. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 100}}}
  743. if err := wStream.Send(wreq); err != nil {
  744. t.Fatalf("watch request failed (%v)", err)
  745. }
  746. resp, err := wStream.Recv()
  747. if err != nil {
  748. t.Errorf("wStream.Recv error: %v", err)
  749. }
  750. if resp.WatchId != -1 || !resp.Created || !resp.Canceled || len(resp.Events) != 0 {
  751. t.Errorf("invalid start-rev expected -1, true, true, 0, but got %d, %v, %v, %d",
  752. resp.WatchId, resp.Created, resp.Canceled, len(resp.Events))
  753. }
  754. }
  755. func TestWatchWithProgressNotify(t *testing.T) {
  756. testInterval := 3 * time.Second
  757. pi := v3rpc.ProgressReportInterval
  758. v3rpc.ProgressReportInterval = testInterval
  759. defer func() { v3rpc.ProgressReportInterval = pi }()
  760. defer testutil.AfterTest(t)
  761. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  762. defer clus.Terminate(t)
  763. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  764. defer cancel()
  765. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  766. if wErr != nil {
  767. t.Fatalf("wAPI.Watch error: %v", wErr)
  768. }
  769. // create two watchers, one with progressNotify set.
  770. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  771. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}}}
  772. if err := wStream.Send(wreq); err != nil {
  773. t.Fatalf("watch request failed (%v)", err)
  774. }
  775. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  776. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}}}
  777. if err := wStream.Send(wreq); err != nil {
  778. t.Fatalf("watch request failed (%v)", err)
  779. }
  780. // two creation + one notification
  781. for i := 0; i < 3; i++ {
  782. rok, resp := waitResponse(wStream, testInterval+time.Second)
  783. if resp.Created {
  784. continue
  785. }
  786. if rok {
  787. t.Errorf("failed to receive response from watch stream")
  788. }
  789. if resp.Header.Revision != 1 {
  790. t.Errorf("revision = %d, want 1", resp.Header.Revision)
  791. }
  792. if len(resp.Events) != 0 {
  793. t.Errorf("len(resp.Events) = %d, want 0", len(resp.Events))
  794. }
  795. }
  796. // no more notification
  797. rok, resp := waitResponse(wStream, testInterval+time.Second)
  798. if !rok {
  799. t.Errorf("unexpected pb.WatchResponse is received %+v", resp)
  800. }
  801. }