KeepAlive: auto grant a new lease if 0 is given as lease id (#242)

Fixes #3037

Signed-off-by: Tao He <linzhu.ht@alibaba-inc.com>
This commit is contained in:
Tao He 2023-07-20 14:21:27 +08:00 committed by GitHub
parent 15c022e36c
commit 0eee75b52e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -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<SyncClient&>(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<SyncClient&>(client).leasegrant(ttl).value().lease();
}
stubs.reset(new EtcdServerStubs{});
stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel());

View File

@ -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::KeepAlive>(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();
}