kv_test.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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/v3/clientv3"
  24. "go.etcd.io/etcd/v3/etcdserver/api/v3rpc/rpctypes"
  25. "go.etcd.io/etcd/v3/integration"
  26. "go.etcd.io/etcd/v3/mvcc/mvccpb"
  27. "go.etcd.io/etcd/v3/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. // fetch keyspace with empty key using WithFromKey
  357. {
  358. "", "",
  359. 0,
  360. []clientv3.OpOption{clientv3.WithFromKey(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},
  361. []*mvccpb.KeyValue{
  362. {Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
  363. {Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
  364. {Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
  365. {Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
  366. {Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
  367. {Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
  368. },
  369. },
  370. }
  371. for i, tt := range tests {
  372. opts := []clientv3.OpOption{clientv3.WithRange(tt.end), clientv3.WithRev(tt.rev)}
  373. opts = append(opts, tt.opts...)
  374. resp, err := kv.Get(ctx, tt.begin, opts...)
  375. if err != nil {
  376. t.Fatalf("#%d: couldn't range (%v)", i, err)
  377. }
  378. if !reflect.DeepEqual(wheader, resp.Header) {
  379. t.Fatalf("#%d: wheader expected %+v, got %+v", i, wheader, resp.Header)
  380. }
  381. if !reflect.DeepEqual(tt.wantSet, resp.Kvs) {
  382. t.Fatalf("#%d: resp.Kvs expected %+v, got %+v", i, tt.wantSet, resp.Kvs)
  383. }
  384. }
  385. }
  386. func TestKVGetErrConnClosed(t *testing.T) {
  387. defer testutil.AfterTest(t)
  388. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  389. defer clus.Terminate(t)
  390. cli := clus.Client(0)
  391. donec := make(chan struct{})
  392. if err := cli.Close(); err != nil {
  393. t.Fatal(err)
  394. }
  395. clus.TakeClient(0)
  396. go func() {
  397. defer close(donec)
  398. _, err := cli.Get(context.TODO(), "foo")
  399. if !clientv3.IsConnCanceled(err) {
  400. t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
  401. }
  402. }()
  403. select {
  404. case <-time.After(integration.RequestWaitTimeout):
  405. t.Fatal("kv.Get took too long")
  406. case <-donec:
  407. }
  408. }
  409. func TestKVNewAfterClose(t *testing.T) {
  410. defer testutil.AfterTest(t)
  411. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  412. defer clus.Terminate(t)
  413. cli := clus.Client(0)
  414. clus.TakeClient(0)
  415. if err := cli.Close(); err != nil {
  416. t.Fatal(err)
  417. }
  418. donec := make(chan struct{})
  419. go func() {
  420. _, err := cli.Get(context.TODO(), "foo")
  421. if !clientv3.IsConnCanceled(err) {
  422. t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
  423. }
  424. close(donec)
  425. }()
  426. select {
  427. case <-time.After(integration.RequestWaitTimeout):
  428. t.Fatal("kv.Get took too long")
  429. case <-donec:
  430. }
  431. }
  432. func TestKVDeleteRange(t *testing.T) {
  433. defer testutil.AfterTest(t)
  434. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  435. defer clus.Terminate(t)
  436. kv := clus.RandClient()
  437. ctx := context.TODO()
  438. tests := []struct {
  439. key string
  440. opts []clientv3.OpOption
  441. wkeys []string
  442. }{
  443. // [a, c)
  444. {
  445. key: "a",
  446. opts: []clientv3.OpOption{clientv3.WithRange("c")},
  447. wkeys: []string{"c", "c/abc", "d"},
  448. },
  449. // >= c
  450. {
  451. key: "c",
  452. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  453. wkeys: []string{"a", "b"},
  454. },
  455. // c*
  456. {
  457. key: "c",
  458. opts: []clientv3.OpOption{clientv3.WithPrefix()},
  459. wkeys: []string{"a", "b", "d"},
  460. },
  461. // *
  462. {
  463. key: "\x00",
  464. opts: []clientv3.OpOption{clientv3.WithFromKey()},
  465. wkeys: []string{},
  466. },
  467. }
  468. for i, tt := range tests {
  469. keySet := []string{"a", "b", "c", "c/abc", "d"}
  470. for j, key := range keySet {
  471. if _, err := kv.Put(ctx, key, ""); err != nil {
  472. t.Fatalf("#%d: couldn't put %q (%v)", j, key, err)
  473. }
  474. }
  475. _, err := kv.Delete(ctx, tt.key, tt.opts...)
  476. if err != nil {
  477. t.Fatalf("#%d: couldn't delete range (%v)", i, err)
  478. }
  479. resp, err := kv.Get(ctx, "a", clientv3.WithFromKey())
  480. if err != nil {
  481. t.Fatalf("#%d: couldn't get keys (%v)", i, err)
  482. }
  483. keys := []string{}
  484. for _, kv := range resp.Kvs {
  485. keys = append(keys, string(kv.Key))
  486. }
  487. if !reflect.DeepEqual(tt.wkeys, keys) {
  488. t.Errorf("#%d: resp.Kvs got %v, expected %v", i, keys, tt.wkeys)
  489. }
  490. }
  491. }
  492. func TestKVDelete(t *testing.T) {
  493. defer testutil.AfterTest(t)
  494. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  495. defer clus.Terminate(t)
  496. kv := clus.RandClient()
  497. ctx := context.TODO()
  498. presp, err := kv.Put(ctx, "foo", "")
  499. if err != nil {
  500. t.Fatalf("couldn't put 'foo' (%v)", err)
  501. }
  502. if presp.Header.Revision != 2 {
  503. t.Fatalf("presp.Header.Revision got %d, want %d", presp.Header.Revision, 2)
  504. }
  505. resp, err := kv.Delete(ctx, "foo")
  506. if err != nil {
  507. t.Fatalf("couldn't delete key (%v)", err)
  508. }
  509. if resp.Header.Revision != 3 {
  510. t.Fatalf("resp.Header.Revision got %d, want %d", resp.Header.Revision, 3)
  511. }
  512. gresp, err := kv.Get(ctx, "foo")
  513. if err != nil {
  514. t.Fatalf("couldn't get key (%v)", err)
  515. }
  516. if len(gresp.Kvs) > 0 {
  517. t.Fatalf("gresp.Kvs got %+v, want none", gresp.Kvs)
  518. }
  519. }
  520. func TestKVCompactError(t *testing.T) {
  521. defer testutil.AfterTest(t)
  522. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  523. defer clus.Terminate(t)
  524. kv := clus.RandClient()
  525. ctx := context.TODO()
  526. for i := 0; i < 5; i++ {
  527. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  528. t.Fatalf("couldn't put 'foo' (%v)", err)
  529. }
  530. }
  531. _, err := kv.Compact(ctx, 6)
  532. if err != nil {
  533. t.Fatalf("couldn't compact 6 (%v)", err)
  534. }
  535. _, err = kv.Compact(ctx, 6)
  536. if err != rpctypes.ErrCompacted {
  537. t.Fatalf("expected %v, got %v", rpctypes.ErrCompacted, err)
  538. }
  539. _, err = kv.Compact(ctx, 100)
  540. if err != rpctypes.ErrFutureRev {
  541. t.Fatalf("expected %v, got %v", rpctypes.ErrFutureRev, err)
  542. }
  543. }
  544. func TestKVCompact(t *testing.T) {
  545. defer testutil.AfterTest(t)
  546. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  547. defer clus.Terminate(t)
  548. kv := clus.RandClient()
  549. ctx := context.TODO()
  550. for i := 0; i < 10; i++ {
  551. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  552. t.Fatalf("couldn't put 'foo' (%v)", err)
  553. }
  554. }
  555. _, err := kv.Compact(ctx, 7)
  556. if err != nil {
  557. t.Fatalf("couldn't compact kv space (%v)", err)
  558. }
  559. _, err = kv.Compact(ctx, 7)
  560. if err == nil || err != rpctypes.ErrCompacted {
  561. t.Fatalf("error got %v, want %v", err, rpctypes.ErrCompacted)
  562. }
  563. wcli := clus.RandClient()
  564. // new watcher could precede receiving the compaction without quorum first
  565. wcli.Get(ctx, "quorum-get")
  566. wchan := wcli.Watch(ctx, "foo", clientv3.WithRev(3))
  567. if wr := <-wchan; wr.CompactRevision != 7 {
  568. t.Fatalf("wchan CompactRevision got %v, want 7", wr.CompactRevision)
  569. }
  570. if wr, ok := <-wchan; ok {
  571. t.Fatalf("wchan got %v, expected closed", wr)
  572. }
  573. _, err = kv.Compact(ctx, 1000)
  574. if err == nil || err != rpctypes.ErrFutureRev {
  575. t.Fatalf("error got %v, want %v", err, rpctypes.ErrFutureRev)
  576. }
  577. }
  578. // TestKVGetRetry ensures get will retry on disconnect.
  579. func TestKVGetRetry(t *testing.T) {
  580. defer testutil.AfterTest(t)
  581. clusterSize := 3
  582. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: clusterSize})
  583. defer clus.Terminate(t)
  584. // because killing leader and following election
  585. // could give no other endpoints for client reconnection
  586. fIdx := (clus.WaitLeader(t) + 1) % clusterSize
  587. kv := clus.Client(fIdx)
  588. ctx := context.TODO()
  589. if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
  590. t.Fatal(err)
  591. }
  592. clus.Members[fIdx].Stop(t)
  593. donec := make(chan struct{})
  594. go func() {
  595. // Get will fail, but reconnect will trigger
  596. gresp, gerr := kv.Get(ctx, "foo")
  597. if gerr != nil {
  598. t.Fatal(gerr)
  599. }
  600. wkvs := []*mvccpb.KeyValue{
  601. {
  602. Key: []byte("foo"),
  603. Value: []byte("bar"),
  604. CreateRevision: 2,
  605. ModRevision: 2,
  606. Version: 1,
  607. },
  608. }
  609. if !reflect.DeepEqual(gresp.Kvs, wkvs) {
  610. t.Fatalf("bad get: got %v, want %v", gresp.Kvs, wkvs)
  611. }
  612. donec <- struct{}{}
  613. }()
  614. time.Sleep(100 * time.Millisecond)
  615. clus.Members[fIdx].Restart(t)
  616. clus.Members[fIdx].WaitOK(t)
  617. select {
  618. case <-time.After(20 * time.Second):
  619. t.Fatalf("timed out waiting for get")
  620. case <-donec:
  621. }
  622. }
  623. // TestKVPutFailGetRetry ensures a get will retry following a failed put.
  624. func TestKVPutFailGetRetry(t *testing.T) {
  625. defer testutil.AfterTest(t)
  626. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  627. defer clus.Terminate(t)
  628. kv := clus.Client(0)
  629. clus.Members[0].Stop(t)
  630. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  631. defer cancel()
  632. _, err := kv.Put(ctx, "foo", "bar")
  633. if err == nil {
  634. t.Fatalf("got success on disconnected put, wanted error")
  635. }
  636. donec := make(chan struct{})
  637. go func() {
  638. // Get will fail, but reconnect will trigger
  639. gresp, gerr := kv.Get(context.TODO(), "foo")
  640. if gerr != nil {
  641. t.Fatal(gerr)
  642. }
  643. if len(gresp.Kvs) != 0 {
  644. t.Fatalf("bad get kvs: got %+v, want empty", gresp.Kvs)
  645. }
  646. donec <- struct{}{}
  647. }()
  648. time.Sleep(100 * time.Millisecond)
  649. clus.Members[0].Restart(t)
  650. select {
  651. case <-time.After(20 * time.Second):
  652. t.Fatalf("timed out waiting for get")
  653. case <-donec:
  654. }
  655. }
  656. // TestKVGetCancel tests that a context cancel on a Get terminates as expected.
  657. func TestKVGetCancel(t *testing.T) {
  658. defer testutil.AfterTest(t)
  659. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  660. defer clus.Terminate(t)
  661. oldconn := clus.Client(0).ActiveConnection()
  662. kv := clus.Client(0)
  663. ctx, cancel := context.WithCancel(context.TODO())
  664. cancel()
  665. resp, err := kv.Get(ctx, "abc")
  666. if err == nil {
  667. t.Fatalf("cancel on get response %v, expected context error", resp)
  668. }
  669. newconn := clus.Client(0).ActiveConnection()
  670. if oldconn != newconn {
  671. t.Fatalf("cancel on get broke client connection")
  672. }
  673. }
  674. // TestKVGetStoppedServerAndClose ensures closing after a failed Get works.
  675. func TestKVGetStoppedServerAndClose(t *testing.T) {
  676. defer testutil.AfterTest(t)
  677. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  678. defer clus.Terminate(t)
  679. cli := clus.Client(0)
  680. clus.Members[0].Stop(t)
  681. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  682. // this Get fails and triggers an asynchronous connection retry
  683. _, err := cli.Get(ctx, "abc")
  684. cancel()
  685. if err != nil && !(isCanceled(err) || isClientTimeout(err)) {
  686. t.Fatal(err)
  687. }
  688. }
  689. // TestKVPutStoppedServerAndClose ensures closing after a failed Put works.
  690. func TestKVPutStoppedServerAndClose(t *testing.T) {
  691. defer testutil.AfterTest(t)
  692. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  693. defer clus.Terminate(t)
  694. cli := clus.Client(0)
  695. clus.Members[0].Stop(t)
  696. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  697. // get retries on all errors.
  698. // so here we use it to eat the potential broken pipe error for the next put.
  699. // grpc client might see a broken pipe error when we issue the get request before
  700. // grpc finds out the original connection is down due to the member shutdown.
  701. _, err := cli.Get(ctx, "abc")
  702. cancel()
  703. if err != nil && !(isCanceled(err) || isClientTimeout(err)) {
  704. t.Fatal(err)
  705. }
  706. ctx, cancel = context.WithTimeout(context.TODO(), time.Second)
  707. // this Put fails and triggers an asynchronous connection retry
  708. _, err = cli.Put(ctx, "abc", "123")
  709. cancel()
  710. if err != nil && !(isCanceled(err) || isClientTimeout(err) || isUnavailable(err)) {
  711. t.Fatal(err)
  712. }
  713. }
  714. // TestKVPutAtMostOnce ensures that a Put will only occur at most once
  715. // in the presence of network errors.
  716. func TestKVPutAtMostOnce(t *testing.T) {
  717. defer testutil.AfterTest(t)
  718. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  719. defer clus.Terminate(t)
  720. if _, err := clus.Client(0).Put(context.TODO(), "k", "1"); err != nil {
  721. t.Fatal(err)
  722. }
  723. for i := 0; i < 10; i++ {
  724. clus.Members[0].DropConnections()
  725. donec := make(chan struct{})
  726. go func() {
  727. defer close(donec)
  728. for i := 0; i < 10; i++ {
  729. clus.Members[0].DropConnections()
  730. time.Sleep(5 * time.Millisecond)
  731. }
  732. }()
  733. _, err := clus.Client(0).Put(context.TODO(), "k", "v")
  734. <-donec
  735. if err != nil {
  736. break
  737. }
  738. }
  739. resp, err := clus.Client(0).Get(context.TODO(), "k")
  740. if err != nil {
  741. t.Fatal(err)
  742. }
  743. if resp.Kvs[0].Version > 11 {
  744. t.Fatalf("expected version <= 10, got %+v", resp.Kvs[0])
  745. }
  746. }
  747. // TestKVLargeRequests tests various client/server side request limits.
  748. func TestKVLargeRequests(t *testing.T) {
  749. defer testutil.AfterTest(t)
  750. tests := []struct {
  751. // make sure that "MaxCallSendMsgSize" < server-side default send/recv limit
  752. maxRequestBytesServer uint
  753. maxCallSendBytesClient int
  754. maxCallRecvBytesClient int
  755. valueSize int
  756. expectError error
  757. }{
  758. {
  759. maxRequestBytesServer: 1,
  760. maxCallSendBytesClient: 0,
  761. maxCallRecvBytesClient: 0,
  762. valueSize: 1024,
  763. expectError: rpctypes.ErrRequestTooLarge,
  764. },
  765. // without proper client-side receive size limit
  766. // "code = ResourceExhausted desc = grpc: received message larger than max (5242929 vs. 4194304)"
  767. {
  768. maxRequestBytesServer: 7*1024*1024 + 512*1024,
  769. maxCallSendBytesClient: 7 * 1024 * 1024,
  770. maxCallRecvBytesClient: 0,
  771. valueSize: 5 * 1024 * 1024,
  772. expectError: nil,
  773. },
  774. {
  775. maxRequestBytesServer: 10 * 1024 * 1024,
  776. maxCallSendBytesClient: 100 * 1024 * 1024,
  777. maxCallRecvBytesClient: 0,
  778. valueSize: 10 * 1024 * 1024,
  779. expectError: rpctypes.ErrRequestTooLarge,
  780. },
  781. {
  782. maxRequestBytesServer: 10 * 1024 * 1024,
  783. maxCallSendBytesClient: 10 * 1024 * 1024,
  784. maxCallRecvBytesClient: 0,
  785. valueSize: 10 * 1024 * 1024,
  786. expectError: grpc.Errorf(codes.ResourceExhausted, "trying to send message larger than max "),
  787. },
  788. {
  789. maxRequestBytesServer: 10 * 1024 * 1024,
  790. maxCallSendBytesClient: 100 * 1024 * 1024,
  791. maxCallRecvBytesClient: 0,
  792. valueSize: 10*1024*1024 + 5,
  793. expectError: rpctypes.ErrRequestTooLarge,
  794. },
  795. {
  796. maxRequestBytesServer: 10 * 1024 * 1024,
  797. maxCallSendBytesClient: 10 * 1024 * 1024,
  798. maxCallRecvBytesClient: 0,
  799. valueSize: 10*1024*1024 + 5,
  800. expectError: grpc.Errorf(codes.ResourceExhausted, "trying to send message larger than max "),
  801. },
  802. }
  803. for i, test := range tests {
  804. clus := integration.NewClusterV3(t,
  805. &integration.ClusterConfig{
  806. Size: 1,
  807. MaxRequestBytes: test.maxRequestBytesServer,
  808. ClientMaxCallSendMsgSize: test.maxCallSendBytesClient,
  809. ClientMaxCallRecvMsgSize: test.maxCallRecvBytesClient,
  810. },
  811. )
  812. cli := clus.Client(0)
  813. _, err := cli.Put(context.TODO(), "foo", strings.Repeat("a", test.valueSize))
  814. if _, ok := err.(rpctypes.EtcdError); ok {
  815. if err != test.expectError {
  816. t.Errorf("#%d: expected %v, got %v", i, test.expectError, err)
  817. }
  818. } else if err != nil && !strings.HasPrefix(err.Error(), test.expectError.Error()) {
  819. t.Errorf("#%d: expected error starting with '%s', got '%s'", i, test.expectError.Error(), err.Error())
  820. }
  821. // put request went through, now expects large response back
  822. if err == nil {
  823. _, err = cli.Get(context.TODO(), "foo")
  824. if err != nil {
  825. t.Errorf("#%d: get expected no error, got %v", i, err)
  826. }
  827. }
  828. clus.Terminate(t)
  829. }
  830. }
  831. // TestKVForLearner ensures learner member only accepts serializable read request.
  832. func TestKVForLearner(t *testing.T) {
  833. defer testutil.AfterTest(t)
  834. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  835. defer clus.Terminate(t)
  836. // we have to add and launch learner member after initial cluster was created, because
  837. // bootstrapping a cluster with learner member is not supported.
  838. clus.AddAndLaunchLearnerMember(t)
  839. learners, err := clus.GetLearnerMembers()
  840. if err != nil {
  841. t.Fatalf("failed to get the learner members in cluster: %v", err)
  842. }
  843. if len(learners) != 1 {
  844. t.Fatalf("added 1 learner to cluster, got %d", len(learners))
  845. }
  846. if len(clus.Members) != 4 {
  847. t.Fatalf("expecting 4 members in cluster after adding the learner member, got %d", len(clus.Members))
  848. }
  849. // note:
  850. // 1. clus.Members[3] is the newly added learner member, which was appended to clus.Members
  851. // 2. we are using member's grpcAddr instead of clientURLs as the endpoint for clientv3.Config,
  852. // because the implementation of integration test has diverged from embed/etcd.go.
  853. learnerEp := clus.Members[3].GRPCAddr()
  854. cfg := clientv3.Config{
  855. Endpoints: []string{learnerEp},
  856. DialTimeout: 5 * time.Second,
  857. DialOptions: []grpc.DialOption{grpc.WithBlock()},
  858. }
  859. // this client only has endpoint of the learner member
  860. cli, err := clientv3.New(cfg)
  861. if err != nil {
  862. t.Fatalf("failed to create clientv3: %v", err)
  863. }
  864. defer cli.Close()
  865. // waiting for learner member to catch up applying the config change entries in raft log.
  866. time.Sleep(3 * time.Second)
  867. tests := []struct {
  868. op clientv3.Op
  869. wErr bool
  870. }{
  871. {
  872. op: clientv3.OpGet("foo", clientv3.WithSerializable()),
  873. wErr: false,
  874. },
  875. {
  876. op: clientv3.OpGet("foo"),
  877. wErr: true,
  878. },
  879. {
  880. op: clientv3.OpPut("foo", "bar"),
  881. wErr: true,
  882. },
  883. {
  884. op: clientv3.OpDelete("foo"),
  885. wErr: true,
  886. },
  887. {
  888. op: clientv3.OpTxn([]clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("foo"), "=", 0)}, nil, nil),
  889. wErr: true,
  890. },
  891. }
  892. for idx, test := range tests {
  893. _, err := cli.Do(context.TODO(), test.op)
  894. if err != nil && !test.wErr {
  895. t.Errorf("%d: expect no error, got %v", idx, err)
  896. }
  897. if err == nil && test.wErr {
  898. t.Errorf("%d: expect error, got nil", idx)
  899. }
  900. }
  901. }