2014-05-27 16:59:49 +00:00
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
|
|
#include <zkutil/ZooKeeper.h>
|
|
|
|
|
#include <Yandex/logger_useful.h>
|
|
|
|
|
#include <DB/Core/Exception.h>
|
|
|
|
|
|
|
|
|
|
namespace zkutil
|
|
|
|
|
{
|
|
|
|
|
class Lock
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
/// lock_prefix - относительный путь до блокировки в ZK. Начинается со слеша
|
|
|
|
|
/// lock_name - имя ноды блокировки в ZK
|
2014-12-26 10:40:49 +00:00
|
|
|
|
Lock(zkutil::ZooKeeperPtr zk, const std::string & lock_prefix_, const std::string & lock_name_, const std::string & lock_message_ = "",
|
|
|
|
|
bool create_parent_path = false) :
|
2014-08-13 13:41:08 +00:00
|
|
|
|
zookeeper(zk), lock_path(lock_prefix_ + "/" + lock_name_), lock_message(lock_message_), log(&Logger::get("zkutil::Lock"))
|
2014-05-27 16:59:49 +00:00
|
|
|
|
{
|
2014-12-26 10:40:49 +00:00
|
|
|
|
if (create_parent_path)
|
|
|
|
|
zookeeper->createAncestors(lock_prefix_);
|
|
|
|
|
|
2014-07-03 17:24:17 +00:00
|
|
|
|
zookeeper->createIfNotExists(lock_prefix_, "");
|
2014-05-27 16:59:49 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-26 10:40:49 +00:00
|
|
|
|
Lock(const Lock &) = delete;
|
|
|
|
|
Lock & operator=(const Lock &) = delete;
|
|
|
|
|
|
2014-05-27 16:59:49 +00:00
|
|
|
|
~Lock()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
unlock();
|
|
|
|
|
}
|
|
|
|
|
catch (const zkutil::KeeperException & e)
|
|
|
|
|
{
|
|
|
|
|
DB::tryLogCurrentException(__PRETTY_FUNCTION__);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
enum Status
|
|
|
|
|
{
|
|
|
|
|
UNLOCKED,
|
2014-07-03 17:24:17 +00:00
|
|
|
|
LOCKED_BY_ME,
|
|
|
|
|
LOCKED_BY_OTHER,
|
|
|
|
|
END
|
2014-05-27 16:59:49 +00:00
|
|
|
|
};
|
2014-07-03 17:24:17 +00:00
|
|
|
|
std::string status2String(Status status);
|
2014-05-27 16:59:49 +00:00
|
|
|
|
|
2014-07-03 17:24:17 +00:00
|
|
|
|
/// проверяет создана ли эфемерная нода и кто ее владелец.
|
2014-05-27 16:59:49 +00:00
|
|
|
|
/// если мы сами создавали эфемерную ноду, то надо вызывать этот метод, чтобы убедится,
|
|
|
|
|
/// что сессия с зукипером не порвалось
|
2014-07-03 17:24:17 +00:00
|
|
|
|
Status check();
|
2014-05-27 16:59:49 +00:00
|
|
|
|
|
2014-07-03 17:24:17 +00:00
|
|
|
|
void unlock();
|
2014-05-27 16:59:49 +00:00
|
|
|
|
|
2014-07-03 17:24:17 +00:00
|
|
|
|
bool tryLock();
|
2014-05-27 16:59:49 +00:00
|
|
|
|
|
|
|
|
|
/// путь к ноде блокировки в zookeeper
|
|
|
|
|
const std::string & getPath() { return lock_path; }
|
|
|
|
|
|
|
|
|
|
private:
|
2014-07-03 17:24:17 +00:00
|
|
|
|
Status checkImpl();
|
2014-05-27 16:59:49 +00:00
|
|
|
|
zkutil::ZooKeeperPtr zookeeper;
|
|
|
|
|
std::string lock_path;
|
2014-08-13 13:41:08 +00:00
|
|
|
|
std::string lock_message;
|
2014-05-27 16:59:49 +00:00
|
|
|
|
Logger * log;
|
|
|
|
|
bool locked = false;
|
|
|
|
|
};
|
|
|
|
|
}
|