kv_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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. "math/rand"
  18. "os"
  19. "reflect"
  20. "strings"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/clientv3"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  25. "github.com/coreos/etcd/integration"
  26. "github.com/coreos/etcd/mvcc/mvccpb"
  27. "github.com/coreos/etcd/pkg/testutil"
  28. "golang.org/x/net/context"
  29. "google.golang.org/grpc"
  30. )
  31. func TestKVPutError(t *testing.T) {
  32. defer testutil.AfterTest(t)
  33. var (
  34. maxReqBytes = 1.5 * 1024 * 1024 // hard coded max in v3_server.go
  35. quota = int64(int(maxReqBytes) + 8*os.Getpagesize())
  36. )
  37. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1, QuotaBackendBytes: quota})
  38. defer clus.Terminate(t)
  39. kv := clientv3.NewKV(clus.RandClient())
  40. ctx := context.TODO()
  41. _, err := kv.Put(ctx, "", "bar")
  42. if err != rpctypes.ErrEmptyKey {
  43. t.Fatalf("expected %v, got %v", rpctypes.ErrEmptyKey, err)
  44. }
  45. _, err = kv.Put(ctx, "key", strings.Repeat("a", int(maxReqBytes+100)))
  46. if err != rpctypes.ErrRequestTooLarge {
  47. t.Fatalf("expected %v, got %v", rpctypes.ErrRequestTooLarge, err)
  48. }
  49. _, err = kv.Put(ctx, "foo1", strings.Repeat("a", int(maxReqBytes-50)))
  50. if err != nil { // below quota
  51. t.Fatal(err)
  52. }
  53. time.Sleep(1 * time.Second) // give enough time for commit
  54. _, err = kv.Put(ctx, "foo2", strings.Repeat("a", int(maxReqBytes-50)))
  55. if err != rpctypes.ErrNoSpace { // over quota
  56. t.Fatalf("expected %v, got %v", rpctypes.ErrNoSpace, err)
  57. }
  58. }
  59. func TestKVPut(t *testing.T) {
  60. defer testutil.AfterTest(t)
  61. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  62. defer clus.Terminate(t)
  63. lapi := clientv3.NewLease(clus.RandClient())
  64. defer lapi.Close()
  65. kv := clientv3.NewKV(clus.RandClient())
  66. ctx := context.TODO()
  67. resp, err := lapi.Grant(context.Background(), 10)
  68. if err != nil {
  69. t.Fatalf("failed to create lease %v", err)
  70. }
  71. tests := []struct {
  72. key, val string
  73. leaseID clientv3.LeaseID
  74. }{
  75. {"foo", "bar", clientv3.NoLease},
  76. {"hello", "world", resp.ID},
  77. }
  78. for i, tt := range tests {
  79. if _, err := kv.Put(ctx, tt.key, tt.val, clientv3.WithLease(tt.leaseID)); err != nil {
  80. t.Fatalf("#%d: couldn't put %q (%v)", i, tt.key, err)
  81. }
  82. resp, err := kv.Get(ctx, tt.key)
  83. if err != nil {
  84. t.Fatalf("#%d: couldn't get key (%v)", i, err)
  85. }
  86. if len(resp.Kvs) != 1 {
  87. t.Fatalf("#%d: expected 1 key, got %d", i, len(resp.Kvs))
  88. }
  89. if !bytes.Equal([]byte(tt.val), resp.Kvs[0].Value) {
  90. t.Errorf("#%d: val = %s, want %s", i, tt.val, resp.Kvs[0].Value)
  91. }
  92. if tt.leaseID != clientv3.LeaseID(resp.Kvs[0].Lease) {
  93. t.Errorf("#%d: val = %d, want %d", i, tt.leaseID, resp.Kvs[0].Lease)
  94. }
  95. }
  96. }
  97. // TestKVPutWithIgnoreValue ensures that Put with WithIgnoreValue does not clobber the old value.
  98. func TestKVPutWithIgnoreValue(t *testing.T) {
  99. defer testutil.AfterTest(t)
  100. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  101. defer clus.Terminate(t)
  102. kv := clientv3.NewKV(clus.RandClient())
  103. _, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue())
  104. if err != rpctypes.ErrKeyNotFound {
  105. t.Fatalf("err expected %v, got %v", rpctypes.ErrKeyNotFound, err)
  106. }
  107. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  108. t.Fatal(err)
  109. }
  110. if _, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue()); err != nil {
  111. t.Fatal(err)
  112. }
  113. rr, rerr := kv.Get(context.TODO(), "foo")
  114. if rerr != nil {
  115. t.Fatal(rerr)
  116. }
  117. if len(rr.Kvs) != 1 {
  118. t.Fatalf("len(rr.Kvs) expected 1, got %d", len(rr.Kvs))
  119. }
  120. if !bytes.Equal(rr.Kvs[0].Value, []byte("bar")) {
  121. t.Fatalf("value expected 'bar', got %q", rr.Kvs[0].Value)
  122. }
  123. }
  124. func TestKVPutWithRequireLeader(t *testing.T) {
  125. defer testutil.AfterTest(t)
  126. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  127. defer clus.Terminate(t)
  128. clus.Members[1].Stop(t)
  129. clus.Members[2].Stop(t)
  130. // wait for election timeout, then member[0] will not have a leader.
  131. var (
  132. electionTicks = 10
  133. tickDuration = 10 * time.Millisecond
  134. )
  135. time.Sleep(time.Duration(3*electionTicks) * tickDuration)
  136. kv := clientv3.NewKV(clus.Client(0))
  137. _, err := kv.Put(clientv3.WithRequireLeader(context.Background()), "foo", "bar")
  138. if err != rpctypes.ErrNoLeader {
  139. t.Fatal(err)
  140. }
  141. // clients may give timeout errors since the members are stopped; take
  142. // the clients so that terminating the cluster won't complain
  143. clus.Client(1).Close()
  144. clus.Client(2).Close()
  145. clus.TakeClient(1)
  146. clus.TakeClient(2)
  147. }
  148. func TestKVRange(t *testing.T) {
  149. defer testutil.AfterTest(t)
  150. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  151. defer clus.Terminate(t)
  152. kv := clientv3.NewKV(clus.RandClient())
  153. ctx := context.TODO()
  154. keySet := []string{"a", "b", "c", "c", "c", "foo", "foo/abc", "fop"}
  155. for i, key := range keySet {
  156. if _, err := kv.Put(ctx, key, ""); err != nil {
  157. t.Fatalf("#%d: couldn't put %q (%v)", i, key, err)
  158. }
  159. }
  160. resp, err := kv.Get(ctx, keySet[0])
  161. if err != nil {
  162. t.Fatalf("couldn't get key (%v)", err)
  163. }
  164. wheader := resp.Header
  165. tests := []struct {
  166. begin, end string
  167. rev int64
  168. opts []clientv3.OpOption
  169. wantSet []*mvccpb.KeyValue
  170. }{
  171. // range first two
  172. {
  173. "a", "c",
  174. 0,
  175. nil,
  176. []*mvccpb.KeyValue{
  177. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  178. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  179. },
  180. },
  181. // range first two with serializable
  182. {
  183. "a", "c",
  184. 0,
  185. []clientv3.OpOption{clientv3.WithSerializable()},
  186. []*mvccpb.KeyValue{
  187. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  188. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  189. },
  190. },
  191. // range all with rev
  192. {
  193. "a", "x",
  194. 2,
  195. nil,
  196. []*mvccpb.KeyValue{
  197. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  198. },
  199. },
  200. // range all with countOnly
  201. {
  202. "a", "x",
  203. 2,
  204. []clientv3.OpOption{clientv3.WithCountOnly()},
  205. nil,
  206. },
  207. // range all with SortByKey, SortAscend
  208. {
  209. "a", "x",
  210. 0,
  211. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
  212. []*mvccpb.KeyValue{
  213. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  214. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  215. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  216. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  217. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  218. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  219. },
  220. },
  221. // range all with SortByKey, missing sorting order (ASCEND by default)
  222. {
  223. "a", "x",
  224. 0,
  225. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortNone)},
  226. []*mvccpb.KeyValue{
  227. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  228. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  229. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  230. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  231. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  232. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  233. },
  234. },
  235. // range all with SortByCreateRevision, SortDescend
  236. {
  237. "a", "x",
  238. 0,
  239. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortDescend)},
  240. []*mvccpb.KeyValue{
  241. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  242. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  243. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  244. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  245. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  246. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  247. },
  248. },
  249. // range all with SortByCreateRevision, missing sorting order (ASCEND by default)
  250. {
  251. "a", "x",
  252. 0,
  253. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortNone)},
  254. []*mvccpb.KeyValue{
  255. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  256. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  257. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  258. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  259. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  260. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  261. },
  262. },
  263. // range all with SortByModRevision, SortDescend
  264. {
  265. "a", "x",
  266. 0,
  267. []clientv3.OpOption{clientv3.WithSort(clientv3.SortByModRevision, clientv3.SortDescend)},
  268. []*mvccpb.KeyValue{
  269. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  270. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  271. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  272. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  273. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  274. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  275. },
  276. },
  277. // WithPrefix
  278. {
  279. "foo", "",
  280. 0,
  281. []clientv3.OpOption{clientv3.WithPrefix()},
  282. []*mvccpb.KeyValue{
  283. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  284. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  285. },
  286. },
  287. // WithFromKey
  288. {
  289. "fo", "",
  290. 0,
  291. []clientv3.OpOption{clientv3.WithFromKey()},
  292. []*mvccpb.KeyValue{
  293. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  294. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  295. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  296. },
  297. },
  298. }
  299. for i, tt := range tests {
  300. opts := []clientv3.OpOption{clientv3.WithRange(tt.end), clientv3.WithRev(tt.rev)}
  301. opts = append(opts, tt.opts...)
  302. resp, err := kv.Get(ctx, tt.begin, opts...)
  303. if err != nil {
  304. t.Fatalf("#%d: couldn't range (%v)", i, err)
  305. }
  306. if !reflect.DeepEqual(wheader, resp.Header) {
  307. t.Fatalf("#%d: wheader expected %+v, got %+v", i, wheader, resp.Header)
  308. }
  309. if !reflect.DeepEqual(tt.wantSet, resp.Kvs) {
  310. t.Fatalf("#%d: resp.Kvs expected %+v, got %+v", i, tt.wantSet, resp.Kvs)
  311. }
  312. }
  313. }
  314. func TestKVGetErrConnClosed(t *testing.T) {
  315. defer testutil.AfterTest(t)
  316. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  317. defer clus.Terminate(t)
  318. cli := clus.Client(0)
  319. kv := clientv3.NewKV(cli)
  320. donec := make(chan struct{})
  321. go func() {
  322. defer close(donec)
  323. _, err := kv.Get(context.TODO(), "foo")
  324. if err != nil && err != grpc.ErrClientConnClosing {
  325. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
  326. }
  327. }()
  328. if err := cli.Close(); err != nil {
  329. t.Fatal(err)
  330. }
  331. clus.TakeClient(0)
  332. select {
  333. case <-time.After(3 * time.Second):
  334. t.Fatal("kv.Get took too long")
  335. case <-donec:
  336. }
  337. }
  338. func TestKVNewAfterClose(t *testing.T) {
  339. defer testutil.AfterTest(t)
  340. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  341. defer clus.Terminate(t)
  342. cli := clus.Client(0)
  343. clus.TakeClient(0)
  344. if err := cli.Close(); err != nil {
  345. t.Fatal(err)
  346. }
  347. donec := make(chan struct{})
  348. go func() {
  349. kv := clientv3.NewKV(cli)
  350. if _, err := kv.Get(context.TODO(), "foo"); err != grpc.ErrClientConnClosing {
  351. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
  352. }
  353. close(donec)
  354. }()
  355. select {
  356. case <-time.After(3 * time.Second):
  357. t.Fatal("kv.Get took too long")
  358. case <-donec:
  359. }
  360. }
  361. func TestKVDeleteRange(t *testing.T) {
  362. defer testutil.AfterTest(t)
  363. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  364. defer clus.Terminate(t)
  365. kv := clientv3.NewKV(clus.RandClient())
  366. ctx := context.TODO()
  367. tests := []struct {
  368. key string
  369. opts []clientv3.OpOption
  370. wkeys []string
  371. }{
  372. // [a, c)
  373. {
  374. key: "a",
  375. opts: []clientv3.OpOption{clientv3.WithRange("c")},
  376. wkeys: []string{"c", "c/abc", "d"},
  377. },
  378. // >= c
  379. {
  380. key: "c",
  381. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  382. wkeys: []string{"a", "b"},
  383. },
  384. // c*
  385. {
  386. key: "c",
  387. opts: []clientv3.OpOption{clientv3.WithPrefix()},
  388. wkeys: []string{"a", "b", "d"},
  389. },
  390. // *
  391. {
  392. key: "\x00",
  393. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  394. wkeys: []string{},
  395. },
  396. }
  397. for i, tt := range tests {
  398. keySet := []string{"a", "b", "c", "c/abc", "d"}
  399. for j, key := range keySet {
  400. if _, err := kv.Put(ctx, key, ""); err != nil {
  401. t.Fatalf("#%d: couldn't put %q (%v)", j, key, err)
  402. }
  403. }
  404. _, err := kv.Delete(ctx, tt.key, tt.opts...)
  405. if err != nil {
  406. t.Fatalf("#%d: couldn't delete range (%v)", i, err)
  407. }
  408. resp, err := kv.Get(ctx, "a", clientv3.WithFromKey())
  409. if err != nil {
  410. t.Fatalf("#%d: couldn't get keys (%v)", i, err)
  411. }
  412. keys := []string{}
  413. for _, kv := range resp.Kvs {
  414. keys = append(keys, string(kv.Key))
  415. }
  416. if !reflect.DeepEqual(tt.wkeys, keys) {
  417. t.Errorf("#%d: resp.Kvs got %v, expected %v", i, keys, tt.wkeys)
  418. }
  419. }
  420. }
  421. func TestKVDelete(t *testing.T) {
  422. defer testutil.AfterTest(t)
  423. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  424. defer clus.Terminate(t)
  425. kv := clientv3.NewKV(clus.RandClient())
  426. ctx := context.TODO()
  427. presp, err := kv.Put(ctx, "foo", "")
  428. if err != nil {
  429. t.Fatalf("couldn't put 'foo' (%v)", err)
  430. }
  431. if presp.Header.Revision != 2 {
  432. t.Fatalf("presp.Header.Revision got %d, want %d", presp.Header.Revision, 2)
  433. }
  434. resp, err := kv.Delete(ctx, "foo")
  435. if err != nil {
  436. t.Fatalf("couldn't delete key (%v)", err)
  437. }
  438. if resp.Header.Revision != 3 {
  439. t.Fatalf("resp.Header.Revision got %d, want %d", resp.Header.Revision, 3)
  440. }
  441. gresp, err := kv.Get(ctx, "foo")
  442. if err != nil {
  443. t.Fatalf("couldn't get key (%v)", err)
  444. }
  445. if len(gresp.Kvs) > 0 {
  446. t.Fatalf("gresp.Kvs got %+v, want none", gresp.Kvs)
  447. }
  448. }
  449. func TestKVCompactError(t *testing.T) {
  450. defer testutil.AfterTest(t)
  451. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  452. defer clus.Terminate(t)
  453. kv := clientv3.NewKV(clus.RandClient())
  454. ctx := context.TODO()
  455. for i := 0; i < 5; i++ {
  456. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  457. t.Fatalf("couldn't put 'foo' (%v)", err)
  458. }
  459. }
  460. _, err := kv.Compact(ctx, 6)
  461. if err != nil {
  462. t.Fatalf("couldn't compact 6 (%v)", err)
  463. }
  464. _, err = kv.Compact(ctx, 6)
  465. if err != rpctypes.ErrCompacted {
  466. t.Fatalf("expected %v, got %v", rpctypes.ErrCompacted, err)
  467. }
  468. _, err = kv.Compact(ctx, 100)
  469. if err != rpctypes.ErrFutureRev {
  470. t.Fatalf("expected %v, got %v", rpctypes.ErrFutureRev, err)
  471. }
  472. }
  473. func TestKVCompact(t *testing.T) {
  474. defer testutil.AfterTest(t)
  475. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  476. defer clus.Terminate(t)
  477. kv := clientv3.NewKV(clus.RandClient())
  478. ctx := context.TODO()
  479. for i := 0; i < 10; i++ {
  480. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  481. t.Fatalf("couldn't put 'foo' (%v)", err)
  482. }
  483. }
  484. _, err := kv.Compact(ctx, 7)
  485. if err != nil {
  486. t.Fatalf("couldn't compact kv space (%v)", err)
  487. }
  488. _, err = kv.Compact(ctx, 7)
  489. if err == nil || err != rpctypes.ErrCompacted {
  490. t.Fatalf("error got %v, want %v", err, rpctypes.ErrCompacted)
  491. }
  492. wcli := clus.RandClient()
  493. // new watcher could precede receiving the compaction without quorum first
  494. wcli.Get(ctx, "quorum-get")
  495. wc := clientv3.NewWatcher(wcli)
  496. defer wc.Close()
  497. wchan := wc.Watch(ctx, "foo", clientv3.WithRev(3))
  498. if wr := <-wchan; wr.CompactRevision != 7 {
  499. t.Fatalf("wchan CompactRevision got %v, want 7", wr.CompactRevision)
  500. }
  501. if wr, ok := <-wchan; ok {
  502. t.Fatalf("wchan got %v, expected closed", wr)
  503. }
  504. _, err = kv.Compact(ctx, 1000)
  505. if err == nil || err != rpctypes.ErrFutureRev {
  506. t.Fatalf("error got %v, want %v", err, rpctypes.ErrFutureRev)
  507. }
  508. }
  509. // TestKVGetRetry ensures get will retry on disconnect.
  510. func TestKVGetRetry(t *testing.T) {
  511. defer testutil.AfterTest(t)
  512. clusterSize := 3
  513. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: clusterSize})
  514. defer clus.Terminate(t)
  515. // because killing leader and following election
  516. // could give no other endpoints for client reconnection
  517. fIdx := (clus.WaitLeader(t) + 1) % clusterSize
  518. kv := clientv3.NewKV(clus.Client(fIdx))
  519. ctx := context.TODO()
  520. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  521. t.Fatal(err)
  522. }
  523. clus.Members[fIdx].Stop(t)
  524. donec := make(chan struct{})
  525. go func() {
  526. // Get will fail, but reconnect will trigger
  527. gresp, gerr := kv.Get(ctx, "foo")
  528. if gerr != nil {
  529. t.Fatal(gerr)
  530. }
  531. wkvs := []*mvccpb.KeyValue{
  532. {
  533. Key: []byte("foo"),
  534. Value: []byte("bar"),
  535. CreateRevision: 2,
  536. ModRevision: 2,
  537. Version: 1,
  538. },
  539. }
  540. if !reflect.DeepEqual(gresp.Kvs, wkvs) {
  541. t.Fatalf("bad get: got %v, want %v", gresp.Kvs, wkvs)
  542. }
  543. donec <- struct{}{}
  544. }()
  545. time.Sleep(100 * time.Millisecond)
  546. clus.Members[fIdx].Restart(t)
  547. select {
  548. case <-time.After(5 * time.Second):
  549. t.Fatalf("timed out waiting for get")
  550. case <-donec:
  551. }
  552. }
  553. // TestKVPutFailGetRetry ensures a get will retry following a failed put.
  554. func TestKVPutFailGetRetry(t *testing.T) {
  555. defer testutil.AfterTest(t)
  556. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  557. defer clus.Terminate(t)
  558. kv := clientv3.NewKV(clus.Client(0))
  559. clus.Members[0].Stop(t)
  560. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  561. defer cancel()
  562. _, err := kv.Put(ctx, "foo", "bar")
  563. if err == nil {
  564. t.Fatalf("got success on disconnected put, wanted error")
  565. }
  566. donec := make(chan struct{})
  567. go func() {
  568. // Get will fail, but reconnect will trigger
  569. gresp, gerr := kv.Get(context.TODO(), "foo")
  570. if gerr != nil {
  571. t.Fatal(gerr)
  572. }
  573. if len(gresp.Kvs) != 0 {
  574. t.Fatalf("bad get kvs: got %+v, want empty", gresp.Kvs)
  575. }
  576. donec <- struct{}{}
  577. }()
  578. time.Sleep(100 * time.Millisecond)
  579. clus.Members[0].Restart(t)
  580. select {
  581. case <-time.After(5 * time.Second):
  582. t.Fatalf("timed out waiting for get")
  583. case <-donec:
  584. }
  585. }
  586. // TestKVGetCancel tests that a context cancel on a Get terminates as expected.
  587. func TestKVGetCancel(t *testing.T) {
  588. defer testutil.AfterTest(t)
  589. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  590. defer clus.Terminate(t)
  591. oldconn := clus.Client(0).ActiveConnection()
  592. kv := clientv3.NewKV(clus.Client(0))
  593. ctx, cancel := context.WithCancel(context.TODO())
  594. cancel()
  595. resp, err := kv.Get(ctx, "abc")
  596. if err == nil {
  597. t.Fatalf("cancel on get response %v, expected context error", resp)
  598. }
  599. newconn := clus.Client(0).ActiveConnection()
  600. if oldconn != newconn {
  601. t.Fatalf("cancel on get broke client connection")
  602. }
  603. }
  604. // TestKVGetStoppedServerAndClose ensures closing after a failed Get works.
  605. func TestKVGetStoppedServerAndClose(t *testing.T) {
  606. defer testutil.AfterTest(t)
  607. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  608. defer clus.Terminate(t)
  609. cli := clus.Client(0)
  610. clus.Members[0].Stop(t)
  611. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  612. // this Get fails and triggers an asynchronous connection retry
  613. _, err := cli.Get(ctx, "abc")
  614. cancel()
  615. if !strings.Contains(err.Error(), "context deadline") {
  616. t.Fatal(err)
  617. }
  618. }
  619. // TestKVPutStoppedServerAndClose ensures closing after a failed Put works.
  620. func TestKVPutStoppedServerAndClose(t *testing.T) {
  621. defer testutil.AfterTest(t)
  622. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  623. defer clus.Terminate(t)
  624. cli := clus.Client(0)
  625. clus.Members[0].Stop(t)
  626. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  627. // get retries on all errors.
  628. // so here we use it to eat the potential broken pipe error for the next put.
  629. // grpc client might see a broken pipe error when we issue the get request before
  630. // grpc finds out the original connection is down due to the member shutdown.
  631. _, err := cli.Get(ctx, "abc")
  632. cancel()
  633. if !strings.Contains(err.Error(), "context deadline") {
  634. t.Fatal(err)
  635. }
  636. // this Put fails and triggers an asynchronous connection retry
  637. _, err = cli.Put(ctx, "abc", "123")
  638. cancel()
  639. if !strings.Contains(err.Error(), "context deadline") {
  640. t.Fatal(err)
  641. }
  642. }
  643. // TestKVGetOneEndpointDown ensures a client can connect and get if one endpoint is down
  644. func TestKVPutOneEndpointDown(t *testing.T) {
  645. defer testutil.AfterTest(t)
  646. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  647. defer clus.Terminate(t)
  648. // get endpoint list
  649. eps := make([]string, 3)
  650. for i := range eps {
  651. eps[i] = clus.Members[i].GRPCAddr()
  652. }
  653. // make a dead node
  654. clus.Members[rand.Intn(len(eps))].Stop(t)
  655. // try to connect with dead node in the endpoint list
  656. cfg := clientv3.Config{Endpoints: eps, DialTimeout: 1 * time.Second}
  657. cli, err := clientv3.New(cfg)
  658. if err != nil {
  659. t.Fatal(err)
  660. }
  661. defer cli.Close()
  662. ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second)
  663. if _, err := cli.Get(ctx, "abc", clientv3.WithSerializable()); err != nil {
  664. t.Fatal(err)
  665. }
  666. cancel()
  667. }
  668. // TestKVGetResetLoneEndpoint ensures that if an endpoint resets and all other
  669. // endpoints are down, then it will reconnect.
  670. func TestKVGetResetLoneEndpoint(t *testing.T) {
  671. defer testutil.AfterTest(t)
  672. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 2})
  673. defer clus.Terminate(t)
  674. // get endpoint list
  675. eps := make([]string, 2)
  676. for i := range eps {
  677. eps[i] = clus.Members[i].GRPCAddr()
  678. }
  679. cfg := clientv3.Config{Endpoints: eps, DialTimeout: 500 * time.Millisecond}
  680. cli, err := clientv3.New(cfg)
  681. if err != nil {
  682. t.Fatal(err)
  683. }
  684. defer cli.Close()
  685. // disconnect everything
  686. clus.Members[0].Stop(t)
  687. clus.Members[1].Stop(t)
  688. // have Get try to reconnect
  689. donec := make(chan struct{})
  690. go func() {
  691. ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  692. if _, err := cli.Get(ctx, "abc", clientv3.WithSerializable()); err != nil {
  693. t.Fatal(err)
  694. }
  695. cancel()
  696. close(donec)
  697. }()
  698. time.Sleep(500 * time.Millisecond)
  699. clus.Members[0].Restart(t)
  700. select {
  701. case <-time.After(10 * time.Second):
  702. t.Fatalf("timed out waiting for Get")
  703. case <-donec:
  704. }
  705. }