From 0eee75b52ef8c4b0a1be4bb69f0ffa9f4b849149 Mon Sep 17 00:00:00 2001 From: Tao He Date: Thu, 20 Jul 2023 14:21:27 +0800 Subject: [PATCH] KeepAlive: auto grant a new lease if 0 is given as lease id (#242) Fixes #3037 Signed-off-by: Tao He --- src/KeepAlive.cpp | 8 ++++++++ tst/KeepAliveTest.cpp | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/KeepAlive.cpp b/src/KeepAlive.cpp index c2d39f6..23a1232 100644 --- a/src/KeepAlive.cpp +++ b/src/KeepAlive.cpp @@ -28,6 +28,10 @@ etcd::KeepAlive::KeepAlive(SyncClient const& client, int ttl, int64_t lease_id) lease_id(lease_id), continue_next(true), grpc_timeout(client.get_grpc_timeout()) { + if (ttl > 0 && lease_id == 0) { + this->lease_id = + const_cast(client).leasegrant(ttl).value().lease(); + } stubs.reset(new EtcdServerStubs{}); stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel()); @@ -79,6 +83,10 @@ etcd::KeepAlive::KeepAlive( lease_id(lease_id), continue_next(true), grpc_timeout(client.get_grpc_timeout()) { + if (ttl > 0 && lease_id == 0) { + this->lease_id = + const_cast(client).leasegrant(ttl).value().lease(); + } stubs.reset(new EtcdServerStubs{}); stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel()); diff --git a/tst/KeepAliveTest.cpp b/tst/KeepAliveTest.cpp index dbeea68..f112b0d 100644 --- a/tst/KeepAliveTest.cpp +++ b/tst/KeepAliveTest.cpp @@ -60,3 +60,16 @@ TEST_CASE("keepalive won't expire") { etcd::KeepAlive keepalive(etcd, handler, ttl, lease_id); std::this_thread::sleep_for(std::chrono::seconds(5)); } + +TEST_CASE("keepalive auto-grant") { + etcd::Client etcd(etcd_uri); + + // create a lease without pre-granted lease id + auto keepalive = std::make_shared(etcd, 10 /* ttl */); + auto lease_id = keepalive->Lease(); + REQUIRE(lease_id != 0); + + // sleep for a while, and cancel + std::this_thread::sleep_for(std::chrono::seconds(5)); + keepalive->Cancel(); +}