aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/ZooKeeper/ZooKeeperCachingGetter.cpp
blob: 6577cc4ac958cba751b3a02945546a3277800b26 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <Common/ZooKeeper/ZooKeeperCachingGetter.h>

namespace DB
{

namespace ErrorCodes
{
    extern const int NO_ZOOKEEPER;
}

}

namespace zkutil
{

ZooKeeperCachingGetter::ZooKeeperCachingGetter(zkutil::GetZooKeeper get_zookeeper_) : get_zookeeper{get_zookeeper_}
{
}


void ZooKeeperCachingGetter::resetCache()
{
    std::lock_guard lock{cached_zookeeper_ptr_mutex};
    cached_zookeeper_ptr = nullptr;
}


std::pair<zkutil::ZooKeeperPtr, ZooKeeperCachingGetter::SessionStatus> ZooKeeperCachingGetter::getZooKeeper()
{
    std::lock_guard lock{cached_zookeeper_ptr_mutex};
    return getZooKeeperNoLock();
}


std::pair<zkutil::ZooKeeperPtr, ZooKeeperCachingGetter::SessionStatus> ZooKeeperCachingGetter::getZooKeeperNoLock()
{
    if (!cached_zookeeper_ptr || cached_zookeeper_ptr->expired())
    {
        auto zookeeper = get_zookeeper();
        if (!zookeeper)
            throw DB::Exception(DB::ErrorCodes::NO_ZOOKEEPER, "Can't get ZooKeeper session");

        cached_zookeeper_ptr = zookeeper;
        return {zookeeper, ZooKeeperCachingGetter::SessionStatus::New};
    }
    return {cached_zookeeper_ptr, ZooKeeperCachingGetter::SessionStatus::Cached};
}

}