kv_test.go 20 KB

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