kv_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. // Copyright 2016 The etcd Authors
  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. "reflect"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/clientv3"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  23. "github.com/coreos/etcd/integration"
  24. "github.com/coreos/etcd/mvcc/mvccpb"
  25. "github.com/coreos/etcd/pkg/testutil"
  26. "golang.org/x/net/context"
  27. )
  28. func TestKVPutError(t *testing.T) {
  29. defer testutil.AfterTest(t)
  30. var (
  31. maxReqBytes = 1.5 * 1024 * 1024
  32. quota = int64(maxReqBytes * 1.2)
  33. )
  34. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1, QuotaBackendBytes: quota})
  35. defer clus.Terminate(t)
  36. kv := clientv3.NewKV(clus.RandClient())
  37. ctx := context.TODO()
  38. _, err := kv.Put(ctx, "", "bar")
  39. if err != rpctypes.ErrEmptyKey {
  40. t.Fatalf("expected %v, got %v", rpctypes.ErrEmptyKey, err)
  41. }
  42. _, err = kv.Put(ctx, "key", strings.Repeat("a", int(maxReqBytes+100))) // 1.5MB
  43. if err != rpctypes.ErrRequestTooLarge {
  44. t.Fatalf("expected %v, got %v", rpctypes.ErrRequestTooLarge, err)
  45. }
  46. _, err = kv.Put(ctx, "foo1", strings.Repeat("a", int(maxReqBytes-50)))
  47. if err != nil { // below quota
  48. t.Fatal(err)
  49. }
  50. time.Sleep(500 * time.Millisecond) // give enough time for commit
  51. _, err = kv.Put(ctx, "foo2", strings.Repeat("a", int(maxReqBytes-50)))
  52. if err != rpctypes.ErrNoSpace { // over quota
  53. t.Fatalf("expected %v, got %v", rpctypes.ErrNoSpace, err)
  54. }
  55. }
  56. func TestKVPut(t *testing.T) {
  57. defer testutil.AfterTest(t)
  58. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  59. defer clus.Terminate(t)
  60. lapi := clientv3.NewLease(clus.RandClient())
  61. defer lapi.Close()
  62. kv := clientv3.NewKV(clus.RandClient())
  63. ctx := context.TODO()
  64. resp, err := lapi.Grant(context.Background(), 10)
  65. if err != nil {
  66. t.Fatalf("failed to create lease %v", err)
  67. }
  68. tests := []struct {
  69. key, val string
  70. leaseID clientv3.LeaseID
  71. }{
  72. {"foo", "bar", clientv3.NoLease},
  73. {"hello", "world", resp.ID},
  74. }
  75. for i, tt := range tests {
  76. if _, err := kv.Put(ctx, tt.key, tt.val, clientv3.WithLease(tt.leaseID)); err != nil {
  77. t.Fatalf("#%d: couldn't put %q (%v)", i, tt.key, err)
  78. }
  79. resp, err := kv.Get(ctx, tt.key)
  80. if err != nil {
  81. t.Fatalf("#%d: couldn't get key (%v)", i, err)
  82. }
  83. if len(resp.Kvs) != 1 {
  84. t.Fatalf("#%d: expected 1 key, got %d", i, len(resp.Kvs))
  85. }
  86. if !bytes.Equal([]byte(tt.val), resp.Kvs[0].Value) {
  87. t.Errorf("#%d: val = %s, want %s", i, tt.val, resp.Kvs[0].Value)
  88. }
  89. if tt.leaseID != clientv3.LeaseID(resp.Kvs[0].Lease) {
  90. t.Errorf("#%d: val = %d, want %d", i, tt.leaseID, resp.Kvs[0].Lease)
  91. }
  92. }
  93. }
  94. func TestKVPutWithRequireLeader(t *testing.T) {
  95. // this test might block for a few seconds, make it parallel to speed up the test.
  96. t.Parallel()
  97. defer testutil.AfterTest(t)
  98. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  99. defer clus.Terminate(t)
  100. clus.Members[1].Stop(t)
  101. clus.Members[2].Stop(t)
  102. // wait for election timeout, then member[0] will not have a leader.
  103. var (
  104. electionTicks = 10
  105. tickDuration = 10 * time.Millisecond
  106. )
  107. time.Sleep(time.Duration(3*electionTicks) * tickDuration)
  108. kv := clientv3.NewKV(clus.Client(0))
  109. _, err := kv.Put(clientv3.WithRequireLeader(context.Background()), "foo", "bar")
  110. if err != rpctypes.ErrNoLeader {
  111. t.Fatal(err)
  112. }
  113. }
  114. func TestKVRange(t *testing.T) {
  115. defer testutil.AfterTest(t)
  116. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  117. defer clus.Terminate(t)
  118. kv := clientv3.NewKV(clus.RandClient())
  119. ctx := context.TODO()
  120. keySet := []string{"a", "b", "c", "c", "c", "foo", "foo/abc", "fop"}
  121. for i, key := range keySet {
  122. if _, err := kv.Put(ctx, key, ""); err != nil {
  123. t.Fatalf("#%d: couldn't put %q (%v)", i, key, err)
  124. }
  125. }
  126. resp, err := kv.Get(ctx, keySet[0])
  127. if err != nil {
  128. t.Fatalf("couldn't get key (%v)", err)
  129. }
  130. wheader := resp.Header
  131. tests := []struct {
  132. begin, end string
  133. rev int64
  134. opts []clientv3.OpOption
  135. wantSet []*mvccpb.KeyValue
  136. }{
  137. // range first two
  138. {
  139. "a", "c",
  140. 0,
  141. nil,
  142. []*mvccpb.KeyValue{
  143. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  144. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  145. },
  146. },
  147. // range first two with serializable
  148. {
  149. "a", "c",
  150. 0,
  151. []clientv3.OpOption{clientv3.WithSerializable()},
  152. []*mvccpb.KeyValue{
  153. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  154. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  155. },
  156. },
  157. // range all with rev
  158. {
  159. "a", "x",
  160. 2,
  161. nil,
  162. []*mvccpb.KeyValue{
  163. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  164. },
  165. },
  166. // range all with SortByKey, SortAscend
  167. {
  168. "a", "x",
  169. 0,
  170. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
  171. []*mvccpb.KeyValue{
  172. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  173. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  174. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  175. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  176. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  177. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  178. },
  179. },
  180. // range all with SortByCreateRevision, SortDescend
  181. {
  182. "a", "x",
  183. 0,
  184. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortDescend)},
  185. []*mvccpb.KeyValue{
  186. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  187. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  188. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  189. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  190. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  191. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  192. },
  193. },
  194. // range all with SortByModRevision, SortDescend
  195. {
  196. "a", "x",
  197. 0,
  198. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByModRevision, clientv3.SortDescend)},
  199. []*mvccpb.KeyValue{
  200. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  201. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  202. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  203. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  204. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  205. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  206. },
  207. },
  208. // WithPrefix
  209. {
  210. "foo", "",
  211. 0,
  212. []clientv3.OpOption{clientv3.WithPrefix()},
  213. []*mvccpb.KeyValue{
  214. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  215. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  216. },
  217. },
  218. // WithFromKey
  219. {
  220. "fo", "",
  221. 0,
  222. []clientv3.OpOption{clientv3.WithFromKey()},
  223. []*mvccpb.KeyValue{
  224. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  225. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  226. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  227. },
  228. },
  229. }
  230. for i, tt := range tests {
  231. opts := []clientv3.OpOption{clientv3.WithRange(tt.end), clientv3.WithRev(tt.rev)}
  232. opts = append(opts, tt.opts...)
  233. resp, err := kv.Get(ctx, tt.begin, opts...)
  234. if err != nil {
  235. t.Fatalf("#%d: couldn't range (%v)", i, err)
  236. }
  237. if !reflect.DeepEqual(wheader, resp.Header) {
  238. t.Fatalf("#%d: wheader expected %+v, got %+v", i, wheader, resp.Header)
  239. }
  240. if !reflect.DeepEqual(tt.wantSet, resp.Kvs) {
  241. t.Fatalf("#%d: resp.Kvs expected %+v, got %+v", i, tt.wantSet, resp.Kvs)
  242. }
  243. }
  244. }
  245. func TestKVDeleteRange(t *testing.T) {
  246. defer testutil.AfterTest(t)
  247. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  248. defer clus.Terminate(t)
  249. kv := clientv3.NewKV(clus.RandClient())
  250. ctx := context.TODO()
  251. tests := []struct {
  252. key string
  253. opts []clientv3.OpOption
  254. wkeys []string
  255. }{
  256. // [a, c)
  257. {
  258. key: "a",
  259. opts: []clientv3.OpOption{clientv3.WithRange("c")},
  260. wkeys: []string{"c", "c/abc", "d"},
  261. },
  262. // >= c
  263. {
  264. key: "c",
  265. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  266. wkeys: []string{"a", "b"},
  267. },
  268. // c*
  269. {
  270. key: "c",
  271. opts: []clientv3.OpOption{clientv3.WithPrefix()},
  272. wkeys: []string{"a", "b", "d"},
  273. },
  274. // *
  275. {
  276. key: "\x00",
  277. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  278. wkeys: []string{},
  279. },
  280. }
  281. for i, tt := range tests {
  282. keySet := []string{"a", "b", "c", "c/abc", "d"}
  283. for j, key := range keySet {
  284. if _, err := kv.Put(ctx, key, ""); err != nil {
  285. t.Fatalf("#%d: couldn't put %q (%v)", j, key, err)
  286. }
  287. }
  288. _, err := kv.Delete(ctx, tt.key, tt.opts...)
  289. if err != nil {
  290. t.Fatalf("#%d: couldn't delete range (%v)", i, err)
  291. }
  292. resp, err := kv.Get(ctx, "a", clientv3.WithFromKey())
  293. if err != nil {
  294. t.Fatalf("#%d: couldn't get keys (%v)", i, err)
  295. }
  296. keys := []string{}
  297. for _, kv := range resp.Kvs {
  298. keys = append(keys, string(kv.Key))
  299. }
  300. if !reflect.DeepEqual(tt.wkeys, keys) {
  301. t.Errorf("#%d: resp.Kvs got %v, expected %v", i, keys, tt.wkeys)
  302. }
  303. }
  304. }
  305. func TestKVDelete(t *testing.T) {
  306. defer testutil.AfterTest(t)
  307. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  308. defer clus.Terminate(t)
  309. kv := clientv3.NewKV(clus.RandClient())
  310. ctx := context.TODO()
  311. presp, err := kv.Put(ctx, "foo", "")
  312. if err != nil {
  313. t.Fatalf("couldn't put 'foo' (%v)", err)
  314. }
  315. if presp.Header.Revision != 2 {
  316. t.Fatalf("presp.Header.Revision got %d, want %d", presp.Header.Revision, 2)
  317. }
  318. resp, err := kv.Delete(ctx, "foo")
  319. if err != nil {
  320. t.Fatalf("couldn't delete key (%v)", err)
  321. }
  322. if resp.Header.Revision != 3 {
  323. t.Fatalf("resp.Header.Revision got %d, want %d", resp.Header.Revision, 3)
  324. }
  325. gresp, err := kv.Get(ctx, "foo")
  326. if err != nil {
  327. t.Fatalf("couldn't get key (%v)", err)
  328. }
  329. if len(gresp.Kvs) > 0 {
  330. t.Fatalf("gresp.Kvs got %+v, want none", gresp.Kvs)
  331. }
  332. }
  333. func TestKVCompactError(t *testing.T) {
  334. defer testutil.AfterTest(t)
  335. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  336. defer clus.Terminate(t)
  337. kv := clientv3.NewKV(clus.RandClient())
  338. ctx := context.TODO()
  339. for i := 0; i < 5; i++ {
  340. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  341. t.Fatalf("couldn't put 'foo' (%v)", err)
  342. }
  343. }
  344. err := kv.Compact(ctx, 6)
  345. if err != nil {
  346. t.Fatalf("couldn't compact 6 (%v)", err)
  347. }
  348. err = kv.Compact(ctx, 6)
  349. if err != rpctypes.ErrCompacted {
  350. t.Fatalf("expected %v, got %v", rpctypes.ErrCompacted, err)
  351. }
  352. err = kv.Compact(ctx, 100)
  353. if err != rpctypes.ErrFutureRev {
  354. t.Fatalf("expected %v, got %v", rpctypes.ErrFutureRev, err)
  355. }
  356. }
  357. func TestKVCompact(t *testing.T) {
  358. defer testutil.AfterTest(t)
  359. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  360. defer clus.Terminate(t)
  361. kv := clientv3.NewKV(clus.RandClient())
  362. ctx := context.TODO()
  363. for i := 0; i < 10; i++ {
  364. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  365. t.Fatalf("couldn't put 'foo' (%v)", err)
  366. }
  367. }
  368. err := kv.Compact(ctx, 7)
  369. if err != nil {
  370. t.Fatalf("couldn't compact kv space (%v)", err)
  371. }
  372. err = kv.Compact(ctx, 7)
  373. if err == nil || err != rpctypes.ErrCompacted {
  374. t.Fatalf("error got %v, want %v", err, rpctypes.ErrCompacted)
  375. }
  376. wcli := clus.RandClient()
  377. // new watcher could precede receiving the compaction without quorum first
  378. wcli.Get(ctx, "quorum-get")
  379. wc := clientv3.NewWatcher(wcli)
  380. defer wc.Close()
  381. wchan := wc.Watch(ctx, "foo", clientv3.WithRev(3))
  382. if wr := <-wchan; wr.CompactRevision != 7 {
  383. t.Fatalf("wchan CompactRevision got %v, want 7", wr.CompactRevision)
  384. }
  385. if wr, ok := <-wchan; ok {
  386. t.Fatalf("wchan got %v, expected closed", wr)
  387. }
  388. err = kv.Compact(ctx, 1000)
  389. if err == nil || err != rpctypes.ErrFutureRev {
  390. t.Fatalf("error got %v, want %v", err, rpctypes.ErrFutureRev)
  391. }
  392. }
  393. // TestKVGetRetry ensures get will retry on disconnect.
  394. func TestKVGetRetry(t *testing.T) {
  395. defer testutil.AfterTest(t)
  396. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  397. defer clus.Terminate(t)
  398. kv := clientv3.NewKV(clus.Client(0))
  399. ctx := context.TODO()
  400. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  401. t.Fatal(err)
  402. }
  403. clus.Members[0].Stop(t)
  404. <-clus.Members[0].StopNotify()
  405. donec := make(chan struct{})
  406. go func() {
  407. // Get will fail, but reconnect will trigger
  408. gresp, gerr := kv.Get(ctx, "foo")
  409. if gerr != nil {
  410. t.Fatal(gerr)
  411. }
  412. wkvs := []*mvccpb.KeyValue{
  413. {
  414. Key: []byte("foo"),
  415. Value: []byte("bar"),
  416. CreateRevision: 2,
  417. ModRevision: 2,
  418. Version: 1,
  419. },
  420. }
  421. if !reflect.DeepEqual(gresp.Kvs, wkvs) {
  422. t.Fatalf("bad get: got %v, want %v", gresp.Kvs, wkvs)
  423. }
  424. donec <- struct{}{}
  425. }()
  426. time.Sleep(100 * time.Millisecond)
  427. clus.Members[0].Restart(t)
  428. select {
  429. case <-time.After(5 * time.Second):
  430. t.Fatalf("timed out waiting for get")
  431. case <-donec:
  432. }
  433. }
  434. // TestKVPutFailGetRetry ensures a get will retry following a failed put.
  435. func TestKVPutFailGetRetry(t *testing.T) {
  436. defer testutil.AfterTest(t)
  437. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  438. defer clus.Terminate(t)
  439. kv := clientv3.NewKV(clus.Client(0))
  440. ctx := context.TODO()
  441. clus.Members[0].Stop(t)
  442. <-clus.Members[0].StopNotify()
  443. _, err := kv.Put(ctx, "foo", "bar")
  444. if err == nil {
  445. t.Fatalf("got success on disconnected put, wanted error")
  446. }
  447. donec := make(chan struct{})
  448. go func() {
  449. // Get will fail, but reconnect will trigger
  450. gresp, gerr := kv.Get(ctx, "foo")
  451. if gerr != nil {
  452. t.Fatal(gerr)
  453. }
  454. if len(gresp.Kvs) != 0 {
  455. t.Fatalf("bad get kvs: got %+v, want empty", gresp.Kvs)
  456. }
  457. donec <- struct{}{}
  458. }()
  459. time.Sleep(100 * time.Millisecond)
  460. clus.Members[0].Restart(t)
  461. select {
  462. case <-time.After(5 * time.Second):
  463. t.Fatalf("timed out waiting for get")
  464. case <-donec:
  465. }
  466. }
  467. // TestKVGetCancel tests that a context cancel on a Get terminates as expected.
  468. func TestKVGetCancel(t *testing.T) {
  469. defer testutil.AfterTest(t)
  470. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  471. defer clus.Terminate(t)
  472. oldconn := clus.Client(0).ActiveConnection()
  473. kv := clientv3.NewKV(clus.Client(0))
  474. ctx, cancel := context.WithCancel(context.TODO())
  475. cancel()
  476. resp, err := kv.Get(ctx, "abc")
  477. if err == nil {
  478. t.Fatalf("cancel on get response %v, expected context error", resp)
  479. }
  480. newconn := clus.Client(0).ActiveConnection()
  481. if oldconn != newconn {
  482. t.Fatalf("cancel on get broke client connection")
  483. }
  484. }
  485. // TestKVPutStoppedServerAndClose ensures closing after a failed Put works.
  486. func TestKVPutStoppedServerAndClose(t *testing.T) {
  487. t.Parallel()
  488. defer testutil.AfterTest(t)
  489. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  490. defer clus.Terminate(t)
  491. clus.Members[0].Stop(t)
  492. // this Put fails and triggers an asynchronous connection retry
  493. _, err := clus.Client(0).Put(context.TODO(), "abc", "123")
  494. if err == nil || !strings.Contains(err.Error(), "connection is closing") {
  495. t.Fatal(err)
  496. }
  497. // cluster will terminate and close the client with the retry in-flight
  498. }