kv_test.go 19 KB

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