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)
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)
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)
346 auto ppromise = std::make_unique<promise<get_result>>();
347 auto rc = error_code_from_raw(::zoo_aget(_handle, path, 0, callback, ppromise.get()));
350 auto f = ppromise->get_future();
357 return ppromise->get_future();
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)
440 auto ppromise = std::make_unique<promise<get_children_result>>();
441 auto rc = error_code_from_raw(::zoo_aget_children2(_handle,
450 auto f = ppromise->get_future();
457 return ppromise->get_future();
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)
536 auto ppromise = std::make_unique<promise<exists_result>>();
537 auto rc = error_code_from_raw(::zoo_aexists(_handle, path, 0, callback, ppromise.get()));
540 auto f = ppromise->get_future();
547 return ppromise->get_future();
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)
622 auto ppromise = std::make_unique<promise<create_result>>();
623 auto rc = with_acl(rules, [&] (ptr<const ACL_vector> rules)
625 return error_code_from_raw(::zoo_acreate(_handle,
630 static_cast<int>(mode),
638 auto f = ppromise->get_future();
645 return ppromise->get_future();
650 future<set_result> connection_zk::set(string_view path,
const buffer& data, version
check)
652 ::stat_completion_t callback =
653 [] (
int rc_in, ptr<const struct Stat> stat_raw, ptr<const void> prom_in)
655 std::unique_ptr<promise<set_result>> prom((
ptr<promise<set_result>>) prom_in);
656 auto rc = error_code_from_raw(rc_in);
658 prom->set_value(set_result(stat_from_raw(*stat_raw)));
663 return with_str(path, [&] (ptr<const char> path)
665 auto ppromise = std::make_unique<promise<set_result>>();
666 auto rc = error_code_from_raw(::zoo_aset(_handle,
676 auto f = ppromise->get_future();
683 return ppromise->get_future();
688 future<void> connection_zk::erase(string_view path, version check)
690 ::void_completion_t callback =
691 [] (
int rc_in, ptr<const void> prom_in)
693 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
694 auto rc = error_code_from_raw(rc_in);
701 return with_str(path, [&] (ptr<const char> path)
703 auto ppromise = std::make_unique<promise<void>>();
704 auto rc = error_code_from_raw(::zoo_adelete(_handle, path, check.value, callback, ppromise.get()));
707 auto f = ppromise->get_future();
714 return ppromise->get_future();
719 future<get_acl_result> connection_zk::get_acl(string_view path)
const
721 ::acl_completion_t callback =
722 [] (
int rc_in, ptr<struct ACL_vector> acl_raw, ptr<struct Stat> stat_raw, ptr<const void> prom_in) noexcept
724 std::unique_ptr<promise<get_acl_result>> prom((
ptr<promise<get_acl_result>>) prom_in);
725 auto rc = error_code_from_raw(rc_in);
727 prom->set_value(get_acl_result(acl_from_raw(*acl_raw), stat_from_raw(*stat_raw)));
732 return with_str(path, [&] (ptr<const char> path)
734 auto ppromise = std::make_unique<promise<get_acl_result>>();
735 auto rc = error_code_from_raw(::zoo_aget_acl(_handle, path, callback, ppromise.get()));
738 auto f = ppromise->get_future();
745 return ppromise->get_future();
750 future<void> connection_zk::set_acl(string_view path,
const acl& rules, acl_version check)
752 ::void_completion_t callback =
753 [] (
int rc_in, ptr<const void> prom_in)
755 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
756 auto rc = error_code_from_raw(rc_in);
763 return with_str(path, [&] (ptr<const char> path)
765 return with_acl(rules, [&] (ptr<struct ACL_vector> rules)
767 auto ppromise = std::make_unique<promise<void>>();
768 auto rc = error_code_from_raw(::zoo_aset_acl(_handle,
778 auto f = ppromise->get_future();
785 return ppromise->get_future();
794 promise<multi_result> prom;
795 std::vector<zoo_op_result_t> raw_results;
796 std::map<std::size_t, Stat> raw_stats;
797 std::map<std::size_t, std::vector<char>> path_buffers;
800 source_txn(std::move(src)),
801 raw_results(source_txn.size())
803 for (zoo_op_result_t& x : raw_results)
809 return &raw_stats[idx];
816 path_buffers[idx] = std::vector<char>(sz);
817 return &path_buffers[idx];
827 out.
reserve(raw_results.size());
828 for (std::size_t idx = 0; idx < source_txn.
size(); ++idx)
830 const auto& raw_res = raw_results[idx];
832 switch (source_txn[idx].type())
846 prom.set_value(std::move(out));
851 auto iter = std::partition_point(raw_results.begin(), raw_results.end(),
852 [] (
auto res) {
return res.err == 0; }
859 prom.set_exception(std::current_exception());
864 future<multi_result> connection_zk::commit(
multi_op&& txn_in)
866 ::void_completion_t callback =
869 std::unique_ptr<connection_zk_commit_completer>
871 completer->deliver(error_code_from_raw(rc_in));
874 auto pcompleter = std::make_unique<connection_zk_commit_completer>(std::move(txn_in));
875 auto& txn = pcompleter->source_txn;
878 ::zoo_op raw_ops[txn.size()];
879 std::size_t create_op_count = 0;
880 std::size_t acl_piece_count = 0;
881 for (
const auto& tx : txn)
886 acl_piece_count += tx.as_create().rules.size();
889 ACL_vector encoded_acls[create_op_count];
890 ACL acl_pieces[acl_piece_count];
891 ptr<ACL_vector> encoded_acl_iter = encoded_acls;
892 ptr<ACL> acl_piece_iter = acl_pieces;
894 for (std::size_t idx = 0; idx < txn.size(); ++idx)
896 auto& raw_op = raw_ops[idx];
897 auto& src_op = txn[idx];
898 switch (src_op.type())
901 zoo_check_op_init(&raw_op, src_op.as_check().path.c_str(), src_op.as_check().check.value);
905 const auto& cdata = src_op.as_create();
906 encoded_acl_iter->count = int(cdata.rules.size());
907 encoded_acl_iter->data = acl_piece_iter;
908 for (
const auto& acl : cdata.rules)
910 *acl_piece_iter = encode_acl_part(acl);
914 auto path_buf_ref = pcompleter->path_buffer_for(idx, cdata.path, cdata.mode);
915 zoo_create_op_init(&raw_op,
918 int(cdata.data.size()),
920 static_cast<int>(cdata.mode),
921 path_buf_ref->data(),
922 int(path_buf_ref->size())
928 zoo_delete_op_init(&raw_op, src_op.as_erase().path.c_str(), src_op.as_erase().check.value);
932 const auto& setting = src_op.as_set();
933 zoo_set_op_init(&raw_op,
934 setting.path.c_str(),
936 int(setting.data.size()),
938 pcompleter->raw_stat_at(idx)
944 using std::to_string;
945 throw std::invalid_argument(
"Invalid op_type at index=" + to_string(idx) +
": "
946 + to_string(src_op.type())
951 auto rc = error_code_from_raw(::zoo_amulti(_handle,
954 pcompleter->raw_results.data(),
961 auto f = pcompleter->prom.get_future();
962 pcompleter.release();
968 return pcompleter->prom.get_future();
973 pcompleter->prom.set_exception(std::current_exception());
974 return pcompleter->prom.get_future();
978 future<void> connection_zk::load_fence()
980 ::string_completion_t callback =
981 [] (
int rc_in, ptr<const char>, ptr<const void> prom_in)
983 std::unique_ptr<promise<void>> prom((
ptr<promise<void>>) prom_in);
984 auto rc = error_code_from_raw(rc_in);
991 auto ppromise = std::make_unique<std::promise<void>>();
992 auto rc = error_code_from_raw(::zoo_async(_handle,
"/", callback, ppromise.get()));
995 auto f = ppromise->get_future();
1002 return ppromise->get_future();
1006 void connection_zk::on_session_event_raw(ptr<zhandle_t> handle [[gnu::unused]],
1009 ptr<const char> path_ptr,
1010 ptr<void> watcher_ctx
1013 auto self =
static_cast<ptr<connection_zk>
>(watcher_ctx);
1017 assert(self->_handle ==
nullptr || self->_handle == handle);
1018 auto ev = event_from_raw(ev_type);
1019 auto st = state_from_raw(
state);
1020 auto path = string_view(path_ptr);
1025 std::cerr <<
"WARNING: Got unexpected event " << ev <<
" in state=" << st <<
" with path=" << path << std::endl;
1028 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.