leasing_test.go 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. // Copyright 2017 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. "context"
  17. "fmt"
  18. "math/rand"
  19. "reflect"
  20. "sync"
  21. "testing"
  22. "time"
  23. "go.etcd.io/etcd/clientv3"
  24. "go.etcd.io/etcd/clientv3/concurrency"
  25. "go.etcd.io/etcd/clientv3/leasing"
  26. "go.etcd.io/etcd/integration"
  27. "go.etcd.io/etcd/pkg/testutil"
  28. )
  29. func TestLeasingPutGet(t *testing.T) {
  30. defer testutil.AfterTest(t)
  31. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  32. defer clus.Terminate(t)
  33. lKV1, closeLKV1, err := leasing.NewKV(clus.Client(0), "foo/")
  34. testutil.AssertNil(t, err)
  35. defer closeLKV1()
  36. lKV2, closeLKV2, err := leasing.NewKV(clus.Client(1), "foo/")
  37. testutil.AssertNil(t, err)
  38. defer closeLKV2()
  39. lKV3, closeLKV3, err := leasing.NewKV(clus.Client(2), "foo/")
  40. testutil.AssertNil(t, err)
  41. defer closeLKV3()
  42. resp, err := lKV1.Get(context.TODO(), "abc")
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. if len(resp.Kvs) != 0 {
  47. t.Errorf("expected nil, got %q", resp.Kvs[0].Key)
  48. }
  49. if _, err = lKV1.Put(context.TODO(), "abc", "def"); err != nil {
  50. t.Fatal(err)
  51. }
  52. if resp, err = lKV2.Get(context.TODO(), "abc"); err != nil {
  53. t.Fatal(err)
  54. }
  55. if string(resp.Kvs[0].Key) != "abc" {
  56. t.Errorf("expected key=%q, got key=%q", "abc", resp.Kvs[0].Key)
  57. }
  58. if string(resp.Kvs[0].Value) != "def" {
  59. t.Errorf("expected value=%q, got value=%q", "bar", resp.Kvs[0].Value)
  60. }
  61. if _, err = lKV3.Get(context.TODO(), "abc"); err != nil {
  62. t.Fatal(err)
  63. }
  64. if _, err = lKV2.Put(context.TODO(), "abc", "ghi"); err != nil {
  65. t.Fatal(err)
  66. }
  67. if resp, err = lKV3.Get(context.TODO(), "abc"); err != nil {
  68. t.Fatal(err)
  69. }
  70. if string(resp.Kvs[0].Key) != "abc" {
  71. t.Errorf("expected key=%q, got key=%q", "abc", resp.Kvs[0].Key)
  72. }
  73. if string(resp.Kvs[0].Value) != "ghi" {
  74. t.Errorf("expected value=%q, got value=%q", "bar", resp.Kvs[0].Value)
  75. }
  76. }
  77. // TestLeasingInterval checks the leasing KV fetches key intervals.
  78. func TestLeasingInterval(t *testing.T) {
  79. defer testutil.AfterTest(t)
  80. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  81. defer clus.Terminate(t)
  82. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  83. testutil.AssertNil(t, err)
  84. defer closeLKV()
  85. keys := []string{"abc/a", "abc/b", "abc/a/a"}
  86. for _, k := range keys {
  87. if _, err = clus.Client(0).Put(context.TODO(), k, "v"); err != nil {
  88. t.Fatal(err)
  89. }
  90. }
  91. resp, err := lkv.Get(context.TODO(), "abc/", clientv3.WithPrefix())
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. if len(resp.Kvs) != 3 {
  96. t.Fatalf("expected keys %+v, got response keys %+v", keys, resp.Kvs)
  97. }
  98. // load into cache
  99. if _, err = lkv.Get(context.TODO(), "abc/a"); err != nil {
  100. t.Fatal(err)
  101. }
  102. // get when prefix is also a cached key
  103. if resp, err = lkv.Get(context.TODO(), "abc/a", clientv3.WithPrefix()); err != nil {
  104. t.Fatal(err)
  105. }
  106. if len(resp.Kvs) != 2 {
  107. t.Fatalf("expected keys %+v, got response keys %+v", keys, resp.Kvs)
  108. }
  109. }
  110. // TestLeasingPutInvalidateNew checks the leasing KV updates its cache on a Put to a new key.
  111. func TestLeasingPutInvalidateNew(t *testing.T) {
  112. defer testutil.AfterTest(t)
  113. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  114. defer clus.Terminate(t)
  115. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  116. testutil.AssertNil(t, err)
  117. defer closeLKV()
  118. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  119. t.Fatal(err)
  120. }
  121. if _, err = lkv.Put(context.TODO(), "k", "v"); err != nil {
  122. t.Fatal(err)
  123. }
  124. lkvResp, err := lkv.Get(context.TODO(), "k")
  125. if err != nil {
  126. t.Fatal(err)
  127. }
  128. cResp, cerr := clus.Client(0).Get(context.TODO(), "k")
  129. if cerr != nil {
  130. t.Fatal(cerr)
  131. }
  132. if !reflect.DeepEqual(lkvResp, cResp) {
  133. t.Fatalf(`expected %+v, got response %+v`, cResp, lkvResp)
  134. }
  135. }
  136. // TestLeasingPutInvalidateExisting checks the leasing KV updates its cache on a Put to an existing key.
  137. func TestLeasingPutInvalidateExisting(t *testing.T) {
  138. defer testutil.AfterTest(t)
  139. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  140. defer clus.Terminate(t)
  141. if _, err := clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  142. t.Fatal(err)
  143. }
  144. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  145. testutil.AssertNil(t, err)
  146. defer closeLKV()
  147. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  148. t.Fatal(err)
  149. }
  150. if _, err = lkv.Put(context.TODO(), "k", "v"); err != nil {
  151. t.Fatal(err)
  152. }
  153. lkvResp, err := lkv.Get(context.TODO(), "k")
  154. if err != nil {
  155. t.Fatal(err)
  156. }
  157. cResp, cerr := clus.Client(0).Get(context.TODO(), "k")
  158. if cerr != nil {
  159. t.Fatal(cerr)
  160. }
  161. if !reflect.DeepEqual(lkvResp, cResp) {
  162. t.Fatalf(`expected %+v, got response %+v`, cResp, lkvResp)
  163. }
  164. }
  165. // TestLeasingGetNoLeaseTTL checks a key with a TTL is not leased.
  166. func TestLeasingGetNoLeaseTTL(t *testing.T) {
  167. defer testutil.AfterTest(t)
  168. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  169. defer clus.Terminate(t)
  170. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  171. testutil.AssertNil(t, err)
  172. defer closeLKV()
  173. lresp, err := clus.Client(0).Grant(context.TODO(), 60)
  174. testutil.AssertNil(t, err)
  175. _, err = clus.Client(0).Put(context.TODO(), "k", "v", clientv3.WithLease(lresp.ID))
  176. testutil.AssertNil(t, err)
  177. gresp, err := lkv.Get(context.TODO(), "k")
  178. testutil.AssertNil(t, err)
  179. testutil.AssertEqual(t, len(gresp.Kvs), 1)
  180. clus.Members[0].Stop(t)
  181. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  182. _, err = lkv.Get(ctx, "k")
  183. cancel()
  184. testutil.AssertEqual(t, err, ctx.Err())
  185. }
  186. // TestLeasingGetSerializable checks the leasing KV can make serialized requests
  187. // when the etcd cluster is partitioned.
  188. func TestLeasingGetSerializable(t *testing.T) {
  189. defer testutil.AfterTest(t)
  190. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 2})
  191. defer clus.Terminate(t)
  192. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  193. testutil.AssertNil(t, err)
  194. defer closeLKV()
  195. if _, err = clus.Client(0).Put(context.TODO(), "cached", "abc"); err != nil {
  196. t.Fatal(err)
  197. }
  198. if _, err = lkv.Get(context.TODO(), "cached"); err != nil {
  199. t.Fatal(err)
  200. }
  201. clus.Members[1].Stop(t)
  202. // don't necessarily try to acquire leasing key ownership for new key
  203. resp, err := lkv.Get(context.TODO(), "uncached", clientv3.WithSerializable())
  204. if err != nil {
  205. t.Fatal(err)
  206. }
  207. if len(resp.Kvs) != 0 {
  208. t.Fatalf(`expected no keys, got response %+v`, resp)
  209. }
  210. clus.Members[0].Stop(t)
  211. // leasing key ownership should have "cached" locally served
  212. cachedResp, err := lkv.Get(context.TODO(), "cached", clientv3.WithSerializable())
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. if len(cachedResp.Kvs) != 1 || string(cachedResp.Kvs[0].Value) != "abc" {
  217. t.Fatalf(`expected "cached"->"abc", got response %+v`, cachedResp)
  218. }
  219. }
  220. // TestLeasingPrevKey checks the cache respects WithPrevKV on puts.
  221. func TestLeasingPrevKey(t *testing.T) {
  222. defer testutil.AfterTest(t)
  223. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 2})
  224. defer clus.Terminate(t)
  225. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  226. testutil.AssertNil(t, err)
  227. defer closeLKV()
  228. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  229. t.Fatal(err)
  230. }
  231. // acquire leasing key
  232. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  233. t.Fatal(err)
  234. }
  235. resp, err := lkv.Put(context.TODO(), "k", "def", clientv3.WithPrevKV())
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. if resp.PrevKv == nil || string(resp.PrevKv.Value) != "abc" {
  240. t.Fatalf(`expected PrevKV.Value="abc", got response %+v`, resp)
  241. }
  242. }
  243. // TestLeasingRevGet checks the cache respects Get by Revision.
  244. func TestLeasingRevGet(t *testing.T) {
  245. defer testutil.AfterTest(t)
  246. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  247. defer clus.Terminate(t)
  248. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  249. testutil.AssertNil(t, err)
  250. defer closeLKV()
  251. putResp, err := clus.Client(0).Put(context.TODO(), "k", "abc")
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. if _, err = clus.Client(0).Put(context.TODO(), "k", "def"); err != nil {
  256. t.Fatal(err)
  257. }
  258. // check historic revision
  259. getResp, gerr := lkv.Get(context.TODO(), "k", clientv3.WithRev(putResp.Header.Revision))
  260. if gerr != nil {
  261. t.Fatal(gerr)
  262. }
  263. if len(getResp.Kvs) != 1 || string(getResp.Kvs[0].Value) != "abc" {
  264. t.Fatalf(`expected "k"->"abc" at rev=%d, got response %+v`, putResp.Header.Revision, getResp)
  265. }
  266. // check current revision
  267. getResp, gerr = lkv.Get(context.TODO(), "k")
  268. if gerr != nil {
  269. t.Fatal(gerr)
  270. }
  271. if len(getResp.Kvs) != 1 || string(getResp.Kvs[0].Value) != "def" {
  272. t.Fatalf(`expected "k"->"abc" at rev=%d, got response %+v`, putResp.Header.Revision, getResp)
  273. }
  274. }
  275. // TestLeasingGetWithOpts checks options that can be served through the cache do not depend on the server.
  276. func TestLeasingGetWithOpts(t *testing.T) {
  277. defer testutil.AfterTest(t)
  278. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  279. defer clus.Terminate(t)
  280. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  281. testutil.AssertNil(t, err)
  282. defer closeLKV()
  283. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  284. t.Fatal(err)
  285. }
  286. // in cache
  287. if _, err = lkv.Get(context.TODO(), "k", clientv3.WithKeysOnly()); err != nil {
  288. t.Fatal(err)
  289. }
  290. clus.Members[0].Stop(t)
  291. opts := []clientv3.OpOption{
  292. clientv3.WithKeysOnly(),
  293. clientv3.WithLimit(1),
  294. clientv3.WithMinCreateRev(1),
  295. clientv3.WithMinModRev(1),
  296. clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend),
  297. clientv3.WithSerializable(),
  298. }
  299. for _, opt := range opts {
  300. if _, err := lkv.Get(context.TODO(), "k", opt); err != nil {
  301. t.Fatal(err)
  302. }
  303. }
  304. getOpts := []clientv3.OpOption{}
  305. for i := 0; i < len(opts); i++ {
  306. getOpts = append(getOpts, opts[rand.Intn(len(opts))])
  307. }
  308. getOpts = getOpts[:rand.Intn(len(opts))]
  309. if _, err := lkv.Get(context.TODO(), "k", getOpts...); err != nil {
  310. t.Fatal(err)
  311. }
  312. }
  313. // TestLeasingConcurrentPut ensures that a get after concurrent puts returns
  314. // the recently put data.
  315. func TestLeasingConcurrentPut(t *testing.T) {
  316. defer testutil.AfterTest(t)
  317. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  318. defer clus.Terminate(t)
  319. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  320. testutil.AssertNil(t, err)
  321. defer closeLKV()
  322. // force key into leasing key cache
  323. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  324. t.Fatal(err)
  325. }
  326. // concurrently put through leasing client
  327. numPuts := 16
  328. putc := make(chan *clientv3.PutResponse, numPuts)
  329. for i := 0; i < numPuts; i++ {
  330. go func() {
  331. resp, perr := lkv.Put(context.TODO(), "k", "abc")
  332. if perr != nil {
  333. t.Error(perr)
  334. }
  335. putc <- resp
  336. }()
  337. }
  338. // record maximum revision from puts
  339. maxRev := int64(0)
  340. for i := 0; i < numPuts; i++ {
  341. if resp := <-putc; resp.Header.Revision > maxRev {
  342. maxRev = resp.Header.Revision
  343. }
  344. }
  345. // confirm Get gives most recently put revisions
  346. getResp, gerr := lkv.Get(context.TODO(), "k")
  347. if gerr != nil {
  348. t.Fatal(err)
  349. }
  350. if mr := getResp.Kvs[0].ModRevision; mr != maxRev {
  351. t.Errorf("expected ModRevision %d, got %d", maxRev, mr)
  352. }
  353. if ver := getResp.Kvs[0].Version; ver != int64(numPuts) {
  354. t.Errorf("expected Version %d, got %d", numPuts, ver)
  355. }
  356. }
  357. func TestLeasingDisconnectedGet(t *testing.T) {
  358. defer testutil.AfterTest(t)
  359. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  360. defer clus.Terminate(t)
  361. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  362. testutil.AssertNil(t, err)
  363. defer closeLKV()
  364. if _, err = clus.Client(0).Put(context.TODO(), "cached", "abc"); err != nil {
  365. t.Fatal(err)
  366. }
  367. // get key so it's cached
  368. if _, err = lkv.Get(context.TODO(), "cached"); err != nil {
  369. t.Fatal(err)
  370. }
  371. clus.Members[0].Stop(t)
  372. // leasing key ownership should have "cached" locally served
  373. cachedResp, err := lkv.Get(context.TODO(), "cached")
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. if len(cachedResp.Kvs) != 1 || string(cachedResp.Kvs[0].Value) != "abc" {
  378. t.Fatalf(`expected "cached"->"abc", got response %+v`, cachedResp)
  379. }
  380. }
  381. func TestLeasingDeleteOwner(t *testing.T) {
  382. defer testutil.AfterTest(t)
  383. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  384. defer clus.Terminate(t)
  385. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  386. testutil.AssertNil(t, err)
  387. defer closeLKV()
  388. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  389. t.Fatal(err)
  390. }
  391. // get+own / delete / get
  392. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  393. t.Fatal(err)
  394. }
  395. if _, err = lkv.Delete(context.TODO(), "k"); err != nil {
  396. t.Fatal(err)
  397. }
  398. resp, err := lkv.Get(context.TODO(), "k")
  399. if err != nil {
  400. t.Fatal(err)
  401. }
  402. if len(resp.Kvs) != 0 {
  403. t.Fatalf(`expected "k" to be deleted, got response %+v`, resp)
  404. }
  405. // try to double delete
  406. if _, err = lkv.Delete(context.TODO(), "k"); err != nil {
  407. t.Fatal(err)
  408. }
  409. }
  410. func TestLeasingDeleteNonOwner(t *testing.T) {
  411. defer testutil.AfterTest(t)
  412. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  413. defer clus.Terminate(t)
  414. lkv1, closeLKV1, err := leasing.NewKV(clus.Client(0), "pfx/")
  415. testutil.AssertNil(t, err)
  416. defer closeLKV1()
  417. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "pfx/")
  418. testutil.AssertNil(t, err)
  419. defer closeLKV2()
  420. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  421. t.Fatal(err)
  422. }
  423. // acquire ownership
  424. if _, err = lkv1.Get(context.TODO(), "k"); err != nil {
  425. t.Fatal(err)
  426. }
  427. // delete via non-owner
  428. if _, err = lkv2.Delete(context.TODO(), "k"); err != nil {
  429. t.Fatal(err)
  430. }
  431. // key should be removed from lkv1
  432. resp, err := lkv1.Get(context.TODO(), "k")
  433. if err != nil {
  434. t.Fatal(err)
  435. }
  436. if len(resp.Kvs) != 0 {
  437. t.Fatalf(`expected "k" to be deleted, got response %+v`, resp)
  438. }
  439. }
  440. func TestLeasingOverwriteResponse(t *testing.T) {
  441. defer testutil.AfterTest(t)
  442. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  443. defer clus.Terminate(t)
  444. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  445. testutil.AssertNil(t, err)
  446. defer closeLKV()
  447. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  448. t.Fatal(err)
  449. }
  450. resp, err := lkv.Get(context.TODO(), "k")
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. resp.Kvs[0].Key[0] = 'z'
  455. resp.Kvs[0].Value[0] = 'z'
  456. resp, err = lkv.Get(context.TODO(), "k")
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. if string(resp.Kvs[0].Key) != "k" {
  461. t.Errorf(`expected key "k", got %q`, string(resp.Kvs[0].Key))
  462. }
  463. if string(resp.Kvs[0].Value) != "abc" {
  464. t.Errorf(`expected value "abc", got %q`, string(resp.Kvs[0].Value))
  465. }
  466. }
  467. func TestLeasingOwnerPutResponse(t *testing.T) {
  468. defer testutil.AfterTest(t)
  469. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  470. defer clus.Terminate(t)
  471. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  472. testutil.AssertNil(t, err)
  473. defer closeLKV()
  474. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  475. t.Fatal(err)
  476. }
  477. _, gerr := lkv.Get(context.TODO(), "k")
  478. if gerr != nil {
  479. t.Fatal(gerr)
  480. }
  481. presp, err := lkv.Put(context.TODO(), "k", "def")
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. if presp == nil {
  486. t.Fatal("expected put response, got nil")
  487. }
  488. clus.Members[0].Stop(t)
  489. gresp, gerr := lkv.Get(context.TODO(), "k")
  490. if gerr != nil {
  491. t.Fatal(gerr)
  492. }
  493. if gresp.Kvs[0].ModRevision != presp.Header.Revision {
  494. t.Errorf("expected mod revision %d, got %d", presp.Header.Revision, gresp.Kvs[0].ModRevision)
  495. }
  496. if gresp.Kvs[0].Version != 2 {
  497. t.Errorf("expected version 2, got version %d", gresp.Kvs[0].Version)
  498. }
  499. }
  500. func TestLeasingTxnOwnerGetRange(t *testing.T) {
  501. defer testutil.AfterTest(t)
  502. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  503. defer clus.Terminate(t)
  504. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  505. testutil.AssertNil(t, err)
  506. defer closeLKV()
  507. keyCount := rand.Intn(10) + 1
  508. for i := 0; i < keyCount; i++ {
  509. k := fmt.Sprintf("k-%d", i)
  510. if _, err := clus.Client(0).Put(context.TODO(), k, k+k); err != nil {
  511. t.Fatal(err)
  512. }
  513. }
  514. if _, err := lkv.Get(context.TODO(), "k-"); err != nil {
  515. t.Fatal(err)
  516. }
  517. tresp, terr := lkv.Txn(context.TODO()).Then(clientv3.OpGet("k-", clientv3.WithPrefix())).Commit()
  518. if terr != nil {
  519. t.Fatal(terr)
  520. }
  521. if resp := tresp.Responses[0].GetResponseRange(); len(resp.Kvs) != keyCount {
  522. t.Fatalf("expected %d keys, got response %+v", keyCount, resp.Kvs)
  523. }
  524. }
  525. func TestLeasingTxnOwnerGet(t *testing.T) {
  526. defer testutil.AfterTest(t)
  527. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  528. defer clus.Terminate(t)
  529. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  530. testutil.AssertNil(t, err)
  531. defer closeLKV()
  532. keyCount := rand.Intn(10) + 1
  533. var ops []clientv3.Op
  534. presps := make([]*clientv3.PutResponse, keyCount)
  535. for i := range presps {
  536. k := fmt.Sprintf("k-%d", i)
  537. presp, err := clus.Client(0).Put(context.TODO(), k, k+k)
  538. if err != nil {
  539. t.Fatal(err)
  540. }
  541. presps[i] = presp
  542. if _, err = lkv.Get(context.TODO(), k); err != nil {
  543. t.Fatal(err)
  544. }
  545. ops = append(ops, clientv3.OpGet(k))
  546. }
  547. ops = ops[:rand.Intn(len(ops))]
  548. // served through cache
  549. clus.Members[0].Stop(t)
  550. var thenOps, elseOps []clientv3.Op
  551. cmps, useThen := randCmps("k-", presps)
  552. if useThen {
  553. thenOps = ops
  554. elseOps = []clientv3.Op{clientv3.OpPut("k", "1")}
  555. } else {
  556. thenOps = []clientv3.Op{clientv3.OpPut("k", "1")}
  557. elseOps = ops
  558. }
  559. tresp, terr := lkv.Txn(context.TODO()).
  560. If(cmps...).
  561. Then(thenOps...).
  562. Else(elseOps...).Commit()
  563. if terr != nil {
  564. t.Fatal(terr)
  565. }
  566. if tresp.Succeeded != useThen {
  567. t.Fatalf("expected succeeded=%v, got tresp=%+v", useThen, tresp)
  568. }
  569. if len(tresp.Responses) != len(ops) {
  570. t.Fatalf("expected %d responses, got %d", len(ops), len(tresp.Responses))
  571. }
  572. wrev := presps[len(presps)-1].Header.Revision
  573. if tresp.Header.Revision < wrev {
  574. t.Fatalf("expected header revision >= %d, got %d", wrev, tresp.Header.Revision)
  575. }
  576. for i := range ops {
  577. k := fmt.Sprintf("k-%d", i)
  578. rr := tresp.Responses[i].GetResponseRange()
  579. if rr == nil {
  580. t.Errorf("expected get response, got %+v", tresp.Responses[i])
  581. }
  582. if string(rr.Kvs[0].Key) != k || string(rr.Kvs[0].Value) != k+k {
  583. t.Errorf(`expected key for %q, got %+v`, k, rr.Kvs)
  584. }
  585. }
  586. }
  587. func TestLeasingTxnOwnerDeleteRange(t *testing.T) {
  588. defer testutil.AfterTest(t)
  589. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  590. defer clus.Terminate(t)
  591. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  592. testutil.AssertNil(t, err)
  593. defer closeLKV()
  594. keyCount := rand.Intn(10) + 1
  595. for i := 0; i < keyCount; i++ {
  596. k := fmt.Sprintf("k-%d", i)
  597. if _, perr := clus.Client(0).Put(context.TODO(), k, k+k); perr != nil {
  598. t.Fatal(perr)
  599. }
  600. }
  601. // cache in lkv
  602. resp, err := lkv.Get(context.TODO(), "k-", clientv3.WithPrefix())
  603. if err != nil {
  604. t.Fatal(err)
  605. }
  606. if len(resp.Kvs) != keyCount {
  607. t.Fatalf("expected %d keys, got %d", keyCount, len(resp.Kvs))
  608. }
  609. if _, terr := lkv.Txn(context.TODO()).Then(clientv3.OpDelete("k-", clientv3.WithPrefix())).Commit(); terr != nil {
  610. t.Fatal(terr)
  611. }
  612. resp, err = lkv.Get(context.TODO(), "k-", clientv3.WithPrefix())
  613. if err != nil {
  614. t.Fatal(err)
  615. }
  616. if len(resp.Kvs) != 0 {
  617. t.Fatalf("expected no keys, got %d", len(resp.Kvs))
  618. }
  619. }
  620. func TestLeasingTxnOwnerDelete(t *testing.T) {
  621. defer testutil.AfterTest(t)
  622. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  623. defer clus.Terminate(t)
  624. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  625. testutil.AssertNil(t, err)
  626. defer closeLKV()
  627. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  628. t.Fatal(err)
  629. }
  630. // cache in lkv
  631. if _, gerr := lkv.Get(context.TODO(), "k"); gerr != nil {
  632. t.Fatal(gerr)
  633. }
  634. if _, terr := lkv.Txn(context.TODO()).Then(clientv3.OpDelete("k")).Commit(); terr != nil {
  635. t.Fatal(terr)
  636. }
  637. resp, err := lkv.Get(context.TODO(), "k")
  638. if err != nil {
  639. t.Fatal(err)
  640. }
  641. if len(resp.Kvs) != 0 {
  642. t.Fatalf("expected no keys, got %d", len(resp.Kvs))
  643. }
  644. }
  645. func TestLeasingTxnOwnerIf(t *testing.T) {
  646. defer testutil.AfterTest(t)
  647. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  648. defer clus.Terminate(t)
  649. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  650. testutil.AssertNil(t, err)
  651. defer closeLKV()
  652. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  653. t.Fatal(err)
  654. }
  655. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  656. t.Fatal(err)
  657. }
  658. // served through cache
  659. clus.Members[0].Stop(t)
  660. tests := []struct {
  661. cmps []clientv3.Cmp
  662. wSucceeded bool
  663. wResponses int
  664. }{
  665. // success
  666. {
  667. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), "=", "abc")},
  668. wSucceeded: true,
  669. wResponses: 1,
  670. },
  671. {
  672. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), "=", 2)},
  673. wSucceeded: true,
  674. wResponses: 1,
  675. },
  676. {
  677. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "=", 2)},
  678. wSucceeded: true,
  679. wResponses: 1,
  680. },
  681. {
  682. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), "=", 1)},
  683. wSucceeded: true,
  684. wResponses: 1,
  685. },
  686. // failure
  687. {
  688. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), ">", "abc")},
  689. },
  690. {
  691. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), ">", 2)},
  692. },
  693. {
  694. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "=", 2)},
  695. wSucceeded: true,
  696. wResponses: 1,
  697. },
  698. {
  699. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), ">", 1)},
  700. },
  701. {
  702. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Value("k"), "<", "abc")},
  703. },
  704. {
  705. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.CreateRevision("k"), "<", 2)},
  706. },
  707. {
  708. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.ModRevision("k"), "<", 2)},
  709. },
  710. {
  711. cmps: []clientv3.Cmp{clientv3.Compare(clientv3.Version("k"), "<", 1)},
  712. },
  713. {
  714. cmps: []clientv3.Cmp{
  715. clientv3.Compare(clientv3.Version("k"), "=", 1),
  716. clientv3.Compare(clientv3.Version("k"), "<", 1),
  717. },
  718. },
  719. }
  720. for i, tt := range tests {
  721. tresp, terr := lkv.Txn(context.TODO()).If(tt.cmps...).Then(clientv3.OpGet("k")).Commit()
  722. if terr != nil {
  723. t.Fatal(terr)
  724. }
  725. if tresp.Succeeded != tt.wSucceeded {
  726. t.Errorf("#%d: expected succeeded %v, got %v", i, tt.wSucceeded, tresp.Succeeded)
  727. }
  728. if len(tresp.Responses) != tt.wResponses {
  729. t.Errorf("#%d: expected %d responses, got %d", i, tt.wResponses, len(tresp.Responses))
  730. }
  731. }
  732. }
  733. func TestLeasingTxnCancel(t *testing.T) {
  734. defer testutil.AfterTest(t)
  735. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  736. defer clus.Terminate(t)
  737. lkv1, closeLKV1, err := leasing.NewKV(clus.Client(0), "pfx/")
  738. testutil.AssertNil(t, err)
  739. defer closeLKV1()
  740. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(1), "pfx/")
  741. testutil.AssertNil(t, err)
  742. defer closeLKV2()
  743. // acquire lease but disconnect so no revoke in time
  744. if _, err = lkv1.Get(context.TODO(), "k"); err != nil {
  745. t.Fatal(err)
  746. }
  747. clus.Members[0].Stop(t)
  748. // wait for leader election, if any
  749. if _, err = clus.Client(1).Get(context.TODO(), "abc"); err != nil {
  750. t.Fatal(err)
  751. }
  752. ctx, cancel := context.WithCancel(context.TODO())
  753. go func() {
  754. time.Sleep(100 * time.Millisecond)
  755. cancel()
  756. }()
  757. if _, err := lkv2.Txn(ctx).Then(clientv3.OpPut("k", "v")).Commit(); err != context.Canceled {
  758. t.Fatalf("expected %v, got %v", context.Canceled, err)
  759. }
  760. }
  761. func TestLeasingTxnNonOwnerPut(t *testing.T) {
  762. defer testutil.AfterTest(t)
  763. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  764. defer clus.Terminate(t)
  765. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  766. testutil.AssertNil(t, err)
  767. defer closeLKV()
  768. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "pfx/")
  769. testutil.AssertNil(t, err)
  770. defer closeLKV2()
  771. if _, err = clus.Client(0).Put(context.TODO(), "k", "abc"); err != nil {
  772. t.Fatal(err)
  773. }
  774. if _, err = clus.Client(0).Put(context.TODO(), "k2", "123"); err != nil {
  775. t.Fatal(err)
  776. }
  777. // cache in lkv
  778. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  779. t.Fatal(err)
  780. }
  781. if _, err = lkv.Get(context.TODO(), "k2"); err != nil {
  782. t.Fatal(err)
  783. }
  784. // invalidate via lkv2 txn
  785. opArray := make([]clientv3.Op, 0)
  786. opArray = append(opArray, clientv3.OpPut("k2", "456"))
  787. tresp, terr := lkv2.Txn(context.TODO()).Then(
  788. clientv3.OpTxn(nil, opArray, nil),
  789. clientv3.OpPut("k", "def"),
  790. clientv3.OpPut("k3", "999"), // + a key not in any cache
  791. ).Commit()
  792. if terr != nil {
  793. t.Fatal(terr)
  794. }
  795. if !tresp.Succeeded || len(tresp.Responses) != 3 {
  796. t.Fatalf("expected txn success, got %+v", tresp)
  797. }
  798. // check cache was invalidated
  799. gresp, gerr := lkv.Get(context.TODO(), "k")
  800. if gerr != nil {
  801. t.Fatal(err)
  802. }
  803. if len(gresp.Kvs) != 1 || string(gresp.Kvs[0].Value) != "def" {
  804. t.Errorf(`expected value "def", got %+v`, gresp)
  805. }
  806. gresp, gerr = lkv.Get(context.TODO(), "k2")
  807. if gerr != nil {
  808. t.Fatal(gerr)
  809. }
  810. if len(gresp.Kvs) != 1 || string(gresp.Kvs[0].Value) != "456" {
  811. t.Errorf(`expected value "def", got %+v`, gresp)
  812. }
  813. // check puts were applied and are all in the same revision
  814. w := clus.Client(0).Watch(
  815. clus.Client(0).Ctx(),
  816. "k",
  817. clientv3.WithRev(tresp.Header.Revision),
  818. clientv3.WithPrefix())
  819. wresp := <-w
  820. c := 0
  821. evs := []clientv3.Event{}
  822. for _, ev := range wresp.Events {
  823. evs = append(evs, *ev)
  824. if ev.Kv.ModRevision == tresp.Header.Revision {
  825. c++
  826. }
  827. }
  828. if c != 3 {
  829. t.Fatalf("expected 3 put events, got %+v", evs)
  830. }
  831. }
  832. // TestLeasingTxnRandIfThenOrElse randomly leases keys two separate clients, then
  833. // issues a random If/{Then,Else} transaction on those keys to one client.
  834. func TestLeasingTxnRandIfThenOrElse(t *testing.T) {
  835. defer testutil.AfterTest(t)
  836. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  837. defer clus.Terminate(t)
  838. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "pfx/")
  839. testutil.AssertNil(t, err1)
  840. defer closeLKV1()
  841. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(0), "pfx/")
  842. testutil.AssertNil(t, err2)
  843. defer closeLKV2()
  844. keyCount := 16
  845. dat := make([]*clientv3.PutResponse, keyCount)
  846. for i := 0; i < keyCount; i++ {
  847. k, v := fmt.Sprintf("k-%d", i), fmt.Sprintf("%d", i)
  848. dat[i], err1 = clus.Client(0).Put(context.TODO(), k, v)
  849. if err1 != nil {
  850. t.Fatal(err1)
  851. }
  852. }
  853. // nondeterministically populate leasing caches
  854. var wg sync.WaitGroup
  855. getc := make(chan struct{}, keyCount)
  856. getRandom := func(kv clientv3.KV) {
  857. defer wg.Done()
  858. for i := 0; i < keyCount/2; i++ {
  859. k := fmt.Sprintf("k-%d", rand.Intn(keyCount))
  860. if _, err := kv.Get(context.TODO(), k); err != nil {
  861. t.Error(err)
  862. }
  863. getc <- struct{}{}
  864. }
  865. }
  866. wg.Add(2)
  867. defer wg.Wait()
  868. go getRandom(lkv1)
  869. go getRandom(lkv2)
  870. // random list of comparisons, all true
  871. cmps, useThen := randCmps("k-", dat)
  872. // random list of puts/gets; unique keys
  873. ops := []clientv3.Op{}
  874. usedIdx := make(map[int]struct{})
  875. for i := 0; i < keyCount; i++ {
  876. idx := rand.Intn(keyCount)
  877. if _, ok := usedIdx[idx]; ok {
  878. continue
  879. }
  880. usedIdx[idx] = struct{}{}
  881. k := fmt.Sprintf("k-%d", idx)
  882. switch rand.Intn(2) {
  883. case 0:
  884. ops = append(ops, clientv3.OpGet(k))
  885. case 1:
  886. ops = append(ops, clientv3.OpPut(k, "a"))
  887. // TODO: add delete
  888. }
  889. }
  890. // random lengths
  891. ops = ops[:rand.Intn(len(ops))]
  892. // wait for some gets to populate the leasing caches before committing
  893. for i := 0; i < keyCount/2; i++ {
  894. <-getc
  895. }
  896. // randomly choose between then and else blocks
  897. var thenOps, elseOps []clientv3.Op
  898. if useThen {
  899. thenOps = ops
  900. } else {
  901. // force failure
  902. elseOps = ops
  903. }
  904. tresp, terr := lkv1.Txn(context.TODO()).If(cmps...).Then(thenOps...).Else(elseOps...).Commit()
  905. if terr != nil {
  906. t.Fatal(terr)
  907. }
  908. // cmps always succeed
  909. if tresp.Succeeded != useThen {
  910. t.Fatalf("expected succeeded=%v, got tresp=%+v", useThen, tresp)
  911. }
  912. // get should match what was put
  913. checkPuts := func(s string, kv clientv3.KV) {
  914. for _, op := range ops {
  915. if !op.IsPut() {
  916. continue
  917. }
  918. resp, rerr := kv.Get(context.TODO(), string(op.KeyBytes()))
  919. if rerr != nil {
  920. t.Fatal(rerr)
  921. }
  922. if len(resp.Kvs) != 1 || string(resp.Kvs[0].Value) != "a" {
  923. t.Fatalf(`%s: expected value="a", got %+v`, s, resp.Kvs)
  924. }
  925. }
  926. }
  927. checkPuts("client(0)", clus.Client(0))
  928. checkPuts("lkv1", lkv1)
  929. checkPuts("lkv2", lkv2)
  930. }
  931. func TestLeasingOwnerPutError(t *testing.T) {
  932. defer testutil.AfterTest(t)
  933. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  934. defer clus.Terminate(t)
  935. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  936. testutil.AssertNil(t, err)
  937. defer closeLKV()
  938. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  939. t.Fatal(err)
  940. }
  941. clus.Members[0].Stop(t)
  942. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  943. defer cancel()
  944. if resp, err := lkv.Put(ctx, "k", "v"); err == nil {
  945. t.Fatalf("expected error, got response %+v", resp)
  946. }
  947. }
  948. func TestLeasingOwnerDeleteError(t *testing.T) {
  949. defer testutil.AfterTest(t)
  950. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  951. defer clus.Terminate(t)
  952. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  953. testutil.AssertNil(t, err)
  954. defer closeLKV()
  955. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  956. t.Fatal(err)
  957. }
  958. clus.Members[0].Stop(t)
  959. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  960. defer cancel()
  961. if resp, err := lkv.Delete(ctx, "k"); err == nil {
  962. t.Fatalf("expected error, got response %+v", resp)
  963. }
  964. }
  965. func TestLeasingNonOwnerPutError(t *testing.T) {
  966. defer testutil.AfterTest(t)
  967. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  968. defer clus.Terminate(t)
  969. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  970. testutil.AssertNil(t, err)
  971. defer closeLKV()
  972. clus.Members[0].Stop(t)
  973. ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
  974. defer cancel()
  975. if resp, err := lkv.Put(ctx, "k", "v"); err == nil {
  976. t.Fatalf("expected error, got response %+v", resp)
  977. }
  978. }
  979. func TestLeasingOwnerDeletePrefix(t *testing.T) {
  980. testLeasingOwnerDelete(t, clientv3.OpDelete("key/", clientv3.WithPrefix()))
  981. }
  982. func TestLeasingOwnerDeleteFrom(t *testing.T) {
  983. testLeasingOwnerDelete(t, clientv3.OpDelete("kd", clientv3.WithFromKey()))
  984. }
  985. func testLeasingOwnerDelete(t *testing.T, del clientv3.Op) {
  986. defer testutil.AfterTest(t)
  987. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  988. defer clus.Terminate(t)
  989. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "0/")
  990. testutil.AssertNil(t, err)
  991. defer closeLKV()
  992. for i := 0; i < 8; i++ {
  993. if _, err = clus.Client(0).Put(context.TODO(), fmt.Sprintf("key/%d", i), "123"); err != nil {
  994. t.Fatal(err)
  995. }
  996. }
  997. if _, err = lkv.Get(context.TODO(), "key/1"); err != nil {
  998. t.Fatal(err)
  999. }
  1000. opResp, delErr := lkv.Do(context.TODO(), del)
  1001. if delErr != nil {
  1002. t.Fatal(delErr)
  1003. }
  1004. delResp := opResp.Del()
  1005. // confirm keys are invalidated from cache and deleted on etcd
  1006. for i := 0; i < 8; i++ {
  1007. resp, err := lkv.Get(context.TODO(), fmt.Sprintf("key/%d", i))
  1008. if err != nil {
  1009. t.Fatal(err)
  1010. }
  1011. if len(resp.Kvs) != 0 {
  1012. t.Fatalf("expected no keys on key/%d, got %+v", i, resp)
  1013. }
  1014. }
  1015. // confirm keys were deleted atomically
  1016. w := clus.Client(0).Watch(
  1017. clus.Client(0).Ctx(),
  1018. "key/",
  1019. clientv3.WithRev(delResp.Header.Revision),
  1020. clientv3.WithPrefix())
  1021. if wresp := <-w; len(wresp.Events) != 8 {
  1022. t.Fatalf("expected %d delete events,got %d", 8, len(wresp.Events))
  1023. }
  1024. }
  1025. func TestLeasingDeleteRangeBounds(t *testing.T) {
  1026. defer testutil.AfterTest(t)
  1027. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1028. defer clus.Terminate(t)
  1029. delkv, closeDelKV, err := leasing.NewKV(clus.Client(0), "0/")
  1030. testutil.AssertNil(t, err)
  1031. defer closeDelKV()
  1032. getkv, closeGetKv, err := leasing.NewKV(clus.Client(0), "0/")
  1033. testutil.AssertNil(t, err)
  1034. defer closeGetKv()
  1035. for _, k := range []string{"j", "m"} {
  1036. if _, err = clus.Client(0).Put(context.TODO(), k, "123"); err != nil {
  1037. t.Fatal(err)
  1038. }
  1039. if _, err = getkv.Get(context.TODO(), k); err != nil {
  1040. t.Fatal(err)
  1041. }
  1042. }
  1043. if _, err = delkv.Delete(context.TODO(), "k", clientv3.WithPrefix()); err != nil {
  1044. t.Fatal(err)
  1045. }
  1046. // leases still on server?
  1047. for _, k := range []string{"j", "m"} {
  1048. resp, geterr := clus.Client(0).Get(context.TODO(), "0/"+k, clientv3.WithPrefix())
  1049. if geterr != nil {
  1050. t.Fatal(geterr)
  1051. }
  1052. if len(resp.Kvs) != 1 {
  1053. t.Fatalf("expected leasing key, got %+v", resp)
  1054. }
  1055. }
  1056. // j and m should still have leases registered since not under k*
  1057. clus.Members[0].Stop(t)
  1058. if _, err = getkv.Get(context.TODO(), "j"); err != nil {
  1059. t.Fatal(err)
  1060. }
  1061. if _, err = getkv.Get(context.TODO(), "m"); err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. }
  1065. func TestLeasingDeleteRangeContendTxn(t *testing.T) {
  1066. then := []clientv3.Op{clientv3.OpDelete("key/", clientv3.WithPrefix())}
  1067. testLeasingDeleteRangeContend(t, clientv3.OpTxn(nil, then, nil))
  1068. }
  1069. func TestLeaseDeleteRangeContendDel(t *testing.T) {
  1070. op := clientv3.OpDelete("key/", clientv3.WithPrefix())
  1071. testLeasingDeleteRangeContend(t, op)
  1072. }
  1073. func testLeasingDeleteRangeContend(t *testing.T, op clientv3.Op) {
  1074. defer testutil.AfterTest(t)
  1075. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1076. defer clus.Terminate(t)
  1077. delkv, closeDelKV, err := leasing.NewKV(clus.Client(0), "0/")
  1078. testutil.AssertNil(t, err)
  1079. defer closeDelKV()
  1080. putkv, closePutKV, err := leasing.NewKV(clus.Client(0), "0/")
  1081. testutil.AssertNil(t, err)
  1082. defer closePutKV()
  1083. for i := 0; i < 8; i++ {
  1084. key := fmt.Sprintf("key/%d", i)
  1085. if _, err = clus.Client(0).Put(context.TODO(), key, "123"); err != nil {
  1086. t.Fatal(err)
  1087. }
  1088. if _, err = putkv.Get(context.TODO(), key); err != nil {
  1089. t.Fatal(err)
  1090. }
  1091. }
  1092. ctx, cancel := context.WithCancel(context.TODO())
  1093. donec := make(chan struct{})
  1094. go func() {
  1095. defer close(donec)
  1096. for i := 0; ctx.Err() == nil; i++ {
  1097. key := fmt.Sprintf("key/%d", i%8)
  1098. putkv.Put(ctx, key, "123")
  1099. putkv.Get(ctx, key)
  1100. }
  1101. }()
  1102. _, delErr := delkv.Do(context.TODO(), op)
  1103. cancel()
  1104. <-donec
  1105. if delErr != nil {
  1106. t.Fatal(delErr)
  1107. }
  1108. // confirm keys on non-deleter match etcd
  1109. for i := 0; i < 8; i++ {
  1110. key := fmt.Sprintf("key/%d", i)
  1111. resp, err := putkv.Get(context.TODO(), key)
  1112. if err != nil {
  1113. t.Fatal(err)
  1114. }
  1115. servResp, err := clus.Client(0).Get(context.TODO(), key)
  1116. if err != nil {
  1117. t.Fatal(err)
  1118. }
  1119. if !reflect.DeepEqual(resp.Kvs, servResp.Kvs) {
  1120. t.Errorf("#%d: expected %+v, got %+v", i, servResp.Kvs, resp.Kvs)
  1121. }
  1122. }
  1123. }
  1124. func TestLeasingPutGetDeleteConcurrent(t *testing.T) {
  1125. defer testutil.AfterTest(t)
  1126. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1127. defer clus.Terminate(t)
  1128. lkvs := make([]clientv3.KV, 16)
  1129. for i := range lkvs {
  1130. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "pfx/")
  1131. testutil.AssertNil(t, err)
  1132. defer closeLKV()
  1133. lkvs[i] = lkv
  1134. }
  1135. getdel := func(kv clientv3.KV) {
  1136. if _, err := kv.Put(context.TODO(), "k", "abc"); err != nil {
  1137. t.Fatal(err)
  1138. }
  1139. time.Sleep(time.Millisecond)
  1140. if _, err := kv.Get(context.TODO(), "k"); err != nil {
  1141. t.Fatal(err)
  1142. }
  1143. if _, err := kv.Delete(context.TODO(), "k"); err != nil {
  1144. t.Fatal(err)
  1145. }
  1146. time.Sleep(2 * time.Millisecond)
  1147. }
  1148. var wg sync.WaitGroup
  1149. wg.Add(16)
  1150. for i := 0; i < 16; i++ {
  1151. go func() {
  1152. defer wg.Done()
  1153. for _, kv := range lkvs {
  1154. getdel(kv)
  1155. }
  1156. }()
  1157. }
  1158. wg.Wait()
  1159. resp, err := lkvs[0].Get(context.TODO(), "k")
  1160. if err != nil {
  1161. t.Fatal(err)
  1162. }
  1163. if len(resp.Kvs) > 0 {
  1164. t.Fatalf("expected no kvs, got %+v", resp.Kvs)
  1165. }
  1166. resp, err = clus.Client(0).Get(context.TODO(), "k")
  1167. if err != nil {
  1168. t.Fatal(err)
  1169. }
  1170. if len(resp.Kvs) > 0 {
  1171. t.Fatalf("expected no kvs, got %+v", resp.Kvs)
  1172. }
  1173. }
  1174. // TestLeasingReconnectOwnerRevoke checks that revocation works if
  1175. // disconnected when trying to submit revoke txn.
  1176. func TestLeasingReconnectOwnerRevoke(t *testing.T) {
  1177. defer testutil.AfterTest(t)
  1178. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1179. defer clus.Terminate(t)
  1180. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "foo/")
  1181. testutil.AssertNil(t, err1)
  1182. defer closeLKV1()
  1183. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(1), "foo/")
  1184. testutil.AssertNil(t, err2)
  1185. defer closeLKV2()
  1186. if _, err := lkv1.Get(context.TODO(), "k"); err != nil {
  1187. t.Fatal(err)
  1188. }
  1189. // force leader away from member 0
  1190. clus.Members[0].Stop(t)
  1191. clus.WaitLeader(t)
  1192. clus.Members[0].Restart(t)
  1193. cctx, cancel := context.WithCancel(context.TODO())
  1194. sdonec, pdonec := make(chan struct{}), make(chan struct{})
  1195. // make lkv1 connection choppy so Txn fails
  1196. go func() {
  1197. defer close(sdonec)
  1198. for i := 0; i < 3 && cctx.Err() == nil; i++ {
  1199. clus.Members[0].Stop(t)
  1200. time.Sleep(10 * time.Millisecond)
  1201. clus.Members[0].Restart(t)
  1202. }
  1203. }()
  1204. go func() {
  1205. defer close(pdonec)
  1206. if _, err := lkv2.Put(cctx, "k", "v"); err != nil {
  1207. t.Log(err)
  1208. }
  1209. // blocks until lkv1 connection comes back
  1210. resp, err := lkv1.Get(cctx, "k")
  1211. if err != nil {
  1212. t.Error(err)
  1213. }
  1214. if string(resp.Kvs[0].Value) != "v" {
  1215. t.Errorf(`expected "v" value, got %+v`, resp)
  1216. }
  1217. }()
  1218. select {
  1219. case <-pdonec:
  1220. cancel()
  1221. <-sdonec
  1222. case <-time.After(15 * time.Second):
  1223. cancel()
  1224. <-sdonec
  1225. <-pdonec
  1226. t.Fatal("took too long to revoke and put")
  1227. }
  1228. }
  1229. // TestLeasingReconnectOwnerRevokeCompact checks that revocation works if
  1230. // disconnected and the watch is compacted.
  1231. func TestLeasingReconnectOwnerRevokeCompact(t *testing.T) {
  1232. defer testutil.AfterTest(t)
  1233. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1234. defer clus.Terminate(t)
  1235. lkv1, closeLKV1, err1 := leasing.NewKV(clus.Client(0), "foo/")
  1236. testutil.AssertNil(t, err1)
  1237. defer closeLKV1()
  1238. lkv2, closeLKV2, err2 := leasing.NewKV(clus.Client(1), "foo/")
  1239. testutil.AssertNil(t, err2)
  1240. defer closeLKV2()
  1241. if _, err := lkv1.Get(context.TODO(), "k"); err != nil {
  1242. t.Fatal(err)
  1243. }
  1244. clus.Members[0].Stop(t)
  1245. clus.WaitLeader(t)
  1246. // put some more revisions for compaction
  1247. _, err := clus.Client(1).Put(context.TODO(), "a", "123")
  1248. if err != nil {
  1249. t.Fatal(err)
  1250. }
  1251. presp, err := clus.Client(1).Put(context.TODO(), "a", "123")
  1252. if err != nil {
  1253. t.Fatal(err)
  1254. }
  1255. // compact while lkv1 is disconnected
  1256. rev := presp.Header.Revision
  1257. if _, err = clus.Client(1).Compact(context.TODO(), rev); err != nil {
  1258. t.Fatal(err)
  1259. }
  1260. clus.Members[0].Restart(t)
  1261. cctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  1262. defer cancel()
  1263. if _, err = lkv2.Put(cctx, "k", "v"); err != nil {
  1264. t.Fatal(err)
  1265. }
  1266. resp, err := lkv1.Get(cctx, "k")
  1267. if err != nil {
  1268. t.Fatal(err)
  1269. }
  1270. if string(resp.Kvs[0].Value) != "v" {
  1271. t.Fatalf(`expected "v" value, got %+v`, resp)
  1272. }
  1273. }
  1274. // TestLeasingReconnectOwnerConsistency checks a write error on an owner will
  1275. // not cause inconsistency between the server and the client.
  1276. func TestLeasingReconnectOwnerConsistency(t *testing.T) {
  1277. defer testutil.AfterTest(t)
  1278. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1279. defer clus.Terminate(t)
  1280. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1281. defer closeLKV()
  1282. testutil.AssertNil(t, err)
  1283. if _, err = lkv.Put(context.TODO(), "k", "x"); err != nil {
  1284. t.Fatal(err)
  1285. }
  1286. if _, err = lkv.Put(context.TODO(), "kk", "y"); err != nil {
  1287. t.Fatal(err)
  1288. }
  1289. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1290. t.Fatal(err)
  1291. }
  1292. for i := 0; i < 10; i++ {
  1293. v := fmt.Sprintf("%d", i)
  1294. donec := make(chan struct{})
  1295. clus.Members[0].DropConnections()
  1296. go func() {
  1297. defer close(donec)
  1298. for i := 0; i < 20; i++ {
  1299. clus.Members[0].DropConnections()
  1300. time.Sleep(time.Millisecond)
  1301. }
  1302. }()
  1303. switch rand.Intn(7) {
  1304. case 0:
  1305. _, err = lkv.Put(context.TODO(), "k", v)
  1306. case 1:
  1307. _, err = lkv.Delete(context.TODO(), "k")
  1308. case 2:
  1309. txn := lkv.Txn(context.TODO()).Then(
  1310. clientv3.OpGet("k"),
  1311. clientv3.OpDelete("k"),
  1312. )
  1313. _, err = txn.Commit()
  1314. case 3:
  1315. txn := lkv.Txn(context.TODO()).Then(
  1316. clientv3.OpGet("k"),
  1317. clientv3.OpPut("k", v),
  1318. )
  1319. _, err = txn.Commit()
  1320. case 4:
  1321. _, err = lkv.Do(context.TODO(), clientv3.OpPut("k", v))
  1322. case 5:
  1323. _, err = lkv.Do(context.TODO(), clientv3.OpDelete("k"))
  1324. case 6:
  1325. _, err = lkv.Delete(context.TODO(), "k", clientv3.WithPrefix())
  1326. }
  1327. <-donec
  1328. if err != nil {
  1329. // TODO wrap input client to generate errors
  1330. break
  1331. }
  1332. }
  1333. lresp, lerr := lkv.Get(context.TODO(), "k")
  1334. if lerr != nil {
  1335. t.Fatal(lerr)
  1336. }
  1337. cresp, cerr := clus.Client(0).Get(context.TODO(), "k")
  1338. if cerr != nil {
  1339. t.Fatal(cerr)
  1340. }
  1341. if !reflect.DeepEqual(lresp.Kvs, cresp.Kvs) {
  1342. t.Fatalf("expected %+v, got %+v", cresp, lresp)
  1343. }
  1344. }
  1345. func TestLeasingTxnAtomicCache(t *testing.T) {
  1346. defer testutil.AfterTest(t)
  1347. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1348. defer clus.Terminate(t)
  1349. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1350. testutil.AssertNil(t, err)
  1351. defer closeLKV()
  1352. puts, gets := make([]clientv3.Op, 16), make([]clientv3.Op, 16)
  1353. for i := range puts {
  1354. k := fmt.Sprintf("k-%d", i)
  1355. puts[i], gets[i] = clientv3.OpPut(k, k), clientv3.OpGet(k)
  1356. }
  1357. if _, err = clus.Client(0).Txn(context.TODO()).Then(puts...).Commit(); err != nil {
  1358. t.Fatal(err)
  1359. }
  1360. for i := range gets {
  1361. if _, err = lkv.Do(context.TODO(), gets[i]); err != nil {
  1362. t.Fatal(err)
  1363. }
  1364. }
  1365. numPutters, numGetters := 16, 16
  1366. var wgPutters, wgGetters sync.WaitGroup
  1367. wgPutters.Add(numPutters)
  1368. wgGetters.Add(numGetters)
  1369. f := func() {
  1370. defer wgPutters.Done()
  1371. for i := 0; i < 10; i++ {
  1372. if _, txnerr := lkv.Txn(context.TODO()).Then(puts...).Commit(); err != nil {
  1373. t.Fatal(txnerr)
  1374. }
  1375. }
  1376. }
  1377. donec := make(chan struct{}, numPutters)
  1378. g := func() {
  1379. defer wgGetters.Done()
  1380. for {
  1381. select {
  1382. case <-donec:
  1383. return
  1384. default:
  1385. }
  1386. tresp, err := lkv.Txn(context.TODO()).Then(gets...).Commit()
  1387. if err != nil {
  1388. t.Error(err)
  1389. }
  1390. revs := make([]int64, len(gets))
  1391. for i, resp := range tresp.Responses {
  1392. rr := resp.GetResponseRange()
  1393. revs[i] = rr.Kvs[0].ModRevision
  1394. }
  1395. for i := 1; i < len(revs); i++ {
  1396. if revs[i] != revs[i-1] {
  1397. t.Errorf("expected matching revisions, got %+v", revs)
  1398. }
  1399. }
  1400. }
  1401. }
  1402. for i := 0; i < numGetters; i++ {
  1403. go g()
  1404. }
  1405. for i := 0; i < numPutters; i++ {
  1406. go f()
  1407. }
  1408. wgPutters.Wait()
  1409. close(donec)
  1410. wgGetters.Wait()
  1411. }
  1412. // TestLeasingReconnectTxn checks that Txn is resilient to disconnects.
  1413. func TestLeasingReconnectTxn(t *testing.T) {
  1414. defer testutil.AfterTest(t)
  1415. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1416. defer clus.Terminate(t)
  1417. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1418. testutil.AssertNil(t, err)
  1419. defer closeLKV()
  1420. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1421. t.Fatal(err)
  1422. }
  1423. donec := make(chan struct{})
  1424. go func() {
  1425. defer close(donec)
  1426. clus.Members[0].DropConnections()
  1427. for i := 0; i < 10; i++ {
  1428. clus.Members[0].DropConnections()
  1429. time.Sleep(time.Millisecond)
  1430. }
  1431. time.Sleep(10 * time.Millisecond)
  1432. }()
  1433. _, lerr := lkv.Txn(context.TODO()).
  1434. If(clientv3.Compare(clientv3.Version("k"), "=", 0)).
  1435. Then(clientv3.OpGet("k")).
  1436. Commit()
  1437. <-donec
  1438. if lerr != nil {
  1439. t.Fatal(lerr)
  1440. }
  1441. }
  1442. // TestLeasingReconnectNonOwnerGet checks a get error on an owner will
  1443. // not cause inconsistency between the server and the client.
  1444. func TestLeasingReconnectNonOwnerGet(t *testing.T) {
  1445. defer testutil.AfterTest(t)
  1446. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1447. defer clus.Terminate(t)
  1448. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1449. testutil.AssertNil(t, err)
  1450. defer closeLKV()
  1451. // populate a few keys so some leasing gets have keys
  1452. for i := 0; i < 4; i++ {
  1453. k := fmt.Sprintf("k-%d", i*2)
  1454. if _, err = lkv.Put(context.TODO(), k, k[2:]); err != nil {
  1455. t.Fatal(err)
  1456. }
  1457. }
  1458. n := 0
  1459. for i := 0; i < 10; i++ {
  1460. donec := make(chan struct{})
  1461. clus.Members[0].DropConnections()
  1462. go func() {
  1463. defer close(donec)
  1464. for j := 0; j < 10; j++ {
  1465. clus.Members[0].DropConnections()
  1466. time.Sleep(time.Millisecond)
  1467. }
  1468. }()
  1469. _, err = lkv.Get(context.TODO(), fmt.Sprintf("k-%d", i))
  1470. <-donec
  1471. n++
  1472. if err != nil {
  1473. break
  1474. }
  1475. }
  1476. for i := 0; i < n; i++ {
  1477. k := fmt.Sprintf("k-%d", i)
  1478. lresp, lerr := lkv.Get(context.TODO(), k)
  1479. if lerr != nil {
  1480. t.Fatal(lerr)
  1481. }
  1482. cresp, cerr := clus.Client(0).Get(context.TODO(), k)
  1483. if cerr != nil {
  1484. t.Fatal(cerr)
  1485. }
  1486. if !reflect.DeepEqual(lresp.Kvs, cresp.Kvs) {
  1487. t.Fatalf("expected %+v, got %+v", cresp, lresp)
  1488. }
  1489. }
  1490. }
  1491. func TestLeasingTxnRangeCmp(t *testing.T) {
  1492. defer testutil.AfterTest(t)
  1493. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1494. defer clus.Terminate(t)
  1495. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1496. testutil.AssertNil(t, err)
  1497. defer closeLKV()
  1498. if _, err = clus.Client(0).Put(context.TODO(), "k", "a"); err != nil {
  1499. t.Fatal(err)
  1500. }
  1501. // k2 version = 2
  1502. if _, err = clus.Client(0).Put(context.TODO(), "k2", "a"); err != nil {
  1503. t.Fatal(err)
  1504. }
  1505. if _, err = clus.Client(0).Put(context.TODO(), "k2", "a"); err != nil {
  1506. t.Fatal(err)
  1507. }
  1508. // cache k
  1509. if _, err = lkv.Get(context.TODO(), "k"); err != nil {
  1510. t.Fatal(err)
  1511. }
  1512. cmp := clientv3.Compare(clientv3.Version("k").WithPrefix(), "=", 1)
  1513. tresp, terr := lkv.Txn(context.TODO()).If(cmp).Commit()
  1514. if terr != nil {
  1515. t.Fatal(err)
  1516. }
  1517. if tresp.Succeeded {
  1518. t.Fatalf("expected Succeeded=false, got %+v", tresp)
  1519. }
  1520. }
  1521. func TestLeasingDo(t *testing.T) {
  1522. defer testutil.AfterTest(t)
  1523. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  1524. defer clus.Terminate(t)
  1525. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1526. testutil.AssertNil(t, err)
  1527. defer closeLKV()
  1528. ops := []clientv3.Op{
  1529. clientv3.OpTxn(nil, nil, nil),
  1530. clientv3.OpGet("a"),
  1531. clientv3.OpPut("a/abc", "v"),
  1532. clientv3.OpDelete("a", clientv3.WithPrefix()),
  1533. clientv3.OpTxn(nil, nil, nil),
  1534. }
  1535. for i, op := range ops {
  1536. resp, resperr := lkv.Do(context.TODO(), op)
  1537. if resperr != nil {
  1538. t.Errorf("#%d: failed (%v)", i, resperr)
  1539. }
  1540. switch {
  1541. case op.IsGet() && resp.Get() == nil:
  1542. t.Errorf("#%d: get but nil get response", i)
  1543. case op.IsPut() && resp.Put() == nil:
  1544. t.Errorf("#%d: put op but nil get response", i)
  1545. case op.IsDelete() && resp.Del() == nil:
  1546. t.Errorf("#%d: delete op but nil delete response", i)
  1547. case op.IsTxn() && resp.Txn() == nil:
  1548. t.Errorf("#%d: txn op but nil txn response", i)
  1549. }
  1550. }
  1551. gresp, err := clus.Client(0).Get(context.TODO(), "a", clientv3.WithPrefix())
  1552. if err != nil {
  1553. t.Fatal(err)
  1554. }
  1555. if len(gresp.Kvs) != 0 {
  1556. t.Fatalf("expected no keys, got %+v", gresp.Kvs)
  1557. }
  1558. }
  1559. func TestLeasingTxnOwnerPutBranch(t *testing.T) {
  1560. defer testutil.AfterTest(t)
  1561. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1562. defer clus.Terminate(t)
  1563. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/")
  1564. testutil.AssertNil(t, err)
  1565. defer closeLKV()
  1566. n := 0
  1567. treeOp := makePutTreeOp("tree", &n, 4)
  1568. for i := 0; i < n; i++ {
  1569. k := fmt.Sprintf("tree/%d", i)
  1570. if _, err = clus.Client(0).Put(context.TODO(), k, "a"); err != nil {
  1571. t.Fatal(err)
  1572. }
  1573. if _, err = lkv.Get(context.TODO(), k); err != nil {
  1574. t.Fatal(err)
  1575. }
  1576. }
  1577. if _, err = lkv.Do(context.TODO(), treeOp); err != nil {
  1578. t.Fatal(err)
  1579. }
  1580. // lkv shouldn't need to call out to server for updated leased keys
  1581. clus.Members[0].Stop(t)
  1582. for i := 0; i < n; i++ {
  1583. k := fmt.Sprintf("tree/%d", i)
  1584. lkvResp, err := lkv.Get(context.TODO(), k)
  1585. if err != nil {
  1586. t.Fatal(err)
  1587. }
  1588. clusResp, err := clus.Client(1).Get(context.TODO(), k)
  1589. if err != nil {
  1590. t.Fatal(err)
  1591. }
  1592. if !reflect.DeepEqual(clusResp.Kvs, lkvResp.Kvs) {
  1593. t.Fatalf("expected %+v, got %+v", clusResp.Kvs, lkvResp.Kvs)
  1594. }
  1595. }
  1596. }
  1597. func makePutTreeOp(pfx string, v *int, depth int) clientv3.Op {
  1598. key := fmt.Sprintf("%s/%d", pfx, *v)
  1599. *v = *v + 1
  1600. if depth == 0 {
  1601. return clientv3.OpPut(key, "leaf")
  1602. }
  1603. t, e := makePutTreeOp(pfx, v, depth-1), makePutTreeOp(pfx, v, depth-1)
  1604. tPut, ePut := clientv3.OpPut(key, "then"), clientv3.OpPut(key, "else")
  1605. cmps := make([]clientv3.Cmp, 1)
  1606. if rand.Intn(2) == 0 {
  1607. // follow then path
  1608. cmps[0] = clientv3.Compare(clientv3.Version("nokey"), "=", 0)
  1609. } else {
  1610. // follow else path
  1611. cmps[0] = clientv3.Compare(clientv3.Version("nokey"), ">", 0)
  1612. }
  1613. return clientv3.OpTxn(cmps, []clientv3.Op{t, tPut}, []clientv3.Op{e, ePut})
  1614. }
  1615. func randCmps(pfx string, dat []*clientv3.PutResponse) (cmps []clientv3.Cmp, then bool) {
  1616. for i := 0; i < len(dat); i++ {
  1617. idx := rand.Intn(len(dat))
  1618. k := fmt.Sprintf("%s%d", pfx, idx)
  1619. rev := dat[idx].Header.Revision
  1620. var cmp clientv3.Cmp
  1621. switch rand.Intn(4) {
  1622. case 0:
  1623. cmp = clientv3.Compare(clientv3.CreateRevision(k), ">", rev-1)
  1624. case 1:
  1625. cmp = clientv3.Compare(clientv3.Version(k), "=", 1)
  1626. case 2:
  1627. cmp = clientv3.Compare(clientv3.CreateRevision(k), "=", rev)
  1628. case 3:
  1629. cmp = clientv3.Compare(clientv3.CreateRevision(k), "!=", rev+1)
  1630. }
  1631. cmps = append(cmps, cmp)
  1632. }
  1633. cmps = cmps[:rand.Intn(len(dat))]
  1634. if rand.Intn(2) == 0 {
  1635. return cmps, true
  1636. }
  1637. i := rand.Intn(len(dat))
  1638. cmps = append(cmps, clientv3.Compare(clientv3.Version(fmt.Sprintf("k-%d", i)), "=", 0))
  1639. return cmps, false
  1640. }
  1641. func TestLeasingSessionExpire(t *testing.T) {
  1642. defer testutil.AfterTest(t)
  1643. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1644. defer clus.Terminate(t)
  1645. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/", concurrency.WithTTL(1))
  1646. testutil.AssertNil(t, err)
  1647. defer closeLKV()
  1648. lkv2, closeLKV2, err := leasing.NewKV(clus.Client(0), "foo/")
  1649. testutil.AssertNil(t, err)
  1650. defer closeLKV2()
  1651. // acquire lease on abc
  1652. if _, err = lkv.Get(context.TODO(), "abc"); err != nil {
  1653. t.Fatal(err)
  1654. }
  1655. // down endpoint lkv uses for keepalives
  1656. clus.Members[0].Stop(t)
  1657. if err = waitForLeasingExpire(clus.Client(1), "foo/abc"); err != nil {
  1658. t.Fatal(err)
  1659. }
  1660. waitForExpireAck(t, lkv)
  1661. clus.Members[0].Restart(t)
  1662. integration.WaitClientV3(t, lkv2)
  1663. if _, err = lkv2.Put(context.TODO(), "abc", "def"); err != nil {
  1664. t.Fatal(err)
  1665. }
  1666. resp, err := lkv.Get(context.TODO(), "abc")
  1667. if err != nil {
  1668. t.Fatal(err)
  1669. }
  1670. if v := string(resp.Kvs[0].Value); v != "def" {
  1671. t.Fatalf("expected %q, got %q", "v", v)
  1672. }
  1673. }
  1674. func TestLeasingSessionExpireCancel(t *testing.T) {
  1675. tests := []func(context.Context, clientv3.KV) error{
  1676. func(ctx context.Context, kv clientv3.KV) error {
  1677. _, err := kv.Get(ctx, "abc")
  1678. return err
  1679. },
  1680. func(ctx context.Context, kv clientv3.KV) error {
  1681. _, err := kv.Delete(ctx, "abc")
  1682. return err
  1683. },
  1684. func(ctx context.Context, kv clientv3.KV) error {
  1685. _, err := kv.Put(ctx, "abc", "v")
  1686. return err
  1687. },
  1688. func(ctx context.Context, kv clientv3.KV) error {
  1689. _, err := kv.Txn(ctx).Then(clientv3.OpGet("abc")).Commit()
  1690. return err
  1691. },
  1692. func(ctx context.Context, kv clientv3.KV) error {
  1693. _, err := kv.Do(ctx, clientv3.OpPut("abc", "v"))
  1694. return err
  1695. },
  1696. func(ctx context.Context, kv clientv3.KV) error {
  1697. _, err := kv.Do(ctx, clientv3.OpDelete("abc"))
  1698. return err
  1699. },
  1700. func(ctx context.Context, kv clientv3.KV) error {
  1701. _, err := kv.Do(ctx, clientv3.OpGet("abc"))
  1702. return err
  1703. },
  1704. func(ctx context.Context, kv clientv3.KV) error {
  1705. op := clientv3.OpTxn(nil, []clientv3.Op{clientv3.OpGet("abc")}, nil)
  1706. _, err := kv.Do(ctx, op)
  1707. return err
  1708. },
  1709. }
  1710. for i := range tests {
  1711. t.Run(fmt.Sprintf("test %d", i), func(t *testing.T) {
  1712. defer testutil.AfterTest(t)
  1713. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  1714. defer clus.Terminate(t)
  1715. lkv, closeLKV, err := leasing.NewKV(clus.Client(0), "foo/", concurrency.WithTTL(1))
  1716. testutil.AssertNil(t, err)
  1717. defer closeLKV()
  1718. if _, err = lkv.Get(context.TODO(), "abc"); err != nil {
  1719. t.Fatal(err)
  1720. }
  1721. // down endpoint lkv uses for keepalives
  1722. clus.Members[0].Stop(t)
  1723. if err := waitForLeasingExpire(clus.Client(1), "foo/abc"); err != nil {
  1724. t.Fatal(err)
  1725. }
  1726. waitForExpireAck(t, lkv)
  1727. ctx, cancel := context.WithCancel(context.TODO())
  1728. errc := make(chan error, 1)
  1729. go func() { errc <- tests[i](ctx, lkv) }()
  1730. // some delay to get past for ctx.Err() != nil {} loops
  1731. time.Sleep(100 * time.Millisecond)
  1732. cancel()
  1733. select {
  1734. case err := <-errc:
  1735. if err != ctx.Err() {
  1736. t.Errorf("#%d: expected %v of server unavailable, got %v", i, ctx.Err(), err)
  1737. }
  1738. case <-time.After(5 * time.Second):
  1739. t.Errorf("#%d: timed out waiting for cancel", i)
  1740. }
  1741. clus.Members[0].Restart(t)
  1742. })
  1743. }
  1744. }
  1745. func waitForLeasingExpire(kv clientv3.KV, lkey string) error {
  1746. for {
  1747. time.Sleep(1 * time.Second)
  1748. resp, err := kv.Get(context.TODO(), lkey, clientv3.WithPrefix())
  1749. if err != nil {
  1750. return err
  1751. }
  1752. if len(resp.Kvs) == 0 {
  1753. // server expired the leasing key
  1754. return nil
  1755. }
  1756. }
  1757. }
  1758. func waitForExpireAck(t *testing.T, kv clientv3.KV) {
  1759. // wait for leasing client to acknowledge lost lease
  1760. for i := 0; i < 10; i++ {
  1761. ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
  1762. _, err := kv.Get(ctx, "abc")
  1763. cancel()
  1764. if err == ctx.Err() {
  1765. return
  1766. } else if err != nil {
  1767. t.Logf("current error: %v", err)
  1768. }
  1769. time.Sleep(time.Second)
  1770. }
  1771. t.Fatalf("waited too long to acknlowedge lease expiration")
  1772. }