kv_test.go 22 KB

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