2016-03-01 17:47:53 +00:00
|
|
|
#pragma once
|
|
|
|
|
2016-03-25 12:21:10 +00:00
|
|
|
#include <zkutil/Common.h>
|
2016-03-01 17:47:53 +00:00
|
|
|
#include <string>
|
|
|
|
#include <functional>
|
|
|
|
|
|
|
|
namespace zkutil
|
|
|
|
{
|
|
|
|
|
2016-09-01 09:58:56 +00:00
|
|
|
/// Implementation of a distributed single barrier for ZooKeeper.
|
|
|
|
/// Consider a barrier with N slots. A node that wants to enter this barrier
|
|
|
|
/// creates a uniquely identified token and puts it in a free slot, then waits
|
|
|
|
/// until all of the N slots have been taken.
|
|
|
|
/// This implementation allows entering a barrier more than once. This is done
|
|
|
|
/// by prefixing tokens with a tag which is an integer number representing the
|
|
|
|
/// number of times this barrier has already been crossed. When a node attempts
|
|
|
|
/// to puts its token into a slot, first it looks for lingering obsolete tokens,
|
|
|
|
/// then, if found, deletes them. If a node has put its token into the last free
|
|
|
|
/// slot, it increments the tag value.
|
2016-03-01 17:47:53 +00:00
|
|
|
class SingleBarrier final
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
using CancellationHook = std::function<void()>;
|
|
|
|
|
|
|
|
public:
|
2016-03-25 12:21:10 +00:00
|
|
|
SingleBarrier(GetZooKeeper get_zookeeper_, const std::string & path_, size_t counter_);
|
2016-03-01 17:47:53 +00:00
|
|
|
|
|
|
|
SingleBarrier(const SingleBarrier &) = delete;
|
|
|
|
SingleBarrier & operator=(const SingleBarrier &) = delete;
|
|
|
|
|
|
|
|
SingleBarrier(SingleBarrier &&) = default;
|
|
|
|
SingleBarrier & operator=(SingleBarrier &&) = default;
|
|
|
|
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Register a function that cancels barrier operations if requested.
|
2016-03-01 17:47:53 +00:00
|
|
|
void setCancellationHook(CancellationHook cancellation_hook_);
|
|
|
|
|
2016-10-26 22:27:38 +00:00
|
|
|
void enter(UInt64 timeout = 0);
|
2016-03-01 17:47:53 +00:00
|
|
|
|
|
|
|
private:
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Cancel any ongoing operation if requested. Additionally perform cleanup.
|
2016-03-01 17:47:53 +00:00
|
|
|
void abortIfRequested();
|
|
|
|
|
|
|
|
private:
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Helper that acquires an alive ZooKeeper session.
|
2016-03-25 12:21:10 +00:00
|
|
|
GetZooKeeper get_zookeeper;
|
2016-05-28 17:31:50 +00:00
|
|
|
EventPtr event = std::make_shared<Poco::Event>();
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Function that cancels barrier operations if requested.
|
2016-03-01 17:47:53 +00:00
|
|
|
CancellationHook cancellation_hook;
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Path to the barrier storage.
|
2016-03-01 17:47:53 +00:00
|
|
|
std::string path;
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Token created by the node attempting to enter the barrier.
|
2016-03-25 11:48:45 +00:00
|
|
|
std::string token;
|
2016-09-01 10:24:06 +00:00
|
|
|
/// Number of available slots.
|
2016-03-01 17:47:53 +00:00
|
|
|
size_t counter;
|
|
|
|
};
|
|
|
|
|
|
|
|
}
|