1 #include "connection_zk.hpp"
13 #include <system_error>
16 #include <zookeeper/zookeeper.h>
31 template <
typename FAction>
32 auto with_str(string_view src, FAction&& action) noexcept(noexcept(std::forward<FAction>(action)(
ptr<const
char>())))
33 -> decltype(std::forward<FAction>(action)(
ptr<const
char>()))
35 char buffer[src.size() + 1];
36 buffer[src.size()] =
'\0';
37 std::memcpy(buffer, src.data(), src.size());
38 return std::forward<FAction>(action)(buffer);
41 static ACL encode_acl_part(
const acl_rule& src)
44 out.perms =
static_cast<int>(src.permissions());
45 out.id.scheme =
const_cast<ptr<char>
>(src.scheme().c_str());
46 out.id.id =
const_cast<ptr<char>
>(src.id().c_str());
50 template <
typename FAction>
51 auto with_acl(
const acl& rules, FAction&& action) noexcept(noexcept(std::forward<FAction>(action)(
ptr<ACL_vector>())))
52 -> decltype(std::forward<FAction>(action)(
ptr<ACL_vector>()))
54 ACL parts[rules.size()];
55 for (std::size_t idx = 0; idx < rules.size(); ++idx)
56 parts[idx] = encode_acl_part(rules[idx]);
59 vec.count = int(rules.size());
61 return std::forward<FAction>(action)(&vec);
72 case ZOPERATIONTIMEOUT:
73 raw = ZCONNECTIONLOSS;
75 case ZINVALIDCALLBACK:
80 raw = ZCONNECTIONLOSS;
94 #if ZOO_MAJOR_VERSION <= 3 && ZOO_MINOR_VERSION <= 4
95 static const int ZOO_NOTCONNECTED_STATE = 999;
98 static state state_from_raw(
int raw)
108 if (raw == ZOO_NOTCONNECTED_STATE)
110 raw = ZOO_CONNECTING_STATE;
115 else if (raw == ZOO_ASSOCIATING_STATE)
117 raw = ZOO_CONNECTING_STATE;
120 return static_cast<state>(raw);
123 static stat stat_from_raw(
const struct Stat& raw)
127 out.child_modified_transaction = transaction_id(raw.pzxid);
128 out.child_version = child_version(raw.cversion);
129 out.children_count = raw.numChildren;
130 out.create_time = stat::time_point() + std::chrono::milliseconds(raw.ctime);
131 out.create_transaction = transaction_id(raw.czxid);
132 out.data_size = raw.dataLength;
133 out.data_version = version(raw.version);
134 out.ephemeral_owner = raw.ephemeralOwner;
135 out.modified_time = stat::time_point() + std::chrono::milliseconds(raw.mtime);
136 out.modified_transaction = transaction_id(raw.mzxid);
140 static std::vector<std::string> string_vector_from_raw(
const struct String_vector& raw)
142 std::vector<std::string> out;
143 out.reserve(raw.count);
144 for (std::int32_t idx = 0; idx < raw.count; ++idx)
145 out.emplace_back(raw.data[idx]);
149 static acl acl_from_raw(
const struct ACL_vector& raw)
151 auto sz = std::size_t(raw.count);
155 for (std::size_t idx = 0; idx < sz; ++idx)
157 const auto& item = raw.data[idx];
158 out.emplace_back(item.id.scheme, item.id.id, static_cast<permission>(item.perms));
167 connection_zk::connection_zk(
const connection_params& params) :
170 if (params.connection_schema() !=
"zk")
171 throw std::invalid_argument(std::string(
"Invalid connection string \"") + to_string(params) +
"\"");
173 auto conn_string = [&] ()
175 std::ostringstream os;
177 for (
const auto& host : params.hosts())
189 _handle = ::zookeeper_init(conn_string.c_str(),
190 on_session_event_raw,
191 static_cast<int>(params.timeout().count()),
198 std::system_error(errno, std::system_category(),
"Failed to create ZooKeeper client");
201 connection_zk::~connection_zk() noexcept
210 _event_delivered(
false)
215 virtual void deliver_event(
event ev)
217 if (!_event_delivered.exchange(
true, std::memory_order_relaxed))
219 _event_promise.set_value(std::move(ev));
223 future<event> get_event_future()
225 return _event_promise.get_future();
229 std::atomic<bool> _event_delivered;
230 promise<event> _event_promise;
233 template <
typename TResult>
239 _data_delivered(
false)
242 future<TResult> get_data_future()
244 return _data_promise.get_future();
247 virtual void deliver_event(
event ev)
override
249 if (!_data_delivered.load(std::memory_order_relaxed))
254 watcher::deliver_event(std::move(ev));
257 void deliver_data(optional<TResult> data, std::exception_ptr ex_ptr)
259 if (!_data_delivered.exchange(
true, std::memory_order_relaxed))
263 _data_promise.set_exception(std::move(ex_ptr));
267 _data_promise.set_value(std::move(*data));
273 std::atomic<bool> _data_delivered;
274 promise<TResult> _data_promise;
277 std::shared_ptr<connection_zk::watcher> connection_zk::try_extract_watch(
ptr<const void> addr)
279 std::unique_lock<std::mutex> ax(_watches_protect);
280 auto iter = _watches.find(addr);
281 if (iter != _watches.end())
282 return _watches.extract(iter).mapped();
292 void connection_zk::deliver_watch(ptr<zhandle_t> zh,
295 ptr<const char> path [[gnu::unused]],
299 auto&
self = *connection_from_context(zh);
300 if (
auto watcher =
self.try_extract_watch(proms_in))
301 watcher->deliver_event(event(event_from_raw(type_in), state_from_raw(state_in)));
304 void connection_zk::close()
308 auto err = error_code_from_raw(::zookeeper_close(_handle));
315 std::unique_lock<std::mutex> ax(_watches_protect);
316 auto l_watches = std::move(_watches);
318 for (
const auto& pair : l_watches)
326 return state_from_raw(::zoo_state(_handle));
331 future<get_result> connection_zk::get(string_view path)
333 ::data_completion_t callback =
334 [] (
int rc_in, ptr<const char> data,
int data_sz, ptr<const struct Stat> pstat, ptr<const void> prom_in) noexcept
336 std::unique_ptr<promise<get_result>> prom((
ptr<promise<get_result>>) prom_in);
337 auto rc = error_code_from_raw(rc_in);
339 prom->set_value(get_result(
buffer(data, data + data_sz), stat_from_raw(*pstat)));
344 return with_str(path, [&] (ptr<const char> path) noexcept
346 auto ppromise = std::make_unique<promise<get_result>>();
347 auto fut = ppromise->get_future();
348 auto rc = error_code_from_raw(::zoo_aget(_handle, path, 0, callback, ppromise.get()));
366 static void deliver_raw(
int rc_in,
374 auto rc = error_code_from_raw(rc_in);
379 self.get_event_future()
391 future<watch_result> connection_zk::watch(string_view path)
395 std::unique_lock<std::mutex> ax(_watches_protect);
396 auto watcher = std::make_shared<data_watcher>();
397 auto rc = error_code_from_raw(::zoo_awget(_handle,
401 data_watcher::deliver_raw,
410 return watcher->get_data_future();
414 future<get_children_result> connection_zk::get_children(string_view path)
416 ::strings_stat_completion_t callback =
418 ptr<const struct String_vector> strings_in,
419 ptr<const struct Stat> stat_in,
420 ptr<const void> prom_in
423 std::unique_ptr<promise<get_children_result>> prom((
ptr<promise<get_children_result>>) prom_in);
424 auto rc = error_code_from_raw(rc_in);
430 prom->set_value(get_children_result(string_vector_from_raw(*strings_in), stat_from_raw(*stat_in)));
434 prom->set_exception(std::current_exception());
438 return with_str(path, [&] (ptr<const char> path) noexcept
440 auto ppromise = std::make_unique<promise<get_children_result>>();
441 auto fut = ppromise->get_future();
442 auto rc = error_code_from_raw(::zoo_aget_children2(_handle,
466 static void deliver_raw(
int rc_in,
473 auto rc = error_code_from_raw(rc_in);
481 stat_from_raw(*stat_in)
483 self.get_event_future()
490 self.deliver_data(nullopt, std::current_exception());
496 future<watch_children_result> connection_zk::watch_children(string_view path)
500 std::unique_lock<std::mutex> ax(_watches_protect);
501 auto watcher = std::make_shared<child_watcher>();
502 auto rc = error_code_from_raw(::zoo_awget_children2(_handle,
506 child_watcher::deliver_raw,
515 return watcher->get_data_future();
519 future<exists_result> connection_zk::exists(string_view path)
521 ::stat_completion_t callback =
522 [] (
int rc_in, ptr<const struct Stat> stat_in, ptr<const void> prom_in)
524 std::unique_ptr<promise<exists_result>> prom((
ptr<promise<exists_result>>) prom_in);
525 auto rc = error_code_from_raw(rc_in);
527 prom->set_value(exists_result(stat_from_raw(*stat_in)));
529 prom->set_value(exists_result(nullopt));
534 return with_str(path, [&] (ptr<const char> path) noexcept
536 auto ppromise = std::make_unique<promise<exists_result>>();
537 auto fut = ppromise->get_future();
538 auto rc = error_code_from_raw(::zoo_aexists(_handle, path, 0, callback, ppromise.get()));
559 auto rc = error_code_from_raw(rc_in);
580 future<watch_exists_result> connection_zk::watch_exists(string_view path)
584 std::unique_lock<std::mutex> ax(_watches_protect);
585 auto watcher = std::make_shared<exists_watcher>();
586 auto rc = error_code_from_raw(::zoo_awexists(_handle,
590 exists_watcher::deliver_raw,
599 return watcher->get_data_future();
603 future<create_result> connection_zk::create(string_view path,
609 ::string_completion_t callback =
610 [] (
int rc_in, ptr<const char> name_in, ptr<const void> prom_in)
612 std::unique_ptr<promise<create_result>> prom((
ptr<promise<create_result>>) prom_in);
613 auto rc = error_code_from_raw(rc_in);
615 prom->set_value(create_result(std::string(name_in)));
620 return with_str(path, [&] (ptr<const char> path) noexcept
622 auto ppromise = std::make_unique<promise<create_result>>();
623 auto fut = ppromise->get_future();
624 auto rc = with_acl(rules, [&] (ptr<const ACL_vector> rules) noexcept
626 return error_code_from_raw(::zoo_acreate(_handle,
631 static_cast<int>(mode),
651 future<set_result> connection_zk::set(string_view path,
const buffer& data, version
check)
653 ::stat_completion_t callback =
654 [] (
int rc_in, ptr<const struct Stat> stat_raw, ptr<const void> prom_in)
656 std::unique_ptr<promise<set_result>> prom((
ptr<promise<set_result>>) prom_in);
657 auto rc = error_code_from_raw(rc_in);
659 prom->set_value(set_result(stat_from_raw(*stat_raw)));
664 return with_str(path, [&] (ptr<const char> path) noexcept
666 auto ppromise = std::make_unique<promise<set_result>>();
667 auto fut = ppromise->get_future();
668 auto rc = error_code_from_raw(::zoo_aset(_handle,
690 future<void> connection_zk::erase(string_view path, version check)
692 ::void_completion_t callback =
693 [] (
int rc_in, ptr<const void> prom_in)
695 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
696 auto rc = error_code_from_raw(rc_in);
703 return with_str(path, [&] (ptr<const char> path) noexcept
705 auto ppromise = std::make_unique<promise<void>>();
706 auto fut = ppromise->get_future();
707 auto rc = error_code_from_raw(::zoo_adelete(_handle, path, check.value, callback, ppromise.get()));
721 future<get_acl_result> connection_zk::get_acl(string_view path)
const
723 ::acl_completion_t callback =
724 [] (
int rc_in, ptr<struct ACL_vector> acl_raw, ptr<struct Stat> stat_raw, ptr<const void> prom_in) noexcept
726 std::unique_ptr<promise<get_acl_result>> prom((
ptr<promise<get_acl_result>>) prom_in);
727 auto rc = error_code_from_raw(rc_in);
729 prom->set_value(get_acl_result(acl_from_raw(*acl_raw), stat_from_raw(*stat_raw)));
734 return with_str(path, [&] (ptr<const char> path) noexcept
736 auto ppromise = std::make_unique<promise<get_acl_result>>();
737 auto fut = ppromise->get_future();
738 auto rc = error_code_from_raw(::zoo_aget_acl(_handle, path, callback, ppromise.get()));
752 future<void> connection_zk::set_acl(string_view path,
const acl& rules, acl_version check)
754 ::void_completion_t callback =
755 [] (
int rc_in, ptr<const void> prom_in)
757 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
758 auto rc = error_code_from_raw(rc_in);
765 return with_str(path, [&] (ptr<const char> path) noexcept
767 return with_acl(rules, [&] (ptr<struct ACL_vector> rules) noexcept
769 auto ppromise = std::make_unique<promise<void>>();
770 auto fut = ppromise->get_future();
771 auto rc = error_code_from_raw(::zoo_aset_acl(_handle,
796 promise<multi_result> prom;
797 std::vector<zoo_op_result_t> raw_results;
798 std::map<std::size_t, Stat> raw_stats;
799 std::map<std::size_t, std::vector<char>> path_buffers;
802 source_txn(std::move(src)),
803 raw_results(source_txn.size())
805 for (zoo_op_result_t& x : raw_results)
811 return &raw_stats[idx];
818 path_buffers[idx] = std::vector<char>(sz);
819 return &path_buffers[idx];
829 out.
reserve(raw_results.size());
830 for (std::size_t idx = 0; idx < source_txn.
size(); ++idx)
832 const auto& raw_res = raw_results[idx];
834 switch (source_txn[idx].type())
848 prom.set_value(std::move(out));
853 auto iter = std::partition_point(raw_results.begin(), raw_results.end(),
854 [] (
auto res) {
return res.err == 0; }
861 prom.set_exception(std::current_exception());
866 future<multi_result> connection_zk::commit(
multi_op&& txn_in)
868 ::void_completion_t callback =
871 std::unique_ptr<connection_zk_commit_completer>
873 completer->deliver(error_code_from_raw(rc_in));
876 auto pcompleter = std::make_unique<connection_zk_commit_completer>(std::move(txn_in));
877 auto& txn = pcompleter->source_txn;
880 ::zoo_op raw_ops[txn.size()];
881 std::size_t create_op_count = 0;
882 std::size_t acl_piece_count = 0;
883 for (
const auto& tx : txn)
888 acl_piece_count += tx.as_create().rules.size();
891 ACL_vector encoded_acls[create_op_count];
892 ACL acl_pieces[acl_piece_count];
893 ptr<ACL_vector> encoded_acl_iter = encoded_acls;
894 ptr<ACL> acl_piece_iter = acl_pieces;
896 for (std::size_t idx = 0; idx < txn.size(); ++idx)
898 auto& raw_op = raw_ops[idx];
899 auto& src_op = txn[idx];
900 switch (src_op.type())
903 zoo_check_op_init(&raw_op, src_op.as_check().path.c_str(), src_op.as_check().check.value);
907 const auto& cdata = src_op.as_create();
908 encoded_acl_iter->count = int(cdata.rules.size());
909 encoded_acl_iter->data = acl_piece_iter;
910 for (
const auto& acl : cdata.rules)
912 *acl_piece_iter = encode_acl_part(acl);
916 auto path_buf_ref = pcompleter->path_buffer_for(idx, cdata.path, cdata.mode);
917 zoo_create_op_init(&raw_op,
920 int(cdata.data.size()),
922 static_cast<int>(cdata.mode),
923 path_buf_ref->data(),
924 int(path_buf_ref->size())
930 zoo_delete_op_init(&raw_op, src_op.as_erase().path.c_str(), src_op.as_erase().check.value);
934 const auto& setting = src_op.as_set();
935 zoo_set_op_init(&raw_op,
936 setting.path.c_str(),
938 int(setting.data.size()),
940 pcompleter->raw_stat_at(idx)
946 using std::to_string;
947 throw std::invalid_argument(
"Invalid op_type at index=" + to_string(idx) +
": "
948 + to_string(src_op.type())
953 auto fut = pcompleter->prom.get_future();
954 auto rc = error_code_from_raw(::zoo_amulti(_handle,
957 pcompleter->raw_results.data(),
964 pcompleter.release();
970 return pcompleter->prom.get_future();
975 pcompleter->prom.set_exception(std::current_exception());
976 return pcompleter->prom.get_future();
980 future<void> connection_zk::load_fence()
982 ::string_completion_t callback =
983 [] (
int rc_in, ptr<const char>, ptr<const void> prom_in)
985 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
986 auto rc = error_code_from_raw(rc_in);
993 auto ppromise = std::make_unique<std::promise<void>>();
994 auto rc = error_code_from_raw(::zoo_async(_handle,
"/", callback, ppromise.get()));
997 auto f = ppromise->get_future();
1004 return ppromise->get_future();
1008 void connection_zk::on_session_event_raw(ptr<zhandle_t> handle [[gnu::unused]],
1011 ptr<const char> path_ptr,
1012 ptr<void> watcher_ctx
1015 auto self =
static_cast<ptr<connection_zk>
>(watcher_ctx);
1019 assert(self->_handle ==
nullptr || self->_handle == handle);
1020 auto ev = event_from_raw(ev_type);
1021 auto st = state_from_raw(
state);
1022 auto path = string_view(path_ptr);
1027 std::cerr <<
"WARNING: Got unexpected event " << ev <<
" in state=" << st <<
" with path=" << path << std::endl;
1030 self->on_session_event(st);
Data delivered when a watched event triggers.
T * ptr
A simple, unowned pointer.
This value is issued as part of an event when the state changes.
Describes the various result types of client operations.
Code for transaction_failed.
constexpr bool is_set(create_mode self, create_mode flags)
Check that self has flags set.
The client is not connected to any server in the ensemble.
state
Enumeration of states the client may be at when a watch triggers.
The result type of client::watch_exists.
size_type size() const
The number of operations in this transaction bundle.
The result type of client::create.
The result type of client::exists.
std::exception_ptr get_exception_ptr_of(error_code code)
Get an std::exception_ptr containing an exception with the proper type for the given code...
The result type of client::watch.
create_mode
When used in client::set, this value determines how the entry is created on the server.
The result type of client::watch_children.
void reserve(size_type capacity)
Increase the reserved memory block so it can store at least capacity results without reallocating...
void throw_error(error_code code)
Throw an exception for the given code.
A collection of operations that will be performed atomically.
The result type of client::set.
event_type
Enumeration of types of events that may occur.
The name of the entry will be appended with a monotonically increasing number.
The result type of client::get_children.
The result of a successful client::commit operation.
ZKPP_BUFFER_TYPE buffer
The buffer type.
The result type of client::get.
void emplace_back(TArgs &&...args)
Construct a result emplace on the end of the list using args.
zk::acl_version acl_version
The number of changes to the ACL of the entry.
error_code
Code for all error types thrown by the client library.