v3_watch_test.go 26 KB

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