kv_test.go 25 KB

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