kv_test.go 27 KB

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