Format source code using clformat (#233)

Signed-off-by: Tao He <sighingnow@gmail.com>
This commit is contained in:
Tao He 2023-07-01 20:49:16 +08:00 committed by GitHub
parent fe9f17e61e
commit 1d5128a7e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 4914 additions and 4914 deletions

15
.clang-format Normal file
View File

@ -0,0 +1,15 @@
BasedOnStyle: Google
DerivePointerAlignment: false
PointerAlignment: Left
Cpp11BracedListStyle: true
IndentCaseLabels: false
AllowShortBlocksOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
Standard: 'Cpp11'
SpaceAfterCStyleCast: true
AlignAfterOpenBracket: Align
SortIncludes: true
IncludeBlocks: Preserve
ForEachMacros:
- BOOST_FOREACH

View File

@ -82,6 +82,10 @@ jobs:
wget https://github.com/Kitware/CMake/releases/download/v3.19.3/cmake-3.19.3-Linux-x86_64.sh wget https://github.com/Kitware/CMake/releases/download/v3.19.3/cmake-3.19.3-Linux-x86_64.sh
sudo bash cmake-3.19.3-Linux-x86_64.sh --prefix /usr --skip-license sudo bash cmake-3.19.3-Linux-x86_64.sh --prefix /usr --skip-license
# install clang-format
sudo curl -L https://github.com/muttleyxd/clang-tools-static-binaries/releases/download/master-1d7ec53d/clang-format-11_linux-amd64 --output /usr/bin/clang-format
sudo chmod +x /usr/bin/clang-format
- name: Install grpc v1.27.x for Ubuntu 18.04 - name: Install grpc v1.27.x for Ubuntu 18.04
if: matrix.os == 'ubuntu-18.04' if: matrix.os == 'ubuntu-18.04'
run: | run: |
@ -170,7 +174,7 @@ jobs:
if: false if: false
uses: mxschmitt/action-tmate@v3 uses: mxschmitt/action-tmate@v3
- name: Build - name: CMake
run: | run: |
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/lib/x86_64-linux-gnu export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/lib/x86_64-linux-gnu
@ -182,6 +186,42 @@ jobs:
-DBUILD_ETCD_TESTS=ON \ -DBUILD_ETCD_TESTS=ON \
-DCMAKE_C_COMPILER_LAUNCHER=ccache \ -DCMAKE_C_COMPILER_LAUNCHER=ccache \
-DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
- name: Format
if: runner.os == 'Linux'
run: |
cd build
function prepend() { while read line; do echo "${1}${line}"; done; }
make etcd_cpp_apiv3_clformat
GIT_DIFF=$(git diff --ignore-submodules)
if [[ -n $GIT_DIFF ]]; then
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo "| clang-format failures found!"
echo "|"
echo "$GIT_DIFF" | prepend "| "
echo "|"
echo "| Run: "
echo "|"
echo "| make etcd_cpp_apiv3_clformat"
echo "|"
echo "| to fix this error."
echo "|"
echo "| Ensure you are working with clang-format-11, which can be obtained from"
echo "|"
echo "| https://github.com/muttleyxd/clang-tools-static-binaries/releases "
echo "|"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
exit -1
fi
- name: Build
run: |
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/lib/x86_64-linux-gnu
cd build
make -j`nproc` make -j`nproc`
sudo make install sudo make install

View File

@ -223,6 +223,17 @@ install(EXPORT etcd-targets
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/etcd-cpp-api DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/etcd-cpp-api
) )
file(GLOB_RECURSE FILES_NEED_FORMAT
"etcd/*.hpp"
"src/*.cpp"
"tst/*.cpp"
)
add_custom_target(etcd_cpp_apiv3_clformat
COMMAND clang-format --style=file -i ${FILES_NEED_FORMAT}
COMMENT "Running clang-format, using clang-format-11 from https://github.com/muttleyxd/clang-tools-static-binaries/releases"
VERBATIM)
# deb/rpc packaging for Linux # deb/rpc packaging for Linux
set(CPACK_PACKAGE_NAME ${CMAKE_PROJECT_NAME}) set(CPACK_PACKAGE_NAME ${CMAKE_PROJECT_NAME})

View File

@ -14,24 +14,24 @@
#include "etcd/SyncClient.hpp" #include "etcd/SyncClient.hpp"
#include "etcd/v3/action_constants.hpp" #include "etcd/v3/action_constants.hpp"
namespace etcd namespace etcd {
{
/** /**
* Client is responsible for maintaining a connection towards an etcd server. * Client is responsible for maintaining a connection towards an etcd server.
* Etcd operations can be reached via the methods of the client. * Etcd operations can be reached via the methods of the client.
*/ */
class Client class Client {
{
public: public:
/** /**
* Constructs an async etcd client object from an established synchronous client. * Constructs an async etcd client object from an established synchronous
* client.
* *
* @param sync_client The synchronous client to use for the async client. * @param sync_client The synchronous client to use for the async client.
*/ */
Client(SyncClient* client); Client(SyncClient* client);
/** /**
* Constructs an async etcd client object from an established synchronous client. * Constructs an async etcd client object from an established synchronous
* client.
* *
* @param sync_client The synchronous client to use for the async client. * @param sync_client The synchronous client to use for the async client.
*/ */
@ -40,9 +40,10 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
Client(std::string const& etcd_url, Client(std::string const& etcd_url,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
@ -50,8 +51,8 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
Client(std::string const& etcd_url, Client(std::string const& etcd_url,
@ -65,9 +66,10 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
static Client* WithUrl(std::string const& etcd_url, static Client* WithUrl(std::string const& etcd_url,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
@ -75,8 +77,8 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
static Client* WithUrl(std::string const& etcd_url, static Client* WithUrl(std::string const& etcd_url,
@ -90,34 +92,32 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * round_robin/pick_first/grpclb/xds.
* @param auth_token_ttl TTL seconds for auth token, see also
* `--auth-token-ttl` flags of etcd.
*/ */
Client(std::string const & etcd_url, Client(std::string const& etcd_url, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl = 300,
std::string const & password,
int const auth_token_ttl = 300,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * @param auth_token_ttl TTL seconds for auth token, see also
* Default value should be 300. * `--auth-token-ttl` flags of etcd. Default value should be 300.
*/ */
Client(std::string const & etcd_url, Client(std::string const& etcd_url, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl,
std::string const & password,
int const auth_token_ttl,
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
grpc::ChannelArguments const& arguments grpc::ChannelArguments const& arguments
#else #else
@ -128,12 +128,14 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * round_robin/pick_first/grpclb/xds.
* @param auth_token_ttl TTL seconds for auth token, see also
* `--auth-token-ttl` flags of etcd.
*/ */
static Client* WithUser(std::string const& etcd_url, static Client* WithUser(std::string const& etcd_url,
std::string const& username, std::string const& username,
@ -144,18 +146,17 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * @param auth_token_ttl TTL seconds for auth token, see also
* Default value should be 300. * `--auth-token-ttl` flags of etcd. Default value should be 300.
*/ */
static Client* WithUser(std::string const& etcd_url, static Client* WithUser(std::string const& etcd_url,
std::string const& username, std::string const& username,
std::string const & password, std::string const& password, int const auth_token_ttl,
int const auth_token_ttl,
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
grpc::ChannelArguments const& arguments grpc::ChannelArguments const& arguments
#else #else
@ -166,34 +167,35 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param privkey private key file for SSL/TLS authentication, could be empty
* string.
* @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
Client(std::string const & etcd_url, Client(std::string const& etcd_url, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param privkey private key file for SSL/TLS authentication, could be empty
* string.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
Client(std::string const & etcd_url, Client(std::string const& etcd_url, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
grpc::ChannelArguments const& arguments grpc::ChannelArguments const& arguments
@ -205,18 +207,20 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param target_name_override Override the target host name if you want to pass multiple address * @param privkey private key file for SSL/TLS authentication, could be empty
* for load balancing with SSL, and there's no DNS. The @target_name_override@ must exist in the * string.
* SANS of your SSL certificate. * @param target_name_override Override the target host name if you want to
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * pass multiple address for load balancing with SSL, and there's no DNS. The
* @target_name_override@ must exist in the SANS of your SSL certificate.
* @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
static Client *WithSSL(std::string const & etcd_url, static Client* WithSSL(std::string const& etcd_url, std::string const& ca,
std::string const & ca,
std::string const& cert = "", std::string const& cert = "",
std::string const& privkey = "", std::string const& privkey = "",
std::string const& target_name_override = "", std::string const& target_name_override = "",
@ -225,14 +229,16 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param target_name_override Override the target host name if you want to pass multiple address * @param privkey private key file for SSL/TLS authentication, could be empty
* for load balancing with SSL, and there's no DNS. The @target_name_override@ must exist in the * string.
* SANS of your SSL certificate. * @param target_name_override Override the target host name if you want to
* pass multiple address for load balancing with SSL, and there's no DNS. The
* @target_name_override@ must exist in the SANS of your SSL certificate.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
static Client* WithSSL(std::string const& etcd_url, static Client* WithSSL(std::string const& etcd_url,
@ -241,8 +247,7 @@ namespace etcd
#else #else
grpc_impl::ChannelArguments const& arguments, grpc_impl::ChannelArguments const& arguments,
#endif #endif
std::string const & ca, std::string const& ca, std::string const& cert = "",
std::string const & cert = "",
std::string const& privkey = "", std::string const& privkey = "",
std::string const& target_name_override = ""); std::string const& target_name_override = "");
@ -267,29 +272,31 @@ namespace etcd
pplx::task<Response> get(std::string const& key, int64_t revision); pplx::task<Response> get(std::string const& key, int64_t revision);
/** /**
* Sets the value of a key. The key will be modified if already exists or created * Sets the value of a key. The key will be modified if already exists or
* if it does not exists. * created if it does not exists.
* @param key is the key to be created or modified * @param key is the key to be created or modified
* @param value is the new value to be set * @param value is the new value to be set
*/ */
pplx::task<Response> set(std::string const & key, std::string const & value, int ttl = 0); pplx::task<Response> set(std::string const& key, std::string const& value,
int ttl = 0);
/** /**
* Sets the value of a key. The key will be modified if already exists or created * Sets the value of a key. The key will be modified if already exists or
* if it does not exists. * created if it does not exists.
* @param key is the key to be created or modified * @param key is the key to be created or modified
* @param value is the new value to be set * @param value is the new value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
pplx::task<Response> set(std::string const & key, std::string const & value, int64_t leaseId); pplx::task<Response> set(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Creates a new key and sets it's value. Fails if the key already exists. * Creates a new key and sets it's value. Fails if the key already exists.
* @param key is the key to be created * @param key is the key to be created
* @param value is the value to be set * @param value is the value to be set
*/ */
pplx::task<Response> add(std::string const & key, std::string const & value, int ttl = 0); pplx::task<Response> add(std::string const& key, std::string const& value,
int ttl = 0);
/** /**
* Creates a new key and sets it's value. Fails if the key already exists. * Creates a new key and sets it's value. Fails if the key already exists.
@ -297,7 +304,8 @@ namespace etcd
* @param value is the value to be set * @param value is the value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
pplx::task<Response> add(std::string const & key, std::string const & value, int64_t leaseId); pplx::task<Response> add(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Put a new key-value pair. * Put a new key-value pair.
@ -311,7 +319,8 @@ namespace etcd
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
*/ */
pplx::task<Response> modify(std::string const & key, std::string const & value, int ttl = 0); pplx::task<Response> modify(std::string const& key, std::string const& value,
int ttl = 0);
/** /**
* Modifies an existing key. Fails if the key does not exists. * Modifies an existing key. Fails if the key does not exists.
@ -319,45 +328,56 @@ namespace etcd
* @param value is the new value to be set * @param value is the new value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
pplx::task<Response> modify(std::string const & key, std::string const & value, int64_t leaseId); pplx::task<Response> modify(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Modifies an existing key only if it has a specific value. Fails if the key does not exists * Modifies an existing key only if it has a specific value. Fails if the key
* or the original value differs from the expected one. * does not exists or the original value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_value is the value to be replaced * @param old_value is the value to be replaced
*/ */
pplx::task<Response> modify_if(std::string const & key, std::string const & value, std::string const & old_value, int ttl = 0); pplx::task<Response> modify_if(std::string const& key,
std::string const& value,
std::string const& old_value, int ttl = 0);
/** /**
* Modifies an existing key only if it has a specific value. Fails if the key does not exists * Modifies an existing key only if it has a specific value. Fails if the key
* or the original value differs from the expected one. * does not exists or the original value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_value is the value to be replaced * @param old_value is the value to be replaced
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
pplx::task<Response> modify_if(std::string const & key, std::string const & value, std::string const & old_value, int64_t leaseId); pplx::task<Response> modify_if(std::string const& key,
std::string const& value,
std::string const& old_value, int64_t leaseId);
/** /**
* Modifies an existing key only if it has a specific modification index value. Fails if the key * Modifies an existing key only if it has a specific modification index
* does not exists or the modification index of the previous value differs from the expected one. * value. Fails if the key does not exists or the modification index of the
* previous value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_index is the expected index of the original value * @param old_index is the expected index of the original value
*/ */
pplx::task<Response> modify_if(std::string const & key, std::string const & value, int64_t old_index, int ttl = 0); pplx::task<Response> modify_if(std::string const& key,
std::string const& value, int64_t old_index,
int ttl = 0);
/** /**
* Modifies an existing key only if it has a specific modification index value. Fails if the key * Modifies an existing key only if it has a specific modification index
* does not exists or the modification index of the previous value differs from the expected one. * value. Fails if the key does not exists or the modification index of the
* previous value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_index is the expected index of the original value * @param old_index is the expected index of the original value
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
pplx::task<Response> modify_if(std::string const & key, std::string const & value, int64_t old_index, int64_t leaseId); pplx::task<Response> modify_if(std::string const& key,
std::string const& value, int64_t old_index,
int64_t leaseId);
/** /**
* Removes a single key. The key has to point to a plain, non directory entry. * Removes a single key. The key has to point to a plain, non directory entry.
@ -366,31 +386,36 @@ namespace etcd
pplx::task<Response> rm(std::string const& key); pplx::task<Response> rm(std::string const& key);
/** /**
* Removes a single key but only if it has a specific value. Fails if the key does not exists * Removes a single key but only if it has a specific value. Fails if the key
* or the its value differs from the expected one. * does not exists or the its value differs from the expected one.
* @param key is the key to be deleted * @param key is the key to be deleted
*/ */
pplx::task<Response> rm_if(std::string const & key, std::string const & old_value); pplx::task<Response> rm_if(std::string const& key,
std::string const& old_value);
/** /**
* Removes an existing key only if it has a specific modification index value. Fails if the key * Removes an existing key only if it has a specific modification index value.
* does not exists or the modification index of it differs from the expected one. * Fails if the key does not exists or the modification index of it differs
* from the expected one.
* @param key is the key to be deleted * @param key is the key to be deleted
* @param old_index is the expected index of the existing value * @param old_index is the expected index of the existing value
*/ */
pplx::task<Response> rm_if(std::string const& key, int64_t old_index); pplx::task<Response> rm_if(std::string const& key, int64_t old_index);
/** /**
* Removes a directory node. Fails if the parent directory dos not exists or not a directory. * Removes a directory node. Fails if the parent directory dos not exists or
* not a directory.
* @param key is the directory to be created to be listed * @param key is the directory to be created to be listed
* @param recursive if true then delete a whole subtree, otherwise deletes only an empty directory. * @param recursive if true then delete a whole subtree, otherwise deletes
* only an empty directory.
*/ */
pplx::task<Response> rmdir(std::string const& key, bool recursive = false); pplx::task<Response> rmdir(std::string const& key, bool recursive = false);
/** /**
* Removes multiple keys between [key, range_end). * Removes multiple keys between [key, range_end).
* *
* This overload for `const char *` is to avoid const char * to bool implicit casting. * This overload for `const char *` is to avoid const char * to bool implicit
* casting.
* *
* @param key is the directory to be created to be listed * @param key is the directory to be created to be listed
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
@ -403,7 +428,8 @@ namespace etcd
* @param key is the directory to be created to be listed * @param key is the directory to be created to be listed
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
*/ */
pplx::task<Response> rmdir(std::string const & key, std::string const &range_end); pplx::task<Response> rmdir(std::string const& key,
std::string const& range_end);
/** /**
* Gets a directory listing of the directory prefixed by the key. * Gets a directory listing of the directory prefixed by the key.
@ -416,24 +442,28 @@ namespace etcd
* Gets a directory listing of the directory prefixed by the key. * Gets a directory listing of the directory prefixed by the key.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
*/ */
pplx::task<Response> ls(std::string const& key, size_t const limit); pplx::task<Response> ls(std::string const& key, size_t const limit);
/** /**
* Gets a directory listing of the directory prefixed by the key with given revision. * Gets a directory listing of the directory prefixed by the key with given
* revision.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
pplx::task<Response> ls(std::string const & key, size_t const limit, int64_t revision); pplx::task<Response> ls(std::string const& key, size_t const limit,
int64_t revision);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end). * range_end, i.e., get all keys in the range [key, range_end).
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
@ -441,27 +471,31 @@ namespace etcd
pplx::task<Response> ls(std::string const& key, std::string const& range_end); pplx::task<Response> ls(std::string const& key, std::string const& range_end);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end), and respects the given limit. * range_end, i.e., get all keys in the range [key, range_end), and respects
* the given limit.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
*/ */
pplx::task<Response> ls(std::string const & key, std::string const &range_end, size_t const limit); pplx::task<Response> ls(std::string const& key, std::string const& range_end,
size_t const limit);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end), and respects the given limit and revision. * range_end, i.e., get all keys in the range [key, range_end), and respects
* the given limit and revision.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
pplx::task<Response> ls(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision); pplx::task<Response> ls(std::string const& key, std::string const& range_end,
size_t const limit, int64_t revision);
/** /**
* Gets a directory listing of the directory prefixed by the key. * Gets a directory listing of the directory prefixed by the key.
@ -478,8 +512,8 @@ namespace etcd
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
*/ */
pplx::task<Response> keys(std::string const& key, size_t const limit); pplx::task<Response> keys(std::string const& key, size_t const limit);
@ -489,72 +523,82 @@ namespace etcd
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
pplx::task<Response> keys(std::string const & key, size_t const limit, int64_t revision); pplx::task<Response> keys(std::string const& key, size_t const limit,
int64_t revision);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end), and respects the given limit. * range [key, range_end), and respects the given limit.
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
*/ */
pplx::task<Response> keys(std::string const & key, std::string const &range_end); pplx::task<Response> keys(std::string const& key,
std::string const& range_end);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end). * range [key, range_end).
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
*/ */
pplx::task<Response> keys(std::string const & key, std::string const &range_end, size_t const limit); pplx::task<Response> keys(std::string const& key,
std::string const& range_end, size_t const limit);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end). * range [key, range_end).
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
pplx::task<Response> keys(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision); pplx::task<Response> keys(std::string const& key,
std::string const& range_end, size_t const limit,
int64_t revision);
/** /**
* Watches for changes of a key or a subtree. Please note that if you watch e.g. "/testdir" and * Watches for changes of a key or a subtree. Please note that if you watch
* a new key is created, like "/testdir/newkey" then no change happened in the value of * e.g. "/testdir" and a new key is created, like "/testdir/newkey" then no
* "/testdir" so your watch will not detect this. If you want to detect addition and deletion of * change happened in the value of
* directory entries then you have to do a recursive watch. * "/testdir" so your watch will not detect this. If you want to detect
* addition and deletion of directory entries then you have to do a recursive
* watch.
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param recursive if true watch a whole subtree * @param recursive if true watch a whole subtree
*/ */
pplx::task<Response> watch(std::string const& key, bool recursive = false); pplx::task<Response> watch(std::string const& key, bool recursive = false);
/** /**
* Watches for changes of a key or a subtree from a specific index. The index value can be in the "past". * Watches for changes of a key or a subtree from a specific index. The index
* value can be in the "past".
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param fromIndex the first index we are interested in * @param fromIndex the first index we are interested in
* @param recursive if true watch a whole subtree * @param recursive if true watch a whole subtree
*/ */
pplx::task<Response> watch(std::string const & key, int64_t fromIndex, bool recursive = false); pplx::task<Response> watch(std::string const& key, int64_t fromIndex,
bool recursive = false);
/** /**
* Watches for changes of a range of keys inside [key, range_end). * Watches for changes of a range of keys inside [key, range_end).
* *
* This overload for `const char *` is to avoid const char * to bool implicit casting. * This overload for `const char *` is to avoid const char * to bool implicit
* casting.
* *
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
@ -567,18 +611,21 @@ namespace etcd
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
*/ */
pplx::task<Response> watch(std::string const & key, std::string const &range_end); pplx::task<Response> watch(std::string const& key,
std::string const& range_end);
/** /**
* Watches for changes of a range of keys inside [key, range_end) from a specific index. The index value * Watches for changes of a range of keys inside [key, range_end) from a
* can be in the "past". * specific index. The index value can be in the "past".
* *
* Watches for changes of a key or a subtree from a specific index. The index value can be in the "past". * Watches for changes of a key or a subtree from a specific index. The index
* value can be in the "past".
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
* @param fromIndex the first index we are interested in * @param fromIndex the first index we are interested in
*/ */
pplx::task<Response> watch(std::string const & key, std::string const &range_end, int64_t fromIndex); pplx::task<Response> watch(std::string const& key,
std::string const& range_end, int64_t fromIndex);
/** /**
* Grants a lease. * Grants a lease.
@ -610,30 +657,33 @@ namespace etcd
pplx::task<Response> leases(); pplx::task<Response> leases();
/** /**
* Gains a lock at a key, using a default created lease, using the default lease (10 seconds), with * Gains a lock at a key, using a default created lease, using the default
* keeping alive has already been taken care of by the library. * lease (10 seconds), with keeping alive has already been taken care of by
* the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
*/ */
pplx::task<Response> lock(std::string const& key); pplx::task<Response> lock(std::string const& key);
/** /**
* Lock is special, as waiting for lock may cause the thread resources (in the pplx thread pool) to * Lock is special, as waiting for lock may cause the thread resources (in the
* be exhausted. So we need to provide a way to let the user to issue a lock without taking the a * pplx thread pool) to be exhausted. So we need to provide a way to let the
* shared thread. * user to issue a lock without taking the a shared thread.
* *
* This works like what we have in the sync client, but we can issue such method from the async client * This works like what we have in the sync client, but we can issue such
* directly. * method from the async client directly.
* *
* That would be useful when use already issue the lock from a controlled thread. See more discussion * That would be useful when use already issue the lock from a controlled
* about the target scenario in https://github.com/etcd-cpp-apiv3/etcd-cpp-apiv3/issues/139 * thread. See more discussion about the target scenario in
* https://github.com/etcd-cpp-apiv3/etcd-cpp-apiv3/issues/139
* *
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
*/ */
pplx::task<Response> lock(std::string const& key, const bool sync); pplx::task<Response> lock(std::string const& key, const bool sync);
/** /**
* Gains a lock at a key, using a default created lease, using the specified lease TTL (in seconds), with * Gains a lock at a key, using a default created lease, using the specified
* keeping alive has already been taken care of by the library. * lease TTL (in seconds), with keeping alive has already been taken care of
* by the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
* @param lease_ttl is the TTL used to create a lease for the key. * @param lease_ttl is the TTL used to create a lease for the key.
*/ */
@ -642,19 +692,22 @@ namespace etcd
/** /**
* Lock, but the sync version. * Lock, but the sync version.
*/ */
pplx::task<Response> lock(std::string const &key, int lease_ttl, const bool sync); pplx::task<Response> lock(std::string const& key, int lease_ttl,
const bool sync);
/** /**
* Gains a lock at a key, using a user-provided lease, the lifetime of the lease won't be taken care * Gains a lock at a key, using a user-provided lease, the lifetime of the
* of by the library. * lease won't be taken care of by the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
*/ */
pplx::task<Response> lock_with_lease(std::string const &key, int64_t lease_id); pplx::task<Response> lock_with_lease(std::string const& key,
int64_t lease_id);
/** /**
* Lock, but the sync version. * Lock, but the sync version.
*/ */
pplx::task<Response> lock_with_lease(std::string const &key, int64_t lease_id, const bool sync); pplx::task<Response> lock_with_lease(std::string const& key, int64_t lease_id,
const bool sync);
/** /**
* Releases a lock at a key. * Releases a lock at a key.
@ -696,7 +749,8 @@ namespace etcd
* @param value is the new value to set. * @param value is the new value to set.
*/ */
pplx::task<Response> proclaim(std::string const& name, int64_t lease_id, pplx::task<Response> proclaim(std::string const& name, int64_t lease_id,
std::string const &key, int64_t revision, std::string const &value); std::string const& key, int64_t revision,
std::string const& value);
/** /**
* Get the current leader proclamation. * Get the current leader proclamation.
@ -714,7 +768,8 @@ namespace etcd
* *
* @param name is the names of election to watch. * @param name is the names of election to watch.
* *
* @returns an observer that holds that action and will cancel the request when being destructed. * @returns an observer that holds that action and will cancel the request
* when being destructed.
*/ */
std::unique_ptr<Observer> observe(std::string const& name); std::unique_ptr<Observer> observe(std::string const& name);
@ -748,7 +803,8 @@ namespace etcd
* Set a timeout value for grpc operations. * Set a timeout value for grpc operations.
*/ */
template <typename Period = std::micro> template <typename Period = std::micro>
void set_grpc_timeout(std::chrono::duration<std::chrono::microseconds::rep, Period> const &timeout) { void set_grpc_timeout(std::chrono::duration<std::chrono::microseconds::rep,
Period> const& timeout) {
this->client->set_grpc_timeout(timeout); this->client->set_grpc_timeout(timeout);
} }
@ -769,6 +825,6 @@ namespace etcd
SyncClient* client = nullptr; SyncClient* client = nullptr;
}; };
} } // namespace etcd
#endif #endif

View File

@ -10,52 +10,43 @@
#include <string> #include <string>
#include <thread> #include <thread>
#include "etcd/SyncClient.hpp"
#include "etcd/Response.hpp" #include "etcd/Response.hpp"
#include "etcd/SyncClient.hpp"
namespace etcd namespace etcd {
{
// forward declaration to avoid header/library dependency // forward declaration to avoid header/library dependency
class Client; class Client;
/** /**
* If ID is set to 0, the library will choose an ID, and can be accessed from ".Lease()". * If ID is set to 0, the library will choose an ID, and can be accessed from
* ".Lease()".
*/ */
class KeepAlive class KeepAlive {
{
public: public:
KeepAlive(Client const &client, KeepAlive(Client const& client, int ttl, int64_t lease_id = 0);
int ttl, int64_t lease_id = 0); KeepAlive(SyncClient const& client, int ttl, int64_t lease_id = 0);
KeepAlive(SyncClient const &client, KeepAlive(std::string const& address, int ttl, int64_t lease_id = 0);
int ttl, int64_t lease_id = 0); KeepAlive(std::string const& address, std::string const& username,
KeepAlive(std::string const & address, std::string const& password, int ttl, int64_t lease_id = 0,
int ttl, int64_t lease_id = 0);
KeepAlive(std::string const & address,
std::string const & username, std::string const & password,
int ttl, int64_t lease_id = 0,
int const auth_token_ttl = 300); int const auth_token_ttl = 300);
KeepAlive(Client const& client, KeepAlive(Client const& client,
std::function<void (std::exception_ptr)> const &handler, std::function<void(std::exception_ptr)> const& handler, int ttl,
int ttl, int64_t lease_id = 0); int64_t lease_id = 0);
KeepAlive(SyncClient const& client, KeepAlive(SyncClient const& client,
std::function<void (std::exception_ptr)> const &handler, std::function<void(std::exception_ptr)> const& handler, int ttl,
int ttl, int64_t lease_id = 0); int64_t lease_id = 0);
KeepAlive(std::string const& address, KeepAlive(std::string const& address,
std::function<void (std::exception_ptr)> const &handler, std::function<void(std::exception_ptr)> const& handler, int ttl,
int ttl, int64_t lease_id = 0); int64_t lease_id = 0);
KeepAlive(std::string const & address, KeepAlive(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password,
std::function<void (std::exception_ptr)> const &handler, std::function<void(std::exception_ptr)> const& handler, int ttl,
int ttl, int64_t lease_id = 0, int64_t lease_id = 0, int const auth_token_ttl = 300);
int const auth_token_ttl = 300); KeepAlive(std::string const& address, std::string const& ca,
KeepAlive(std::string const & address, std::string const& cert, std::string const& privkey,
std::string const & ca, std::function<void(std::exception_ptr)> const& handler, int ttl,
std::string const & cert, int64_t lease_id = 0, std::string const& target_name_override = "");
std::string const & privkey,
std::function<void (std::exception_ptr)> const &handler,
int ttl, int64_t lease_id = 0,
std::string const & target_name_override = "");
KeepAlive(KeepAlive const&) = delete; KeepAlive(KeepAlive const&) = delete;
KeepAlive(KeepAlive&&) = delete; KeepAlive(KeepAlive&&) = delete;
@ -68,7 +59,8 @@ namespace etcd
void Cancel(); void Cancel();
/** /**
* Check if the keep alive is still valid (invalid when there's an async exception). * Check if the keep alive is still valid (invalid when there's an async
* exception).
* *
* Nothing will happen if valid and an exception will be rethrowed if invalid. * Nothing will happen if valid and an exception will be rethrowed if invalid.
*/ */
@ -79,7 +71,8 @@ namespace etcd
*/ */
template <typename Rep = std::micro> template <typename Rep = std::micro>
void set_grpc_timeout(std::chrono::duration<Rep> const& timeout) { void set_grpc_timeout(std::chrono::duration<Rep> const& timeout) {
this->grpc_timeout = std::chrono::duration_cast<std::chrono::milliseconds>(timeout); this->grpc_timeout =
std::chrono::duration_cast<std::chrono::milliseconds>(timeout);
} }
/** /**
@ -108,8 +101,9 @@ namespace etcd
std::exception_ptr eptr_; std::exception_ptr eptr_;
std::function<void(std::exception_ptr)> handler_; std::function<void(std::exception_ptr)> handler_;
// Don't use `pplx::task` to avoid sharing thread pool with other actions on the client // Don't use `pplx::task` to avoid sharing thread pool with other actions on
// to avoid any potential blocking, which may block the keepalive loop and evict the lease. // the client to avoid any potential blocking, which may block the keepalive
// loop and evict the lease.
std::thread refresh_task_; std::thread refresh_task_;
int ttl; int ttl;
@ -121,8 +115,9 @@ namespace etcd
std::atomic_bool continue_next; std::atomic_bool continue_next;
// grpc timeout in `refresh()` // grpc timeout in `refresh()`
mutable std::chrono::microseconds grpc_timeout = std::chrono::microseconds::zero(); mutable std::chrono::microseconds grpc_timeout =
std::chrono::microseconds::zero();
}; };
} } // namespace etcd
#endif #endif

View File

@ -2,8 +2,8 @@
#define __ETCD_RESPONSE_HPP__ #define __ETCD_RESPONSE_HPP__
#include <chrono> #include <chrono>
#include <iostream>
#include <functional> #include <functional>
#include <iostream>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
@ -15,10 +15,9 @@ namespace etcdv3 {
class AsyncLeaseKeepAliveAction; class AsyncLeaseKeepAliveAction;
class AsyncObserveAction; class AsyncObserveAction;
class V3Response; class V3Response;
} } // namespace etcdv3
namespace etcd namespace etcd {
{
typedef std::vector<std::string> Keys; typedef std::vector<std::string> Keys;
namespace detail { namespace detail {
@ -28,7 +27,7 @@ namespace etcd
return std::chrono::duration_cast<std::chrono::microseconds>( return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now() - start_timepoint); std::chrono::high_resolution_clock::now() - start_timepoint);
} }
} } // namespace detail
// forward declaration // forward declaration
class KeepAlive; class KeepAlive;
@ -37,53 +36,51 @@ namespace etcd
/** /**
* The Reponse object received for the requests of etcd::Client * The Reponse object received for the requests of etcd::Client
*/ */
class Response class Response {
{
public: public:
template <typename T> template <typename T>
static etcd::Response create(std::unique_ptr<T> call) static etcd::Response create(std::unique_ptr<T> call) {
{
call->waitForResponse(); call->waitForResponse();
auto v3resp = call->ParseResponse(); auto v3resp = call->ParseResponse();
return etcd::Response(v3resp, detail::duration_till_now(call->startTimepoint())); return etcd::Response(v3resp,
detail::duration_till_now(call->startTimepoint()));
} }
template <typename T> template <typename T>
static etcd::Response create(std::shared_ptr<T> call) static etcd::Response create(std::shared_ptr<T> call) {
{
call->waitForResponse(); call->waitForResponse();
auto v3resp = call->ParseResponse(); auto v3resp = call->ParseResponse();
return etcd::Response(v3resp, detail::duration_till_now(call->startTimepoint())); return etcd::Response(v3resp,
detail::duration_till_now(call->startTimepoint()));
} }
template <typename T> template <typename T>
static etcd::Response create(std::unique_ptr<T> call, static etcd::Response create(std::unique_ptr<T> call,
std::function<void(Response)> callback) std::function<void(Response)> callback) {
{
call->waitForResponse(callback); call->waitForResponse(callback);
auto v3resp = call->ParseResponse(); auto v3resp = call->ParseResponse();
return etcd::Response(v3resp, detail::duration_till_now(call->startTimepoint())); return etcd::Response(v3resp,
detail::duration_till_now(call->startTimepoint()));
} }
template <typename T> template <typename T>
static etcd::Response create(std::function<std::unique_ptr<T>()> fn) static etcd::Response create(std::function<std::unique_ptr<T>()> fn) {
{
auto call = fn(); auto call = fn();
call->waitForResponse(); call->waitForResponse();
auto v3resp = call->ParseResponse(); auto v3resp = call->ParseResponse();
return etcd::Response(v3resp, detail::duration_till_now(call->startTimepoint())); return etcd::Response(v3resp,
detail::duration_till_now(call->startTimepoint()));
} }
template <typename T> template <typename T>
static etcd::Response create(std::function<std::shared_ptr<T>()> fn) static etcd::Response create(std::function<std::shared_ptr<T>()> fn) {
{
auto call = fn(); auto call = fn();
call->waitForResponse(); call->waitForResponse();
auto v3resp = call->ParseResponse(); auto v3resp = call->ParseResponse();
return etcd::Response(v3resp, detail::duration_till_now(call->startTimepoint())); return etcd::Response(v3resp,
detail::duration_till_now(call->startTimepoint()));
} }
Response(); Response();
@ -91,7 +88,8 @@ namespace etcd
Response(const Response&); Response(const Response&);
/** /**
* Returns the error code received from the etcd server. In case of success the error code is 0. * Returns the error code received from the etcd server. In case of success
* the error code is 0.
*/ */
int error_code() const; int error_code() const;
@ -131,17 +129,20 @@ namespace etcd
Value const& value() const; Value const& value() const;
/** /**
* Returns the previous value object of the response to a set/modify/rm operation. * Returns the previous value object of the response to a set/modify/rm
* operation.
*/ */
Value const& prev_value() const; Value const& prev_value() const;
/** /**
* Returns the index-th value of the response to an 'ls' operation. Equivalent to values()[index] * Returns the index-th value of the response to an 'ls' operation. Equivalent
* to values()[index]
*/ */
Value const& value(int index) const; Value const& value(int index) const;
/** /**
* Returns the vector of values in a directory in response to an 'ls' operation. * Returns the vector of values in a directory in response to an 'ls'
* operation.
*/ */
Values const& values() const; Values const& values() const;
@ -162,7 +163,8 @@ namespace etcd
int64_t compact_revision() const; int64_t compact_revision() const;
/** /**
* Returns the watcher id for client.watch() requests. `-1` means uninitialized (the response is not for watch). * Returns the watcher id for client.watch() requests. `-1` means
* uninitialized (the response is not for watch).
*/ */
int64_t watch_id() const; int64_t watch_id() const;
@ -207,7 +209,8 @@ namespace etcd
std::vector<int64_t> const& leases() const; std::vector<int64_t> const& leases() const;
protected: protected:
Response(const etcdv3::V3Response& response, std::chrono::microseconds const& duration); Response(const etcdv3::V3Response& response,
std::chrono::microseconds const& duration);
Response(int error_code, std::string const& error_message); Response(int error_code, std::string const& error_message);
Response(int error_code, char const* error_message); Response(int error_code, char const* error_message);
@ -224,7 +227,8 @@ namespace etcd
std::string _lock_key; // for lock std::string _lock_key; // for lock
std::string _name; // for campaign (in v3election) std::string _name; // for campaign (in v3election)
std::vector<Event> _events; // for watch std::vector<Event> _events; // for watch
// execute duration (in microseconds), during the action created and response parsed // execute duration (in microseconds), during the action created and response
// parsed
std::chrono::microseconds _duration; std::chrono::microseconds _duration;
// cluster metadata // cluster metadata
@ -244,6 +248,6 @@ namespace etcd
friend class etcdv3::AsyncLeaseKeepAliveAction; friend class etcdv3::AsyncLeaseKeepAliveAction;
friend class etcdv3::AsyncObserveAction; friend class etcdv3::AsyncObserveAction;
}; };
} } // namespace etcd
#endif #endif

View File

@ -43,27 +43,26 @@ namespace etcdv3 {
namespace detail { namespace detail {
std::string string_plus_one(std::string const& value); std::string string_plus_one(std::string const& value);
std::string resolve_etcd_endpoints(std::string const& default_endpoints); std::string resolve_etcd_endpoints(std::string const& default_endpoints);
} } // namespace detail
} } // namespace etcdv3
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
namespace grpc { namespace grpc {
class Channel; class Channel;
class ChannelArguments; class ChannelArguments;
} } // namespace grpc
#else #else
namespace grpc_impl { namespace grpc_impl {
class Channel; class Channel;
class ChannelArguments; class ChannelArguments;
} } // namespace grpc_impl
#endif #endif
namespace etcd namespace etcd {
{ using etcdv3::ERROR_ACTION_CANCELLED;
using etcdv3::ERROR_KEY_NOT_FOUND;
using etcdv3::ERROR_COMPARE_FAILED; using etcdv3::ERROR_COMPARE_FAILED;
using etcdv3::ERROR_KEY_ALREADY_EXISTS; using etcdv3::ERROR_KEY_ALREADY_EXISTS;
using etcdv3::ERROR_ACTION_CANCELLED; using etcdv3::ERROR_KEY_NOT_FOUND;
class KeepAlive; class KeepAlive;
class Watcher; class Watcher;
@ -74,15 +73,16 @@ namespace etcd
* Etcd operations can be reached via the methods of the client. * Etcd operations can be reached via the methods of the client.
*/ */
/** /**
* SyncClient is a wrapper around etcd::Client and provides a simplified sync interface with blocking operations. * SyncClient is a wrapper around etcd::Client and provides a simplified sync
* interface with blocking operations.
* *
* In case of any exceptions occur in the backend the Response value's error_message will contain the * In case of any exceptions occur in the backend the Response value's
* text of the exception and the error code will be 600 * error_message will contain the text of the exception and the error code will
* be 600
* *
* Use this class only if performance does not matter. * Use this class only if performance does not matter.
*/ */
class SyncClient class SyncClient {
{
private: private:
class TokenAuthenticator; class TokenAuthenticator;
class TokenAuthenticatorDeleter { class TokenAuthenticatorDeleter {
@ -94,9 +94,10 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
SyncClient(std::string const& etcd_url, SyncClient(std::string const& etcd_url,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
@ -104,8 +105,8 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
SyncClient(std::string const& etcd_url, SyncClient(std::string const& etcd_url,
@ -119,9 +120,10 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
static SyncClient* WithUrl(std::string const& etcd_url, static SyncClient* WithUrl(std::string const& etcd_url,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
@ -129,8 +131,8 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
static SyncClient* WithUrl(std::string const& etcd_url, static SyncClient* WithUrl(std::string const& etcd_url,
@ -144,34 +146,32 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * round_robin/pick_first/grpclb/xds.
* @param auth_token_ttl TTL seconds for auth token, see also
* `--auth-token-ttl` flags of etcd.
*/ */
SyncClient(std::string const & etcd_url, SyncClient(std::string const& etcd_url, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl = 300,
std::string const & password,
int const auth_token_ttl = 300,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * @param auth_token_ttl TTL seconds for auth token, see also
* Default value should be 300. * `--auth-token-ttl` flags of etcd. Default value should be 300.
*/ */
SyncClient(std::string const & etcd_url, SyncClient(std::string const& etcd_url, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl,
std::string const & password,
int const auth_token_ttl,
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
grpc::ChannelArguments const& arguments grpc::ChannelArguments const& arguments
#else #else
@ -179,16 +179,17 @@ namespace etcd
#endif #endif
); );
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param load_balancer is the load balance strategy, can be one of
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * round_robin/pick_first/grpclb/xds.
* @param auth_token_ttl TTL seconds for auth token, see also
* `--auth-token-ttl` flags of etcd.
*/ */
static SyncClient* WithUser(std::string const& etcd_url, static SyncClient* WithUser(std::string const& etcd_url,
std::string const& username, std::string const& username,
@ -199,13 +200,13 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param username username of etcd auth * @param username username of etcd auth
* @param password password of etcd auth * @param password password of etcd auth
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
* @param auth_token_ttl TTL seconds for auth token, see also `--auth-token-ttl` flags of etcd. * @param auth_token_ttl TTL seconds for auth token, see also
* Default value should be 300. * `--auth-token-ttl` flags of etcd. Default value should be 300.
*/ */
static SyncClient* WithUser(std::string const& etcd_url, static SyncClient* WithUser(std::string const& etcd_url,
std::string const& username, std::string const& username,
@ -218,38 +219,38 @@ namespace etcd
#endif #endif
); );
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * @param privkey private key file for SSL/TLS authentication, could be empty
* string.
* @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
SyncClient(std::string const & etcd_url, SyncClient(std::string const& etcd_url, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
std::string const& load_balancer = "round_robin"); std::string const& load_balancer = "round_robin");
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param privkey private key file for SSL/TLS authentication, could be empty
* string.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
SyncClient(std::string const & etcd_url, SyncClient(std::string const& etcd_url, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
#if defined(WITH_GRPC_CHANNEL_CLASS) #if defined(WITH_GRPC_CHANNEL_CLASS)
grpc::ChannelArguments const& arguments grpc::ChannelArguments const& arguments
@ -258,22 +259,23 @@ namespace etcd
#endif #endif
); );
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param target_name_override Override the target host name if you want to pass multiple address * @param privkey private key file for SSL/TLS authentication, could be empty
* for load balancing with SSL, and there's no DNS. The @target_name_override@ must exist in the * string.
* SANS of your SSL certificate. * @param target_name_override Override the target host name if you want to
* @param load_balancer is the load balance strategy, can be one of round_robin/pick_first/grpclb/xds. * pass multiple address for load balancing with SSL, and there's no DNS. The
* @target_name_override@ must exist in the SANS of your SSL certificate.
* @param load_balancer is the load balance strategy, can be one of
* round_robin/pick_first/grpclb/xds.
*/ */
static SyncClient *WithSSL(std::string const & etcd_url, static SyncClient* WithSSL(std::string const& etcd_url, std::string const& ca,
std::string const & ca,
std::string const& cert = "", std::string const& cert = "",
std::string const& privkey = "", std::string const& privkey = "",
std::string const& target_name_override = "", std::string const& target_name_override = "",
@ -282,14 +284,16 @@ namespace etcd
/** /**
* Constructs an etcd client object. * Constructs an etcd client object.
* *
* @param etcd_url is the url of the etcd server to connect to, like "http://127.0.0.1:2379", * @param etcd_url is the url of the etcd server to connect to, like
* or multiple url, separated by ',' or ';'. * "http://127.0.0.1:2379", or multiple url, separated by ',' or ';'.
* @param ca root CA file for SSL/TLS connection. * @param ca root CA file for SSL/TLS connection.
* @param cert cert chain file for SSL/TLS authentication, could be empty string. * @param cert cert chain file for SSL/TLS authentication, could be empty
* @param privkey private key file for SSL/TLS authentication, could be empty string. * string.
* @param target_name_override Override the target host name if you want to pass multiple address * @param privkey private key file for SSL/TLS authentication, could be empty
* for load balancing with SSL, and there's no DNS. The @target_name_override@ must exist in the * string.
* SANS of your SSL certificate. * @param target_name_override Override the target host name if you want to
* pass multiple address for load balancing with SSL, and there's no DNS. The
* @target_name_override@ must exist in the SANS of your SSL certificate.
* @param arguments user provided grpc channel arguments. * @param arguments user provided grpc channel arguments.
*/ */
static SyncClient* WithSSL(std::string const& etcd_url, static SyncClient* WithSSL(std::string const& etcd_url,
@ -324,21 +328,22 @@ namespace etcd
Response get(std::string const& key, int64_t revision); Response get(std::string const& key, int64_t revision);
/** /**
* Sets the value of a key. The key will be modified if already exists or created * Sets the value of a key. The key will be modified if already exists or
* if it does not exists. * created if it does not exists.
* @param key is the key to be created or modified * @param key is the key to be created or modified
* @param value is the new value to be set * @param value is the new value to be set
*/ */
Response set(std::string const& key, std::string const& value, int ttl = 0); Response set(std::string const& key, std::string const& value, int ttl = 0);
/** /**
* Sets the value of a key. The key will be modified if already exists or created * Sets the value of a key. The key will be modified if already exists or
* if it does not exists. * created if it does not exists.
* @param key is the key to be created or modified * @param key is the key to be created or modified
* @param value is the new value to be set * @param value is the new value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
Response set(std::string const & key, std::string const & value, int64_t leaseId); Response set(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Creates a new key and sets it's value. Fails if the key already exists. * Creates a new key and sets it's value. Fails if the key already exists.
@ -353,7 +358,8 @@ namespace etcd
* @param value is the value to be set * @param value is the value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
Response add(std::string const & key, std::string const & value, int64_t leaseId); Response add(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Put a new key-value pair. * Put a new key-value pair.
@ -367,7 +373,8 @@ namespace etcd
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
*/ */
Response modify(std::string const & key, std::string const & value, int ttl = 0); Response modify(std::string const& key, std::string const& value,
int ttl = 0);
/** /**
* Modifies an existing key. Fails if the key does not exists. * Modifies an existing key. Fails if the key does not exists.
@ -375,45 +382,52 @@ namespace etcd
* @param value is the new value to be set * @param value is the new value to be set
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
Response modify(std::string const & key, std::string const & value, int64_t leaseId); Response modify(std::string const& key, std::string const& value,
int64_t leaseId);
/** /**
* Modifies an existing key only if it has a specific value. Fails if the key does not exists * Modifies an existing key only if it has a specific value. Fails if the key
* or the original value differs from the expected one. * does not exists or the original value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_value is the value to be replaced * @param old_value is the value to be replaced
*/ */
Response modify_if(std::string const & key, std::string const & value, std::string const & old_value, int ttl = 0); Response modify_if(std::string const& key, std::string const& value,
std::string const& old_value, int ttl = 0);
/** /**
* Modifies an existing key only if it has a specific value. Fails if the key does not exists * Modifies an existing key only if it has a specific value. Fails if the key
* or the original value differs from the expected one. * does not exists or the original value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_value is the value to be replaced * @param old_value is the value to be replaced
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
Response modify_if(std::string const & key, std::string const & value, std::string const & old_value, int64_t leaseId); Response modify_if(std::string const& key, std::string const& value,
std::string const& old_value, int64_t leaseId);
/** /**
* Modifies an existing key only if it has a specific modification index value. Fails if the key * Modifies an existing key only if it has a specific modification index
* does not exists or the modification index of the previous value differs from the expected one. * value. Fails if the key does not exists or the modification index of the
* previous value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_index is the expected index of the original value * @param old_index is the expected index of the original value
*/ */
Response modify_if(std::string const & key, std::string const & value, int64_t old_index, int ttl = 0); Response modify_if(std::string const& key, std::string const& value,
int64_t old_index, int ttl = 0);
/** /**
* Modifies an existing key only if it has a specific modification index value. Fails if the key * Modifies an existing key only if it has a specific modification index
* does not exists or the modification index of the previous value differs from the expected one. * value. Fails if the key does not exists or the modification index of the
* previous value differs from the expected one.
* @param key is the key to be modified * @param key is the key to be modified
* @param value is the new value to be set * @param value is the new value to be set
* @param old_index is the expected index of the original value * @param old_index is the expected index of the original value
* @param leaseId is the lease attached to the key * @param leaseId is the lease attached to the key
*/ */
Response modify_if(std::string const & key, std::string const & value, int64_t old_index, int64_t leaseId); Response modify_if(std::string const& key, std::string const& value,
int64_t old_index, int64_t leaseId);
/** /**
* Removes a single key. The key has to point to a plain, non directory entry. * Removes a single key. The key has to point to a plain, non directory entry.
@ -422,31 +436,35 @@ namespace etcd
Response rm(std::string const& key); Response rm(std::string const& key);
/** /**
* Removes a single key but only if it has a specific value. Fails if the key does not exists * Removes a single key but only if it has a specific value. Fails if the key
* or the its value differs from the expected one. * does not exists or the its value differs from the expected one.
* @param key is the key to be deleted * @param key is the key to be deleted
*/ */
Response rm_if(std::string const& key, std::string const& old_value); Response rm_if(std::string const& key, std::string const& old_value);
/** /**
* Removes an existing key only if it has a specific modification index value. Fails if the key * Removes an existing key only if it has a specific modification index value.
* does not exists or the modification index of it differs from the expected one. * Fails if the key does not exists or the modification index of it differs
* from the expected one.
* @param key is the key to be deleted * @param key is the key to be deleted
* @param old_index is the expected index of the existing value * @param old_index is the expected index of the existing value
*/ */
Response rm_if(std::string const& key, int64_t old_index); Response rm_if(std::string const& key, int64_t old_index);
/** /**
* Removes a directory node. Fails if the parent directory dos not exists or not a directory. * Removes a directory node. Fails if the parent directory dos not exists or
* not a directory.
* @param key is the directory to be created to be listed * @param key is the directory to be created to be listed
* @param recursive if true then delete a whole subtree, otherwise deletes only an empty directory. * @param recursive if true then delete a whole subtree, otherwise deletes
* only an empty directory.
*/ */
Response rmdir(std::string const& key, bool recursive = false); Response rmdir(std::string const& key, bool recursive = false);
/** /**
* Removes multiple keys between [key, range_end). * Removes multiple keys between [key, range_end).
* *
* This overload for `const char *` is to avoid const char * to bool implicit casting. * This overload for `const char *` is to avoid const char * to bool implicit
* casting.
* *
* @param key is the directory to be created to be listed * @param key is the directory to be created to be listed
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
@ -472,24 +490,27 @@ namespace etcd
* Gets a directory listing of the directory prefixed by the key. * Gets a directory listing of the directory prefixed by the key.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
*/ */
Response ls(std::string const& key, size_t const limit); Response ls(std::string const& key, size_t const limit);
/** /**
* Gets a directory listing of the directory prefixed by the key with given revision. * Gets a directory listing of the directory prefixed by the key with given
* revision.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
Response ls(std::string const& key, size_t const limit, int64_t revision); Response ls(std::string const& key, size_t const limit, int64_t revision);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end). * range_end, i.e., get all keys in the range [key, range_end).
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
@ -497,27 +518,33 @@ namespace etcd
Response ls(std::string const& key, std::string const& range_end); Response ls(std::string const& key, std::string const& range_end);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end), and respects the given limit. * range_end, i.e., get all keys in the range [key, range_end), and respects
* the given limit.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
*/ */
Response ls(std::string const & key, std::string const &range_end, size_t const limit); Response ls(std::string const& key, std::string const& range_end,
size_t const limit);
/** /**
* Gets a directory listing of the directory identified by the key and range_end, i.e., get * Gets a directory listing of the directory identified by the key and
* all keys in the range [key, range_end), and respects the given limit and revision. * range_end, i.e., get all keys in the range [key, range_end), and respects
* the given limit and revision.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. 0 means no limit. * default parameters to ensure backwards binary compatibility. 0 means no
* limit.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
Response ls(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision); Response ls(std::string const& key, std::string const& range_end,
size_t const limit, int64_t revision);
/** /**
* Gets a directory listing of the directory prefixed by the key. * Gets a directory listing of the directory prefixed by the key.
@ -534,26 +561,27 @@ namespace etcd
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
*/ */
Response keys(std::string const& key, size_t const limit); Response keys(std::string const& key, size_t const limit);
/** /**
* Gets a directory listing of the directory prefixed by the key with specified revision. * Gets a directory listing of the directory prefixed by the key with
* specified revision.
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
Response keys(std::string const& key, size_t const limit, int64_t revision); Response keys(std::string const& key, size_t const limit, int64_t revision);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end). * range [key, range_end).
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
@ -563,54 +591,61 @@ namespace etcd
Response keys(std::string const& key, std::string const& range_end); Response keys(std::string const& key, std::string const& range_end);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end), and respects the given limit. * range [key, range_end), and respects the given limit.
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
*/ */
Response keys(std::string const & key, std::string const &range_end, size_t const limit); Response keys(std::string const& key, std::string const& range_end,
size_t const limit);
/** /**
* List keys identified by the key and range_end, i.e., get all keys in the range [key, * List keys identified by the key and range_end, i.e., get all keys in the
* range_end), and respects the given limit and revision. * range [key, range_end), and respects the given limit and revision.
* *
* Note that only keys are included in the response. * Note that only keys are included in the response.
* *
* @param key is the key to be listed * @param key is the key to be listed
* @param range_end is the end of key range to be listed * @param range_end is the end of key range to be listed
* @param limit is the size limit of results to be listed, we don't use default parameters * @param limit is the size limit of results to be listed, we don't use
* to ensure backwards binary compatibility. * default parameters to ensure backwards binary compatibility.
* @param revision is the revision to be listed * @param revision is the revision to be listed
*/ */
Response keys(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision); Response keys(std::string const& key, std::string const& range_end,
size_t const limit, int64_t revision);
/** /**
* Watches for changes of a key or a subtree. Please note that if you watch e.g. "/testdir" and * Watches for changes of a key or a subtree. Please note that if you watch
* a new key is created, like "/testdir/newkey" then no change happened in the value of * e.g. "/testdir" and a new key is created, like "/testdir/newkey" then no
* "/testdir" so your watch will not detect this. If you want to detect addition and deletion of * change happened in the value of
* directory entries then you have to do a recursive watch. * "/testdir" so your watch will not detect this. If you want to detect
* addition and deletion of directory entries then you have to do a recursive
* watch.
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param recursive if true watch a whole subtree * @param recursive if true watch a whole subtree
*/ */
Response watch(std::string const& key, bool recursive = false); Response watch(std::string const& key, bool recursive = false);
/** /**
* Watches for changes of a key or a subtree from a specific index. The index value can be in the "past". * Watches for changes of a key or a subtree from a specific index. The index
* value can be in the "past".
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param fromIndex the first index we are interested in * @param fromIndex the first index we are interested in
* @param recursive if true watch a whole subtree * @param recursive if true watch a whole subtree
*/ */
Response watch(std::string const & key, int64_t fromIndex, bool recursive = false); Response watch(std::string const& key, int64_t fromIndex,
bool recursive = false);
/** /**
* Watches for changes of a range of keys inside [key, range_end). * Watches for changes of a range of keys inside [key, range_end).
* *
* This overload for `const char *` is to avoid const char * to bool implicit casting. * This overload for `const char *` is to avoid const char * to bool implicit
* casting.
* *
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
@ -626,15 +661,17 @@ namespace etcd
Response watch(std::string const& key, std::string const& range_end); Response watch(std::string const& key, std::string const& range_end);
/** /**
* Watches for changes of a range of keys inside [key, range_end) from a specific index. The index value * Watches for changes of a range of keys inside [key, range_end) from a
* can be in the "past". * specific index. The index value can be in the "past".
* *
* Watches for changes of a key or a subtree from a specific index. The index value can be in the "past". * Watches for changes of a key or a subtree from a specific index. The index
* value can be in the "past".
* @param key is the value or directory to be watched * @param key is the value or directory to be watched
* @param range_end is the end of key range to be removed. * @param range_end is the end of key range to be removed.
* @param fromIndex the first index we are interested in * @param fromIndex the first index we are interested in
*/ */
Response watch(std::string const & key, std::string const &range_end, int64_t fromIndex); Response watch(std::string const& key, std::string const& range_end,
int64_t fromIndex);
/** /**
* Grants a lease. * Grants a lease.
@ -666,23 +703,25 @@ namespace etcd
Response leases(); Response leases();
/** /**
* Gains a lock at a key, using a default created lease, using the default lease (10 seconds), with * Gains a lock at a key, using a default created lease, using the default
* keeping alive has already been taken care of by the library. * lease (10 seconds), with keeping alive has already been taken care of by
* the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
*/ */
Response lock(std::string const& key); Response lock(std::string const& key);
/** /**
* Gains a lock at a key, using a default created lease, using the specified lease TTL (in seconds), with * Gains a lock at a key, using a default created lease, using the specified
* keeping alive has already been taken care of by the library. * lease TTL (in seconds), with keeping alive has already been taken care of
* by the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
* @param lease_ttl is the TTL used to create a lease for the key. * @param lease_ttl is the TTL used to create a lease for the key.
*/ */
Response lock(std::string const& key, int lease_ttl); Response lock(std::string const& key, int lease_ttl);
/** /**
* Gains a lock at a key, using a user-provided lease, the lifetime of the lease won't be taken care * Gains a lock at a key, using a user-provided lease, the lifetime of the
* of by the library. * lease won't be taken care of by the library.
* @param key is the key to be used to request the lock. * @param key is the key to be used to request the lock.
*/ */
Response lock_with_lease(std::string const& key, int64_t lease_id); Response lock_with_lease(std::string const& key, int64_t lease_id);
@ -713,7 +752,8 @@ namespace etcd
* - created rev: the revision of the generated key * - created rev: the revision of the generated key
* - lease: the lease id of the election leader * - lease: the lease id of the election leader
*/ */
Response campaign(std::string const &name, int64_t lease_id, std::string const &value); Response campaign(std::string const& name, int64_t lease_id,
std::string const& value);
/** /**
* Updates the value of election with a new value, with leader key returns by * Updates the value of election with a new value, with leader key returns by
@ -726,7 +766,8 @@ namespace etcd
* @param value is the new value to set. * @param value is the new value to set.
*/ */
Response proclaim(std::string const& name, int64_t lease_id, Response proclaim(std::string const& name, int64_t lease_id,
std::string const &key, int64_t revision, std::string const &value); std::string const& key, int64_t revision,
std::string const& value);
/** /**
* Get the current leader proclamation. * Get the current leader proclamation.
@ -746,6 +787,7 @@ namespace etcd
~Observer(); ~Observer();
// wait at least *one* response from the observer. // wait at least *one* response from the observer.
Response WaitOnce(); Response WaitOnce();
private: private:
std::shared_ptr<etcdv3::AsyncObserveAction> action = nullptr; std::shared_ptr<etcdv3::AsyncObserveAction> action = nullptr;
@ -757,7 +799,8 @@ namespace etcd
* *
* @param name is the names of election to watch. * @param name is the names of election to watch.
* *
* @returns an observer that holds that action and will cancel the request when being destructed. * @returns an observer that holds that action and will cancel the request
* when being destructed.
*/ */
std::unique_ptr<Observer> observe(std::string const& name); std::unique_ptr<Observer> observe(std::string const& name);
@ -776,34 +819,64 @@ namespace etcd
private: private:
// TODO: use std::unique_ptr<> // TODO: use std::unique_ptr<>
std::shared_ptr<etcdv3::AsyncHeadAction> head_internal(); std::shared_ptr<etcdv3::AsyncHeadAction> head_internal();
std::shared_ptr<etcdv3::AsyncRangeAction> get_internal(std::string const & key, int64_t revision=0); std::shared_ptr<etcdv3::AsyncRangeAction> get_internal(std::string const& key,
std::shared_ptr<etcdv3::AsyncSetAction> set_internal(std::string const & key, std::string const & value, int64_t leaseId); int64_t revision = 0);
std::shared_ptr<etcdv3::AsyncSetAction> add_internal(std::string const & key, std::string const & value, int64_t leaseId); std::shared_ptr<etcdv3::AsyncSetAction> set_internal(std::string const& key,
std::shared_ptr<etcdv3::AsyncPutAction> put_internal(std::string const & key, std::string const & value); std::string const& value,
std::shared_ptr<etcdv3::AsyncUpdateAction> modify_internal(std::string const & key, std::string const & value, int64_t leaseId); int64_t leaseId);
std::shared_ptr<etcdv3::AsyncCompareAndSwapAction> modify_if_internal(std::string const & key, std::string const & value, int64_t old_index, std::string const & old_value, int64_t leaseId, etcdv3::AtomicityType const & atomicity_type); std::shared_ptr<etcdv3::AsyncSetAction> add_internal(std::string const& key,
std::shared_ptr<etcdv3::AsyncDeleteAction> rm_internal(std::string const & key); std::string const& value,
std::shared_ptr<etcdv3::AsyncCompareAndDeleteAction> rm_if_internal(std::string const & key, int64_t old_index, const std::string & old_value, etcdv3::AtomicityType const & atomicity_type); int64_t leaseId);
std::shared_ptr<etcdv3::AsyncDeleteAction> rmdir_internal(std::string const & key, bool recursive = false); std::shared_ptr<etcdv3::AsyncPutAction> put_internal(
std::shared_ptr<etcdv3::AsyncDeleteAction> rmdir_internal(std::string const & key, std::string const &range_end); std::string const& key, std::string const& value);
std::shared_ptr<etcdv3::AsyncRangeAction> ls_internal(std::string const & key, size_t const limit, bool const keys_only = false, int64_t revision=0); std::shared_ptr<etcdv3::AsyncUpdateAction> modify_internal(
std::shared_ptr<etcdv3::AsyncRangeAction> ls_internal(std::string const & key, std::string const &range_end, size_t const limit, bool const keys_only = false, int64_t revision=0); std::string const& key, std::string const& value, int64_t leaseId);
std::shared_ptr<etcdv3::AsyncWatchAction> watch_internal(std::string const & key, int64_t fromIndex, bool recursive = false); std::shared_ptr<etcdv3::AsyncCompareAndSwapAction> modify_if_internal(
std::shared_ptr<etcdv3::AsyncWatchAction> watch_internal(std::string const & key, std::string const &range_end, int64_t fromIndex); std::string const& key, std::string const& value, int64_t old_index,
std::shared_ptr<etcdv3::AsyncLeaseRevokeAction> leaserevoke_internal(int64_t lease_id); std::string const& old_value, int64_t leaseId,
std::shared_ptr<etcdv3::AsyncLeaseTimeToLiveAction> leasetimetolive_internal(int64_t lease_id); etcdv3::AtomicityType const& atomicity_type);
std::shared_ptr<etcdv3::AsyncDeleteAction> rm_internal(
std::string const& key);
std::shared_ptr<etcdv3::AsyncCompareAndDeleteAction> rm_if_internal(
std::string const& key, int64_t old_index, const std::string& old_value,
etcdv3::AtomicityType const& atomicity_type);
std::shared_ptr<etcdv3::AsyncDeleteAction> rmdir_internal(
std::string const& key, bool recursive = false);
std::shared_ptr<etcdv3::AsyncDeleteAction> rmdir_internal(
std::string const& key, std::string const& range_end);
std::shared_ptr<etcdv3::AsyncRangeAction> ls_internal(
std::string const& key, size_t const limit, bool const keys_only = false,
int64_t revision = 0);
std::shared_ptr<etcdv3::AsyncRangeAction> ls_internal(
std::string const& key, std::string const& range_end, size_t const limit,
bool const keys_only = false, int64_t revision = 0);
std::shared_ptr<etcdv3::AsyncWatchAction> watch_internal(
std::string const& key, int64_t fromIndex, bool recursive = false);
std::shared_ptr<etcdv3::AsyncWatchAction> watch_internal(
std::string const& key, std::string const& range_end, int64_t fromIndex);
std::shared_ptr<etcdv3::AsyncLeaseRevokeAction> leaserevoke_internal(
int64_t lease_id);
std::shared_ptr<etcdv3::AsyncLeaseTimeToLiveAction> leasetimetolive_internal(
int64_t lease_id);
std::shared_ptr<etcdv3::AsyncLeaseLeasesAction> leases_internal(); std::shared_ptr<etcdv3::AsyncLeaseLeasesAction> leases_internal();
Response lock_internal(std::string const &key, std::shared_ptr<etcd::KeepAlive> const &keepalive); Response lock_internal(std::string const& key,
std::shared_ptr<etcdv3::AsyncLockAction> lock_with_lease_internal(std::string const &key, int64_t lease_id); std::shared_ptr<etcd::KeepAlive> const& keepalive);
std::shared_ptr<etcdv3::AsyncUnlockAction> unlock_internal(std::string const &lock_key); std::shared_ptr<etcdv3::AsyncLockAction> lock_with_lease_internal(
std::shared_ptr<etcdv3::AsyncTxnAction> txn_internal(etcdv3::Transaction const &txn); std::string const& key, int64_t lease_id);
std::shared_ptr<etcdv3::AsyncCampaignAction> campaign_internal(std::string const &name, int64_t lease_id, std::string const &value); std::shared_ptr<etcdv3::AsyncUnlockAction> unlock_internal(
std::string const& lock_key);
std::shared_ptr<etcdv3::AsyncTxnAction> txn_internal(
etcdv3::Transaction const& txn);
std::shared_ptr<etcdv3::AsyncCampaignAction> campaign_internal(
std::string const& name, int64_t lease_id, std::string const& value);
std::shared_ptr<etcdv3::AsyncProclaimAction> proclaim_internal( std::shared_ptr<etcdv3::AsyncProclaimAction> proclaim_internal(
std::string const &name, int64_t lease_id, std::string const& name, int64_t lease_id, std::string const& key,
std::string const &key, int64_t revision, std::string const &value); int64_t revision, std::string const& value);
std::shared_ptr<etcdv3::AsyncLeaderAction> leader_internal(std::string const &name); std::shared_ptr<etcdv3::AsyncLeaderAction> leader_internal(
std::shared_ptr<etcdv3::AsyncResignAction> resign_internal(std::string const &name, int64_t lease_id, std::string const& name);
std::string const &key, int64_t revision); std::shared_ptr<etcdv3::AsyncResignAction> resign_internal(
std::string const& name, int64_t lease_id, std::string const& key,
int64_t revision);
public: public:
/** /**
@ -824,8 +897,10 @@ namespace etcd
* Set a timeout value for grpc operations. * Set a timeout value for grpc operations.
*/ */
template <typename Period = std::micro> template <typename Period = std::micro>
void set_grpc_timeout(std::chrono::duration<std::chrono::microseconds::rep, Period> const &timeout) { void set_grpc_timeout(std::chrono::duration<std::chrono::microseconds::rep,
grpc_timeout = std::chrono::duration_cast<std::chrono::milliseconds>(timeout); Period> const& timeout) {
grpc_timeout =
std::chrono::duration_cast<std::chrono::milliseconds>(timeout);
} }
/** /**
@ -842,8 +917,10 @@ namespace etcd
std::shared_ptr<grpc_impl::Channel> channel; std::shared_ptr<grpc_impl::Channel> channel;
#endif #endif
mutable std::unique_ptr<TokenAuthenticator, TokenAuthenticatorDeleter> token_authenticator; mutable std::unique_ptr<TokenAuthenticator, TokenAuthenticatorDeleter>
mutable std::chrono::microseconds grpc_timeout = std::chrono::microseconds::zero(); token_authenticator;
mutable std::chrono::microseconds grpc_timeout =
std::chrono::microseconds::zero();
struct EtcdServerStubs; struct EtcdServerStubs;
struct EtcdServerStubsDeleter { struct EtcdServerStubsDeleter {
@ -860,6 +937,6 @@ namespace etcd
friend class Client; friend class Client;
}; };
} } // namespace etcd
#endif #endif

View File

@ -11,14 +11,13 @@ namespace etcdv3 {
namespace mvccpb { namespace mvccpb {
class KeyValue; class KeyValue;
class Event; class Event;
} } // namespace mvccpb
namespace electionpb { namespace electionpb {
class LeaderKey; class LeaderKey;
} }
namespace etcd namespace etcd {
{
class Value; class Value;
class Event; class Event;
class Response; class Response;
@ -28,12 +27,11 @@ namespace etcd
/** /**
* Represents a value object received from the etcd server * Represents a value object received from the etcd server
*/ */
class Value class Value {
{
public: public:
/** /**
* Returns true if this value represents a directory on the server. If true the as_string() * Returns true if this value represents a directory on the server. If true
* method is meaningless. * the as_string() method is meaningless.
*/ */
bool is_dir() const; bool is_dir() const;
@ -73,7 +71,8 @@ namespace etcd
friend class Client; friend class Client;
friend class SyncClient; friend class SyncClient;
friend class Response; friend class Response;
friend class BaseResponse; //deliberately done since Value class will be removed during full V3 friend class BaseResponse; // deliberately done since Value class will be
// removed during full V3
friend class DeleteRpcResponse; friend class DeleteRpcResponse;
friend class AsyncDeleteResponse; friend class AsyncDeleteResponse;
@ -94,8 +93,7 @@ namespace etcd
typedef std::vector<Value> Values; typedef std::vector<Value> Values;
class Event class Event {
{
public: public:
enum class EventType { enum class EventType {
PUT, PUT,
@ -125,6 +123,6 @@ namespace etcd
}; };
typedef std::vector<Event> Events; typedef std::vector<Event> Events;
} } // namespace etcd
#endif #endif

View File

@ -8,32 +8,24 @@
#include "etcd/Response.hpp" #include "etcd/Response.hpp"
namespace etcd namespace etcd {
{
// forward declaration to avoid header/library dependency // forward declaration to avoid header/library dependency
class Client; class Client;
class Watcher class Watcher {
{
public: public:
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(SyncClient const& client, std::string const& key, Watcher(SyncClient const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback);
std::function<void(Response)> callback);
Watcher(SyncClient const& client, std::string const& key, Watcher(SyncClient const& client, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback);
std::function<void(Response)> callback);
Watcher(Client const& client, std::string const& key, int64_t fromIndex, Watcher(Client const& client, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(SyncClient const& client, std::string const& key, int64_t fromIndex, Watcher(SyncClient const& client, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback); std::function<void(Response)> callback);
@ -41,78 +33,60 @@ namespace etcd
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback); std::function<void(Response)> callback);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback);
std::function<void(Response)> callback);
Watcher(std::string const& address, std::string const& key, int64_t fromIndex, Watcher(std::string const& address, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive = false);
bool recursive=false);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback); std::function<void(Response)> callback);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key, std::function<void(Response)> callback, bool recursive = false,
std::function<void(Response)> callback,
bool recursive=false,
int const auth_token_ttl = 300); int const auth_token_ttl = 300);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key, std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback,
int const auth_token_ttl = 300);
Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
int64_t fromIndex, std::function<void(Response)> callback,
bool recursive = false, int const auth_token_ttl = 300);
Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
int const auth_token_ttl = 300); int const auth_token_ttl = 300);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& ca,
std::string const & username, std::string const & password, std::string const& cert, std::string const& privkey,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
bool recursive=false,
int const auth_token_ttl = 300);
Watcher(std::string const & address,
std::string const & username, std::string const & password,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
int const auth_token_ttl = 300);
Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const& key, int64_t fromIndex, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, bool recursive = false, std::function<void(Response)> callback, bool recursive = false,
std::string const& target_name_override = ""); std::string const& target_name_override = "");
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert, std::string const& key, std::string const& range_end,
std::string const & privkey, int64_t fromIndex, std::function<void(Response)> callback,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::string const& target_name_override = ""); std::string const& target_name_override = "");
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(SyncClient const& client, std::string const& key, Watcher(SyncClient const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback); std::function<void(bool)> wait_callback);
Watcher(SyncClient const& client, std::string const& key, Watcher(SyncClient const& client, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback); std::function<void(bool)> wait_callback);
Watcher(Client const& client, std::string const& key, int64_t fromIndex, Watcher(Client const& client, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(SyncClient const& client, std::string const& key, int64_t fromIndex, Watcher(SyncClient const& client, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(Client const& client, std::string const& key, Watcher(Client const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
@ -123,61 +97,48 @@ namespace etcd
std::function<void(bool)> wait_callback); std::function<void(bool)> wait_callback);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback); std::function<void(bool)> wait_callback);
Watcher(std::string const& address, std::string const& key, int64_t fromIndex, Watcher(std::string const& address, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false);
bool recursive=false);
Watcher(std::string const& address, std::string const& key, Watcher(std::string const& address, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback); std::function<void(bool)> wait_callback);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false,
bool recursive=false,
int const auth_token_ttl = 300); int const auth_token_ttl = 300);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key, std::string const &range_end, std::string const& range_end, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
int const auth_token_ttl = 300);
Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
int64_t fromIndex, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, bool recursive = false,
int const auth_token_ttl = 300);
Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback,
int const auth_token_ttl = 300); int const auth_token_ttl = 300);
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& ca,
std::string const & username, std::string const & password, std::string const& cert, std::string const& privkey,
std::string const& key, int64_t fromIndex, std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive = false,
bool recursive=false,
int const auth_token_ttl = 300);
Watcher(std::string const & address,
std::string const & username, std::string const & password,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
int const auth_token_ttl = 300);
Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
bool recursive=false,
std::string const& target_name_override = ""); std::string const& target_name_override = "");
Watcher(std::string const & address, Watcher(std::string const& address, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert, std::string const& key, std::string const& range_end,
std::string const & privkey, int64_t fromIndex, std::function<void(Response)> callback,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback,
std::string const& target_name_override = ""); std::string const& target_name_override = "");
@ -185,8 +146,8 @@ namespace etcd
Watcher(Watcher&&) = delete; Watcher(Watcher&&) = delete;
/** /**
* Wait util the task has been stopped, actively or passively, e.g., the watcher * Wait util the task has been stopped, actively or passively, e.g., the
* get cancelled or the server closes the connection. * watcher get cancelled or the server closes the connection.
* *
* Returns true if the watcher is been normally cancelled, otherwise false. * Returns true if the watcher is been normally cancelled, otherwise false.
*/ */
@ -195,7 +156,8 @@ namespace etcd
/** /**
* An async wait, the callback will be called when the task has been stopped. * An async wait, the callback will be called when the task has been stopped.
* *
* The callback parameter would be true if the watch is been normally cancelled. * The callback parameter would be true if the watch is been normally
* cancelled.
* *
* Note that you shouldn't use the watcher itself inside the `Wait()` callback * Note that you shouldn't use the watcher itself inside the `Wait()` callback
* as the callback will be invoked in a separate **detached** thread where the * as the callback will be invoked in a separate **detached** thread where the
@ -216,16 +178,16 @@ namespace etcd
~Watcher(); ~Watcher();
protected: protected:
void doWatch(std::string const & key, void doWatch(std::string const& key, std::string const& range_end,
std::string const & range_end,
std::string const& auth_token, std::string const& auth_token,
std::function<void(Response)> callback); std::function<void(Response)> callback);
std::function<void(Response)> callback; std::function<void(Response)> callback;
std::function<void(bool)> wait_callback; std::function<void(bool)> wait_callback;
// Don't use `pplx::task` to avoid sharing thread pool with other actions on the client // Don't use `pplx::task` to avoid sharing thread pool with other actions on
// to avoid any potential blocking, which may block the keepalive loop and evict the lease. // the client to avoid any potential blocking, which may block the keepalive
// loop and evict the lease.
std::thread task_; std::thread task_;
struct EtcdServerStubs; struct EtcdServerStubs;
@ -239,6 +201,6 @@ namespace etcd
bool recursive; bool recursive;
std::atomic_bool cancelled; std::atomic_bool cancelled;
}; };
} } // namespace etcd
#endif #endif

View File

@ -6,33 +6,27 @@
#include <grpc++/grpc++.h> #include <grpc++/grpc++.h>
#include "proto/rpc.grpc.pb.h" #include "proto/rpc.grpc.pb.h"
#include "proto/v3lock.grpc.pb.h"
#include "proto/v3election.grpc.pb.h" #include "proto/v3election.grpc.pb.h"
#include "proto/v3lock.grpc.pb.h"
using grpc::ClientContext; using grpc::ClientContext;
using grpc::CompletionQueue; using grpc::CompletionQueue;
using grpc::Status; using grpc::Status;
using etcdserverpb::KV; using etcdserverpb::KV;
using etcdserverpb::Watch;
using etcdserverpb::Lease; using etcdserverpb::Lease;
using v3lockpb::Lock; using etcdserverpb::Watch;
using v3electionpb::Election; using v3electionpb::Election;
using v3lockpb::Lock;
namespace etcd { namespace etcd {
class Response; class Response;
} }
namespace etcdv3 namespace etcdv3 {
{ enum class AtomicityType { PREV_INDEX = 0, PREV_VALUE = 1 };
enum class AtomicityType
{
PREV_INDEX = 0,
PREV_VALUE = 1
};
struct ActionParameters struct ActionParameters {
{
ActionParameters(); ActionParameters();
bool withPrefix; bool withPrefix;
int64_t revision = 0; int64_t revision = 0;
@ -61,8 +55,7 @@ namespace etcdv3
void dump(std::ostream& os) const; void dump(std::ostream& os) const;
}; };
class Action class Action {
{
public: public:
Action(etcdv3::ActionParameters const& params); Action(etcdv3::ActionParameters const& params);
Action(etcdv3::ActionParameters&& params); Action(etcdv3::ActionParameters&& params);
@ -70,12 +63,14 @@ namespace etcdv3
void waitForResponse(); void waitForResponse();
const std::chrono::high_resolution_clock::time_point startTimepoint(); const std::chrono::high_resolution_clock::time_point startTimepoint();
protected: protected:
Status status; Status status;
ClientContext context; ClientContext context;
CompletionQueue cq_; CompletionQueue cq_;
etcdv3::ActionParameters parameters; etcdv3::ActionParameters parameters;
std::chrono::high_resolution_clock::time_point start_timepoint; std::chrono::high_resolution_clock::time_point start_timepoint;
private: private:
// Init things like auth token, etc. // Init things like auth token, etc.
void InitAction(); void InitAction();
@ -86,6 +81,6 @@ namespace etcdv3
namespace detail { namespace detail {
std::string string_plus_one(std::string const& value); std::string string_plus_one(std::string const& value);
std::string resolve_etcd_endpoints(std::string const& default_endpoints); std::string resolve_etcd_endpoints(std::string const& default_endpoints);
} } // namespace detail
} } // namespace etcdv3
#endif #endif

View File

@ -6,16 +6,16 @@
#include <grpc++/grpc++.h> #include <grpc++/grpc++.h>
#include "proto/rpc.pb.h"
#include "proto/rpc.grpc.pb.h" #include "proto/rpc.grpc.pb.h"
#include "proto/v3election.pb.h" #include "proto/rpc.pb.h"
#include "proto/v3election.grpc.pb.h" #include "proto/v3election.grpc.pb.h"
#include "proto/v3lock.pb.h" #include "proto/v3election.pb.h"
#include "proto/v3lock.grpc.pb.h" #include "proto/v3lock.grpc.pb.h"
#include "proto/v3lock.pb.h"
#include "etcd/Response.hpp"
#include "etcd/v3/Action.hpp" #include "etcd/v3/Action.hpp"
#include "etcd/v3/V3Response.hpp" #include "etcd/v3/V3Response.hpp"
#include "etcd/Response.hpp"
using grpc::ClientAsyncReader; using grpc::ClientAsyncReader;
using grpc::ClientAsyncReaderWriter; using grpc::ClientAsyncReaderWriter;
@ -23,28 +23,20 @@ using grpc::ClientAsyncResponseReader;
using etcdserverpb::KV; using etcdserverpb::KV;
using v3electionpb::CampaignRequest;
using v3electionpb::CampaignResponse;
using etcdserverpb::DeleteRangeRequest; using etcdserverpb::DeleteRangeRequest;
using etcdserverpb::DeleteRangeResponse; using etcdserverpb::DeleteRangeResponse;
using etcdserverpb::LeaseCheckpointRequest; using etcdserverpb::LeaseCheckpointRequest;
using etcdserverpb::LeaseCheckpointResponse; using etcdserverpb::LeaseCheckpointResponse;
using etcdserverpb::LeaseGrantRequest; using etcdserverpb::LeaseGrantRequest;
using etcdserverpb::LeaseGrantResponse; using etcdserverpb::LeaseGrantResponse;
using etcdserverpb::LeaseRevokeRequest;
using etcdserverpb::LeaseRevokeResponse;
using etcdserverpb::LeaseKeepAliveRequest; using etcdserverpb::LeaseKeepAliveRequest;
using etcdserverpb::LeaseKeepAliveResponse; using etcdserverpb::LeaseKeepAliveResponse;
using etcdserverpb::LeaseLeasesRequest; using etcdserverpb::LeaseLeasesRequest;
using etcdserverpb::LeaseLeasesResponse; using etcdserverpb::LeaseLeasesResponse;
using etcdserverpb::LeaseRevokeRequest;
using etcdserverpb::LeaseRevokeResponse;
using etcdserverpb::LeaseTimeToLiveRequest; using etcdserverpb::LeaseTimeToLiveRequest;
using etcdserverpb::LeaseTimeToLiveResponse; using etcdserverpb::LeaseTimeToLiveResponse;
using etcdserverpb::TxnRequest;
using etcdserverpb::TxnResponse;
using etcdserverpb::RangeRequest;
using etcdserverpb::RangeResponse;
using v3electionpb::ResignRequest;
using v3electionpb::ResignResponse;
using etcdserverpb::PutRequest; using etcdserverpb::PutRequest;
using etcdserverpb::PutResponse; using etcdserverpb::PutResponse;
using etcdserverpb::RangeRequest; using etcdserverpb::RangeRequest;
@ -53,10 +45,14 @@ using etcdserverpb::TxnRequest;
using etcdserverpb::TxnResponse; using etcdserverpb::TxnResponse;
using etcdserverpb::WatchRequest; using etcdserverpb::WatchRequest;
using etcdserverpb::WatchResponse; using etcdserverpb::WatchResponse;
using v3electionpb::CampaignRequest;
using v3electionpb::CampaignResponse;
using v3electionpb::LeaderRequest; using v3electionpb::LeaderRequest;
using v3electionpb::LeaderResponse; using v3electionpb::LeaderResponse;
using v3electionpb::ProclaimRequest; using v3electionpb::ProclaimRequest;
using v3electionpb::ProclaimResponse; using v3electionpb::ProclaimResponse;
using v3electionpb::ResignRequest;
using v3electionpb::ResignResponse;
using v3lockpb::LockRequest; using v3lockpb::LockRequest;
using v3lockpb::LockResponse; using v3lockpb::LockResponse;
using v3lockpb::UnlockRequest; using v3lockpb::UnlockRequest;
@ -71,191 +67,176 @@ namespace etcdv3 {
} }
namespace etcdv3 { namespace etcdv3 {
class AsyncCampaignResponse : public etcdv3::V3Response class AsyncCampaignResponse : public etcdv3::V3Response {
{
public: public:
AsyncCampaignResponse(){}; AsyncCampaignResponse(){};
void ParseResponse(CampaignResponse& resp); void ParseResponse(CampaignResponse& resp);
}; };
class AsyncDeleteResponse : public etcdv3::V3Response class AsyncDeleteResponse : public etcdv3::V3Response {
{
public: public:
AsyncDeleteResponse(){}; AsyncDeleteResponse(){};
void ParseResponse(std::string const& key, bool prefix, DeleteRangeResponse& resp); void ParseResponse(std::string const& key, bool prefix,
DeleteRangeResponse& resp);
}; };
class AsyncHeadResponse : public etcdv3::V3Response class AsyncHeadResponse : public etcdv3::V3Response {
{
public: public:
AsyncHeadResponse(){}; AsyncHeadResponse(){};
void ParseResponse(RangeResponse& resp); void ParseResponse(RangeResponse& resp);
}; };
class AsyncLeaderResponse : public etcdv3::V3Response class AsyncLeaderResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaderResponse(){}; AsyncLeaderResponse(){};
void ParseResponse(LeaderResponse& resp); void ParseResponse(LeaderResponse& resp);
}; };
class AsyncLeaseGrantResponse : public etcdv3::V3Response class AsyncLeaseGrantResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaseGrantResponse(){}; AsyncLeaseGrantResponse(){};
void ParseResponse(LeaseGrantResponse& resp); void ParseResponse(LeaseGrantResponse& resp);
}; };
class AsyncLeaseKeepAliveResponse : public etcdv3::V3Response class AsyncLeaseKeepAliveResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaseKeepAliveResponse(){}; AsyncLeaseKeepAliveResponse(){};
void ParseResponse(LeaseKeepAliveResponse& resp); void ParseResponse(LeaseKeepAliveResponse& resp);
}; };
class AsyncLeaseLeasesResponse : public etcdv3::V3Response class AsyncLeaseLeasesResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaseLeasesResponse(){}; AsyncLeaseLeasesResponse(){};
void ParseResponse(LeaseLeasesResponse& resp); void ParseResponse(LeaseLeasesResponse& resp);
}; };
class AsyncLeaseRevokeResponse : public etcdv3::V3Response class AsyncLeaseRevokeResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaseRevokeResponse(){}; AsyncLeaseRevokeResponse(){};
void ParseResponse(LeaseRevokeResponse& resp); void ParseResponse(LeaseRevokeResponse& resp);
}; };
class AsyncLeaseTimeToLiveResponse : public etcdv3::V3Response class AsyncLeaseTimeToLiveResponse : public etcdv3::V3Response {
{
public: public:
AsyncLeaseTimeToLiveResponse(){}; AsyncLeaseTimeToLiveResponse(){};
void ParseResponse(LeaseTimeToLiveResponse& resp); void ParseResponse(LeaseTimeToLiveResponse& resp);
}; };
class AsyncLockResponse : public etcdv3::V3Response class AsyncLockResponse : public etcdv3::V3Response {
{
public: public:
AsyncLockResponse(){}; AsyncLockResponse(){};
void ParseResponse(LockResponse& resp); void ParseResponse(LockResponse& resp);
}; };
class AsyncObserveResponse : public etcdv3::V3Response class AsyncObserveResponse : public etcdv3::V3Response {
{
public: public:
AsyncObserveResponse(){}; AsyncObserveResponse(){};
void ParseResponse(LeaderResponse& resp); void ParseResponse(LeaderResponse& resp);
}; };
class AsyncProclaimResponse : public etcdv3::V3Response class AsyncProclaimResponse : public etcdv3::V3Response {
{
public: public:
AsyncProclaimResponse(){}; AsyncProclaimResponse(){};
void ParseResponse(ProclaimResponse& resp); void ParseResponse(ProclaimResponse& resp);
}; };
class AsyncPutResponse : public etcdv3::V3Response class AsyncPutResponse : public etcdv3::V3Response {
{
public: public:
AsyncPutResponse(){}; AsyncPutResponse(){};
void ParseResponse(PutResponse& resp); void ParseResponse(PutResponse& resp);
}; };
class AsyncRangeResponse : public etcdv3::V3Response class AsyncRangeResponse : public etcdv3::V3Response {
{
public: public:
AsyncRangeResponse(){}; AsyncRangeResponse(){};
void ParseResponse(RangeResponse& resp, bool prefix = false); void ParseResponse(RangeResponse& resp, bool prefix = false);
}; };
class AsyncResignResponse : public etcdv3::V3Response class AsyncResignResponse : public etcdv3::V3Response {
{
public: public:
AsyncResignResponse(){}; AsyncResignResponse(){};
void ParseResponse(ResignResponse& resp); void ParseResponse(ResignResponse& resp);
}; };
class AsyncTxnResponse : public etcdv3::V3Response class AsyncTxnResponse : public etcdv3::V3Response {
{
public: public:
AsyncTxnResponse(){}; AsyncTxnResponse(){};
void ParseResponse(TxnResponse& resp); void ParseResponse(TxnResponse& resp);
void ParseResponse(std::string const& key, bool prefix, TxnResponse& resp); void ParseResponse(std::string const& key, bool prefix, TxnResponse& resp);
}; };
class AsyncUnlockResponse : public etcdv3::V3Response class AsyncUnlockResponse : public etcdv3::V3Response {
{
public: public:
AsyncUnlockResponse(){}; AsyncUnlockResponse(){};
void ParseResponse(UnlockResponse& resp); void ParseResponse(UnlockResponse& resp);
}; };
class AsyncWatchResponse : public etcdv3::V3Response class AsyncWatchResponse : public etcdv3::V3Response {
{
public: public:
AsyncWatchResponse(){}; AsyncWatchResponse(){};
void ParseResponse(WatchResponse& resp); void ParseResponse(WatchResponse& resp);
}; };
} } // namespace etcdv3
namespace etcdv3 namespace etcdv3 {
{ class AsyncCampaignAction : public etcdv3::Action {
class AsyncCampaignAction : public etcdv3::Action
{
public: public:
AsyncCampaignAction(etcdv3::ActionParameters&& params); AsyncCampaignAction(etcdv3::ActionParameters&& params);
AsyncCampaignResponse ParseResponse(); AsyncCampaignResponse ParseResponse();
private: private:
CampaignResponse reply; CampaignResponse reply;
std::unique_ptr<ClientAsyncResponseReader<CampaignResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<CampaignResponse>> response_reader;
}; };
class AsyncCompareAndDeleteAction : public etcdv3::Action class AsyncCompareAndDeleteAction : public etcdv3::Action {
{
public: public:
AsyncCompareAndDeleteAction(etcdv3::ActionParameters && params, etcdv3::AtomicityType type); AsyncCompareAndDeleteAction(etcdv3::ActionParameters&& params,
etcdv3::AtomicityType type);
AsyncTxnResponse ParseResponse(); AsyncTxnResponse ParseResponse();
private: private:
TxnResponse reply; TxnResponse reply;
std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader;
}; };
class AsyncCompareAndSwapAction : public etcdv3::Action class AsyncCompareAndSwapAction : public etcdv3::Action {
{
public: public:
AsyncCompareAndSwapAction(etcdv3::ActionParameters && params, etcdv3::AtomicityType type); AsyncCompareAndSwapAction(etcdv3::ActionParameters&& params,
etcdv3::AtomicityType type);
AsyncTxnResponse ParseResponse(); AsyncTxnResponse ParseResponse();
private: private:
TxnResponse reply; TxnResponse reply;
std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader;
}; };
class AsyncDeleteAction : public etcdv3::Action class AsyncDeleteAction : public etcdv3::Action {
{
public: public:
AsyncDeleteAction(etcdv3::ActionParameters&& params); AsyncDeleteAction(etcdv3::ActionParameters&& params);
AsyncDeleteResponse ParseResponse(); AsyncDeleteResponse ParseResponse();
private: private:
DeleteRangeResponse reply; DeleteRangeResponse reply;
std::unique_ptr<ClientAsyncResponseReader<DeleteRangeResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<DeleteRangeResponse>>
response_reader;
}; };
class AsyncHeadAction : public etcdv3::Action class AsyncHeadAction : public etcdv3::Action {
{
public: public:
AsyncHeadAction(etcdv3::ActionParameters&& params); AsyncHeadAction(etcdv3::ActionParameters&& params);
AsyncHeadResponse ParseResponse(); AsyncHeadResponse ParseResponse();
private: private:
RangeResponse reply; RangeResponse reply;
std::unique_ptr<ClientAsyncResponseReader<RangeResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<RangeResponse>> response_reader;
}; };
class AsyncLeaderAction : public etcdv3::Action class AsyncLeaderAction : public etcdv3::Action {
{
public: public:
AsyncLeaderAction(etcdv3::ActionParameters&& params); AsyncLeaderAction(etcdv3::ActionParameters&& params);
AsyncLeaderResponse ParseResponse(); AsyncLeaderResponse ParseResponse();
private: private:
LeaderResponse reply; LeaderResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LeaderResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LeaderResponse>> response_reader;
@ -265,9 +246,11 @@ namespace etcdv3
public: public:
AsyncLeaseGrantAction(etcdv3::ActionParameters&& params); AsyncLeaseGrantAction(etcdv3::ActionParameters&& params);
AsyncLeaseGrantResponse ParseResponse(); AsyncLeaseGrantResponse ParseResponse();
private: private:
LeaseGrantResponse reply; LeaseGrantResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LeaseGrantResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LeaseGrantResponse>>
response_reader;
}; };
class AsyncLeaseKeepAliveAction : public etcdv3::Action { class AsyncLeaseKeepAliveAction : public etcdv3::Action {
@ -283,7 +266,9 @@ namespace etcdv3
etcdv3::ActionParameters& mutable_parameters(); etcdv3::ActionParameters& mutable_parameters();
LeaseKeepAliveResponse reply; LeaseKeepAliveResponse reply;
std::unique_ptr<ClientAsyncReaderWriter<LeaseKeepAliveRequest, LeaseKeepAliveResponse>> stream; std::unique_ptr<
ClientAsyncReaderWriter<LeaseKeepAliveRequest, LeaseKeepAliveResponse>>
stream;
LeaseKeepAliveRequest req; LeaseKeepAliveRequest req;
bool isCancelled; bool isCancelled;
@ -296,47 +281,53 @@ namespace etcdv3
public: public:
AsyncLeaseLeasesAction(etcdv3::ActionParameters&& params); AsyncLeaseLeasesAction(etcdv3::ActionParameters&& params);
AsyncLeaseLeasesResponse ParseResponse(); AsyncLeaseLeasesResponse ParseResponse();
private: private:
LeaseLeasesResponse reply; LeaseLeasesResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LeaseLeasesResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LeaseLeasesResponse>>
response_reader;
}; };
class AsyncLeaseRevokeAction : public etcdv3::Action { class AsyncLeaseRevokeAction : public etcdv3::Action {
public: public:
AsyncLeaseRevokeAction(etcdv3::ActionParameters&& params); AsyncLeaseRevokeAction(etcdv3::ActionParameters&& params);
AsyncLeaseRevokeResponse ParseResponse(); AsyncLeaseRevokeResponse ParseResponse();
private: private:
LeaseRevokeResponse reply; LeaseRevokeResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LeaseRevokeResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LeaseRevokeResponse>>
response_reader;
}; };
class AsyncLeaseTimeToLiveAction : public etcdv3::Action { class AsyncLeaseTimeToLiveAction : public etcdv3::Action {
public: public:
AsyncLeaseTimeToLiveAction(etcdv3::ActionParameters&& params); AsyncLeaseTimeToLiveAction(etcdv3::ActionParameters&& params);
AsyncLeaseTimeToLiveResponse ParseResponse(); AsyncLeaseTimeToLiveResponse ParseResponse();
private: private:
LeaseTimeToLiveResponse reply; LeaseTimeToLiveResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LeaseTimeToLiveResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LeaseTimeToLiveResponse>>
response_reader;
}; };
class AsyncLockAction : public etcdv3::Action class AsyncLockAction : public etcdv3::Action {
{
public: public:
AsyncLockAction(etcdv3::ActionParameters&& params); AsyncLockAction(etcdv3::ActionParameters&& params);
AsyncLockResponse ParseResponse(); AsyncLockResponse ParseResponse();
private: private:
LockResponse reply; LockResponse reply;
std::unique_ptr<ClientAsyncResponseReader<LockResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<LockResponse>> response_reader;
}; };
class AsyncObserveAction : public etcdv3::Action class AsyncObserveAction : public etcdv3::Action {
{
public: public:
AsyncObserveAction(etcdv3::ActionParameters&& params); AsyncObserveAction(etcdv3::ActionParameters&& params);
AsyncObserveResponse ParseResponse(); AsyncObserveResponse ParseResponse();
void waitForResponse(); void waitForResponse();
void CancelObserve(); void CancelObserve();
bool Cancelled() const; bool Cancelled() const;
private: private:
LeaderResponse reply; LeaderResponse reply;
std::unique_ptr<ClientAsyncReader<LeaderResponse>> response_reader; std::unique_ptr<ClientAsyncReader<LeaderResponse>> response_reader;
@ -344,89 +335,89 @@ namespace etcdv3
std::mutex protect_is_cancalled; std::mutex protect_is_cancalled;
}; };
class AsyncProclaimAction : public etcdv3::Action class AsyncProclaimAction : public etcdv3::Action {
{
public: public:
AsyncProclaimAction(etcdv3::ActionParameters&& params); AsyncProclaimAction(etcdv3::ActionParameters&& params);
AsyncProclaimResponse ParseResponse(); AsyncProclaimResponse ParseResponse();
private: private:
ProclaimResponse reply; ProclaimResponse reply;
std::unique_ptr<ClientAsyncResponseReader<ProclaimResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<ProclaimResponse>> response_reader;
}; };
class AsyncPutAction : public etcdv3::Action class AsyncPutAction : public etcdv3::Action {
{
public: public:
AsyncPutAction(etcdv3::ActionParameters&& params); AsyncPutAction(etcdv3::ActionParameters&& params);
AsyncPutResponse ParseResponse(); AsyncPutResponse ParseResponse();
private: private:
PutResponse reply; PutResponse reply;
std::unique_ptr<ClientAsyncResponseReader<PutResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<PutResponse>> response_reader;
}; };
class AsyncRangeAction : public etcdv3::Action class AsyncRangeAction : public etcdv3::Action {
{
public: public:
AsyncRangeAction(etcdv3::ActionParameters&& params); AsyncRangeAction(etcdv3::ActionParameters&& params);
AsyncRangeResponse ParseResponse(); AsyncRangeResponse ParseResponse();
private: private:
RangeResponse reply; RangeResponse reply;
std::unique_ptr<ClientAsyncResponseReader<RangeResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<RangeResponse>> response_reader;
}; };
class AsyncResignAction : public etcdv3::Action class AsyncResignAction : public etcdv3::Action {
{
public: public:
AsyncResignAction(etcdv3::ActionParameters&& params); AsyncResignAction(etcdv3::ActionParameters&& params);
AsyncResignResponse ParseResponse(); AsyncResignResponse ParseResponse();
private: private:
ResignResponse reply; ResignResponse reply;
std::unique_ptr<ClientAsyncResponseReader<ResignResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<ResignResponse>> response_reader;
}; };
class AsyncSetAction : public etcdv3::Action class AsyncSetAction : public etcdv3::Action {
{
public: public:
AsyncSetAction(etcdv3::ActionParameters&& params, bool create = false); AsyncSetAction(etcdv3::ActionParameters&& params, bool create = false);
AsyncTxnResponse ParseResponse(); AsyncTxnResponse ParseResponse();
private: private:
TxnResponse reply; TxnResponse reply;
std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader;
bool isCreate; bool isCreate;
}; };
class AsyncTxnAction : public etcdv3::Action class AsyncTxnAction : public etcdv3::Action {
{
public: public:
AsyncTxnAction(etcdv3::ActionParameters && params, etcdv3::Transaction const &tx); AsyncTxnAction(etcdv3::ActionParameters&& params,
etcdv3::Transaction const& tx);
AsyncTxnResponse ParseResponse(); AsyncTxnResponse ParseResponse();
private: private:
TxnResponse reply; TxnResponse reply;
std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader;
}; };
class AsyncUnlockAction : public etcdv3::Action class AsyncUnlockAction : public etcdv3::Action {
{
public: public:
AsyncUnlockAction(etcdv3::ActionParameters&& params); AsyncUnlockAction(etcdv3::ActionParameters&& params);
AsyncUnlockResponse ParseResponse(); AsyncUnlockResponse ParseResponse();
private: private:
UnlockResponse reply; UnlockResponse reply;
std::unique_ptr<ClientAsyncResponseReader<UnlockResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<UnlockResponse>> response_reader;
}; };
class AsyncUpdateAction : public etcdv3::Action class AsyncUpdateAction : public etcdv3::Action {
{
public: public:
AsyncUpdateAction(etcdv3::ActionParameters&& params); AsyncUpdateAction(etcdv3::ActionParameters&& params);
AsyncTxnResponse ParseResponse(); AsyncTxnResponse ParseResponse();
private: private:
TxnResponse reply; TxnResponse reply;
std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader;
}; };
class AsyncWatchAction : public etcdv3::Action class AsyncWatchAction : public etcdv3::Action {
{
public: public:
AsyncWatchAction(etcdv3::ActionParameters&& params); AsyncWatchAction(etcdv3::ActionParameters&& params);
AsyncWatchResponse ParseResponse(); AsyncWatchResponse ParseResponse();
@ -434,12 +425,13 @@ namespace etcdv3
void waitForResponse(std::function<void(etcd::Response)> callback); void waitForResponse(std::function<void(etcd::Response)> callback);
void CancelWatch(); void CancelWatch();
bool Cancelled() const; bool Cancelled() const;
private: private:
int64_t watch_id = -1; int64_t watch_id = -1;
WatchResponse reply; WatchResponse reply;
std::unique_ptr<ClientAsyncReaderWriter<WatchRequest, WatchResponse>> stream; std::unique_ptr<ClientAsyncReaderWriter<WatchRequest, WatchResponse>> stream;
std::atomic_bool isCancelled; std::atomic_bool isCancelled;
}; };
} } // namespace etcdv3
#endif #endif

View File

@ -3,18 +3,16 @@
#include "proto/kv.pb.h" #include "proto/kv.pb.h"
namespace etcdv3 {
namespace etcdv3 class KeyValue {
{
class KeyValue
{
public: public:
KeyValue(); KeyValue();
mvccpb::KeyValue kvs; mvccpb::KeyValue kvs;
void set_ttl(int ttl); void set_ttl(int ttl);
int get_ttl() const; int get_ttl() const;
private: private:
int ttl; int ttl;
}; };
} } // namespace etcdv3
#endif #endif

View File

@ -1,8 +1,8 @@
#ifndef V3_SRC_TRANSACTION_HPP_ #ifndef V3_SRC_TRANSACTION_HPP_
#define V3_SRC_TRANSACTION_HPP_ #define V3_SRC_TRANSACTION_HPP_
#include <string>
#include <memory> #include <memory>
#include <string>
namespace etcdserverpb { namespace etcdserverpb {
class TxnRequest; class TxnRequest;
@ -39,11 +39,17 @@ public:
void init_compare(int64_t old_value, CompareResult, CompareTarget); void init_compare(int64_t old_value, CompareResult, CompareTarget);
void setup_basic_failure_operation(std::string const& key); void setup_basic_failure_operation(std::string const& key);
void setup_set_failure_operation(std::string const &key, std::string const &value, int64_t leaseid); void setup_set_failure_operation(std::string const& key,
void setup_basic_create_sequence(std::string const &key, std::string const &value, int64_t leaseid); std::string const& value, int64_t leaseid);
void setup_compare_and_swap_sequence(std::string const &valueToSwap, int64_t leaseid); void setup_basic_create_sequence(std::string const& key,
void setup_delete_sequence(std::string const &key, std::string const &range_end, bool recursive); std::string const& value, int64_t leaseid);
void setup_delete_failure_operation(std::string const &key, std::string const &range_end, bool recursive); void setup_compare_and_swap_sequence(std::string const& valueToSwap,
int64_t leaseid);
void setup_delete_sequence(std::string const& key,
std::string const& range_end, bool recursive);
void setup_delete_failure_operation(std::string const& key,
std::string const& range_end,
bool recursive);
void setup_compare_and_delete_operation(std::string const& key); void setup_compare_and_delete_operation(std::string const& key);
// update without `get` and no `prev_kv` returned // update without `get` and no `prev_kv` returned
@ -51,10 +57,11 @@ public:
void setup_delete(std::string const& key); void setup_delete(std::string const& key);
std::shared_ptr<etcdserverpb::TxnRequest> txn_request; std::shared_ptr<etcdserverpb::TxnRequest> txn_request;
private: private:
std::string key; std::string key;
}; };
} } // namespace etcdv3
#endif #endif

View File

@ -7,10 +7,8 @@
#include "etcd/v3/KeyValue.hpp" #include "etcd/v3/KeyValue.hpp"
namespace etcdv3 namespace etcdv3 {
{ class V3Response {
class V3Response
{
public: public:
V3Response() : error_code(0), index(0){}; V3Response() : error_code(0), index(0){};
void set_error_code(int code); void set_error_code(int code);
@ -38,6 +36,7 @@ namespace etcdv3
uint64_t get_member_id() const; uint64_t get_member_id() const;
uint64_t get_raft_term() const; uint64_t get_raft_term() const;
std::vector<int64_t> const& get_leases() const; std::vector<int64_t> const& get_leases() const;
protected: protected:
int error_code; int error_code;
int64_t index; int64_t index;
@ -61,5 +60,5 @@ namespace etcdv3
// for lease list // for lease list
std::vector<int64_t> leases; std::vector<int64_t> leases;
}; };
} } // namespace etcdv3
#endif #endif

View File

@ -3,8 +3,7 @@
#include <string> #include <string>
namespace etcdv3 namespace etcdv3 {
{
extern char const* CREATE_ACTION; extern char const* CREATE_ACTION;
extern char const* UPDATE_ACTION; extern char const* UPDATE_ACTION;
extern char const* SET_ACTION; extern char const* SET_ACTION;
@ -69,6 +68,6 @@ namespace etcdv3
extern const int ERROR_COMPARE_FAILED; extern const int ERROR_COMPARE_FAILED;
extern const int ERROR_KEY_ALREADY_EXISTS; extern const int ERROR_KEY_ALREADY_EXISTS;
extern const int ERROR_ACTION_CANCELLED; extern const int ERROR_ACTION_CANCELLED;
} } // namespace etcdv3
#endif #endif

View File

@ -1,5 +1,6 @@
#if defined(_WIN32) #if defined(_WIN32)
// see also: https://stackoverflow.com/questions/2561368/illegal-token-on-right-side-of // see also:
// https://stackoverflow.com/questions/2561368/illegal-token-on-right-side-of
#define NOMINMAX #define NOMINMAX
#endif #endif
@ -19,8 +20,8 @@
#endif #endif
#include <chrono> #include <chrono>
#include <iostream>
#include <fstream> #include <fstream>
#include <iostream>
#include <limits> #include <limits>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
@ -31,37 +32,33 @@
#include <grpc++/grpc++.h> #include <grpc++/grpc++.h>
#include <grpc++/security/credentials.h> #include <grpc++/security/credentials.h>
#include "proto/rpc.grpc.pb.h" #include "proto/rpc.grpc.pb.h"
#include "proto/v3lock.grpc.pb.h"
#include "proto/v3election.grpc.pb.h" #include "proto/v3election.grpc.pb.h"
#include "proto/v3lock.grpc.pb.h"
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
#include "etcd/Watcher.hpp" #include "etcd/Watcher.hpp"
#include "etcd/v3/action_constants.hpp"
#include "etcd/v3/Action.hpp" #include "etcd/v3/Action.hpp"
#include "etcd/v3/AsyncGRPC.hpp" #include "etcd/v3/AsyncGRPC.hpp"
#include "etcd/v3/Transaction.hpp" #include "etcd/v3/Transaction.hpp"
#include "etcd/v3/action_constants.hpp"
etcd::Client::Client(etcd::SyncClient *client): client(client) etcd::Client::Client(etcd::SyncClient* client) : client(client) {
{
this->own_client = false; this->own_client = false;
} }
etcd::Client* WithClient(etcd::SyncClient *client) etcd::Client* WithClient(etcd::SyncClient* client) {
{
return new etcd::Client(client); return new etcd::Client(client);
} }
etcd::Client::Client(std::string const& address, etcd::Client::Client(std::string const& address,
std::string const & load_balancer) std::string const& load_balancer) {
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, load_balancer); this->client = new SyncClient(address, load_balancer);
} }
etcd::Client::Client(std::string const& address, etcd::Client::Client(std::string const& address,
grpc::ChannelArguments const & arguments) grpc::ChannelArguments const& arguments) {
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, arguments); this->client = new SyncClient(address, arguments);
} }
@ -76,24 +73,20 @@ etcd::Client *etcd::Client::WithUrl(std::string const & etcd_url,
return new etcd::Client(etcd_url, arguments); return new etcd::Client(etcd_url, arguments);
} }
etcd::Client::Client(std::string const & address, etcd::Client::Client(std::string const& address, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl,
std::string const & password, std::string const& load_balancer) {
int const auth_token_ttl,
std::string const & load_balancer)
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, username, password, auth_token_ttl, load_balancer); this->client = new SyncClient(address, username, password, auth_token_ttl,
load_balancer);
} }
etcd::Client::Client(std::string const & address, etcd::Client::Client(std::string const& address, std::string const& username,
std::string const & username, std::string const& password, int const auth_token_ttl,
std::string const & password, grpc::ChannelArguments const& arguments) {
int const auth_token_ttl,
grpc::ChannelArguments const & arguments)
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, username, password, auth_token_ttl, arguments); this->client =
new SyncClient(address, username, password, auth_token_ttl, arguments);
} }
etcd::Client* etcd::Client::WithUser(std::string const& etcd_url, etcd::Client* etcd::Client::WithUser(std::string const& etcd_url,
@ -101,7 +94,8 @@ etcd::Client *etcd::Client::WithUser(std::string const & etcd_url,
std::string const& password, std::string const& password,
int const auth_token_ttl, int const auth_token_ttl,
std::string const& load_balancer) { std::string const& load_balancer) {
return new etcd::Client(etcd_url, username, password, auth_token_ttl, load_balancer); return new etcd::Client(etcd_url, username, password, auth_token_ttl,
load_balancer);
} }
etcd::Client* etcd::Client::WithUser(std::string const& etcd_url, etcd::Client* etcd::Client::WithUser(std::string const& etcd_url,
@ -109,30 +103,26 @@ etcd::Client *etcd::Client::WithUser(std::string const & etcd_url,
std::string const& password, std::string const& password,
int const auth_token_ttl, int const auth_token_ttl,
grpc::ChannelArguments const& arguments) { grpc::ChannelArguments const& arguments) {
return new etcd::Client(etcd_url, username, password, auth_token_ttl, arguments); return new etcd::Client(etcd_url, username, password, auth_token_ttl,
arguments);
} }
etcd::Client::Client(std::string const& address, std::string const& ca,
etcd::Client::Client(std::string const & address, std::string const& cert, std::string const& privkey,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
std::string const & load_balancer) std::string const& load_balancer) {
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, ca, cert, privkey, target_name_override, load_balancer); this->client = new SyncClient(address, ca, cert, privkey,
target_name_override, load_balancer);
} }
etcd::Client::Client(std::string const & address, etcd::Client::Client(std::string const& address, std::string const& ca,
std::string const & ca, std::string const& cert, std::string const& privkey,
std::string const & cert,
std::string const & privkey,
std::string const& target_name_override, std::string const& target_name_override,
grpc::ChannelArguments const & arguments) grpc::ChannelArguments const& arguments) {
{
this->own_client = true; this->own_client = true;
this->client = new SyncClient(address, ca, cert, privkey, target_name_override, arguments); this->client = new SyncClient(address, ca, cert, privkey,
target_name_override, arguments);
} }
etcd::Client* etcd::Client::WithSSL(std::string const& etcd_url, etcd::Client* etcd::Client::WithSSL(std::string const& etcd_url,
@ -141,7 +131,8 @@ etcd::Client *etcd::Client::WithSSL(std::string const & etcd_url,
std::string const& privkey, std::string const& privkey,
std::string const& target_name_override, std::string const& target_name_override,
std::string const& load_balancer) { std::string const& load_balancer) {
return new etcd::Client(etcd_url, ca, cert, privkey, target_name_override, load_balancer); return new etcd::Client(etcd_url, ca, cert, privkey, target_name_override,
load_balancer);
} }
etcd::Client* etcd::Client::WithSSL(std::string const& etcd_url, etcd::Client* etcd::Client::WithSSL(std::string const& etcd_url,
@ -150,7 +141,8 @@ etcd::Client *etcd::Client::WithSSL(std::string const & etcd_url,
std::string const& cert, std::string const& cert,
std::string const& privkey, std::string const& privkey,
std::string const& target_name_override) { std::string const& target_name_override) {
return new etcd::Client(etcd_url, ca, cert, privkey, target_name_override, arguments); return new etcd::Client(etcd_url, ca, cert, privkey, target_name_override,
arguments);
} }
etcd::Client::~Client() { etcd::Client::~Client() {
@ -159,7 +151,6 @@ etcd::Client::~Client() {
} }
} }
namespace etcd { namespace etcd {
namespace detail { namespace detail {
@ -168,37 +159,46 @@ namespace detail {
// Inspired by: https://stackoverflow.com/a/20669290/5080177 // Inspired by: https://stackoverflow.com/a/20669290/5080177
template <typename A, typename F> template <typename A, typename F>
class capture_impl class capture_impl {
{
mutable A a; mutable A a;
mutable F f; mutable F f;
public:
capture_impl(A && a, F && f)
: a{std::forward<A>(a)}, f{std::forward<F>(f)}
{}
template <typename ...Ts> auto operator()( Ts&&...args ) public:
-> decltype(std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)... )) capture_impl(A&& a, F&& f) : a{std::forward<A>(a)}, f{std::forward<F>(f)} {}
{
template <typename... Ts>
auto operator()(Ts&&... args)
-> decltype(std::forward<F>(f)(std::forward<A>(a),
std::forward<Ts>(args)...)) {
return std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)...); return std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)...);
} }
template <typename ...Ts> auto operator()( Ts&&...args ) const template <typename... Ts>
-> decltype(std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)... )) auto operator()(Ts&&... args) const
{ -> decltype(std::forward<F>(f)(std::forward<A>(a),
std::forward<Ts>(args)...)) {
return std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)...); return std::forward<F>(f)(std::forward<A>(a), std::forward<Ts>(args)...);
} }
}; };
template <typename A, typename F> template <typename A, typename F>
static capture_impl<A, F> capture(A && a, F && f) static capture_impl<A, F> capture(A&& a, F&& f) {
{
return capture_impl<A, F>(std::forward<A>(a), std::forward<F>(f)); return capture_impl<A, F>(std::forward<A>(a), std::forward<F>(f));
} }
template <typename F, typename Params, typename... Ts> template <typename F, typename Params, typename... Ts>
static auto asyncify(F && fn, Params && params, Ts... args) -> pplx::task<decltype(capture(std::forward<Params>(params), std::bind(std::forward<F>(fn), std::placeholders::_1, std::forward<Ts>(args)...))())> { static auto asyncify(F&& fn, Params&& params, Ts... args)
return pplx::task<decltype(capture(std::forward<Params>(params), std::bind(std::forward<F>(fn), std::placeholders::_1, std::forward<Ts>(args)...))())>(capture(std::forward<Params>(params), std::bind(std::forward<F>(fn), std::placeholders::_1, std::forward<Ts>(args)...))); -> pplx::task<decltype(capture(std::forward<Params>(params),
std::bind(std::forward<F>(fn),
std::placeholders::_1,
std::forward<Ts>(args)...))())> {
return pplx::task<decltype(
capture(std::forward<Params>(params),
std::bind(std::forward<F>(fn), std::placeholders::_1,
std::forward<Ts>(args)...))())>(
capture(std::forward<Params>(params),
std::bind(std::forward<F>(fn), std::placeholders::_1,
std::forward<Ts>(args)...)));
} }
} // namespace detail } // namespace detail
@ -208,35 +208,38 @@ using responser_t = etcd::Response (*)(std::shared_ptr<T>);
} // namespace etcd } // namespace etcd
pplx::task<etcd::Response> etcd::Client::head() pplx::task<etcd::Response> etcd::Client::head() {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<etcd::responser_t<etcdv3::AsyncHeadAction>>(Response::create), static_cast<etcd::responser_t<etcdv3::AsyncHeadAction>>(Response::create),
this->client->head_internal()); this->client->head_internal());
} }
pplx::task<etcd::Response> etcd::Client::get(std::string const & key) pplx::task<etcd::Response> etcd::Client::get(std::string const& key) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<etcd::responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<etcd::responser_t<etcdv3::AsyncRangeAction>>(
Response::create),
this->client->get_internal(key)); this->client->get_internal(key));
} }
pplx::task<etcd::Response> etcd::Client::get(std::string const & key, int64_t revision) pplx::task<etcd::Response> etcd::Client::get(std::string const& key,
{ int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<etcd::responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<etcd::responser_t<etcdv3::AsyncRangeAction>>(
Response::create),
this->client->get_internal(key, revision)); this->client->get_internal(key, revision));
} }
pplx::task<etcd::Response> etcd::Client::set(std::string const & key, std::string const & value, int ttl) pplx::task<etcd::Response> etcd::Client::set(std::string const& key,
{ std::string const& value,
int ttl) {
if (ttl > 0) { if (ttl > 0) {
return this->leasegrant(ttl).then([this, key, value](pplx::task<etcd::Response> const &task) { return this->leasegrant(ttl).then(
[this, key, value](pplx::task<etcd::Response> const& task) {
auto resp = task.get(); auto resp = task.get();
if (resp.error_code() == 0) { if (resp.error_code() == 0) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncSetAction>>(
Response::create),
this->client->set_internal(key, value, resp.value().lease())); this->client->set_internal(key, value, resp.value().lease()));
} else { } else {
return pplx::task_from_result(resp); return pplx::task_from_result(resp);
@ -249,21 +252,25 @@ pplx::task<etcd::Response> etcd::Client::set(std::string const & key, std::strin
} }
} }
pplx::task<etcd::Response> etcd::Client::set(std::string const & key, std::string const & value, int64_t leaseid) pplx::task<etcd::Response> etcd::Client::set(std::string const& key,
{ std::string const& value,
int64_t leaseid) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create),
this->client->set_internal(key, value, leaseid)); this->client->set_internal(key, value, leaseid));
} }
pplx::task<etcd::Response> etcd::Client::add(std::string const & key, std::string const & value, int ttl) pplx::task<etcd::Response> etcd::Client::add(std::string const& key,
{ std::string const& value,
int ttl) {
if (ttl > 0) { if (ttl > 0) {
return this->leasegrant(ttl).then([this, key, value](pplx::task<etcd::Response> const &task) { return this->leasegrant(ttl).then(
[this, key, value](pplx::task<etcd::Response> const& task) {
auto resp = task.get(); auto resp = task.get();
if (resp.error_code() == 0) { if (resp.error_code() == 0) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncSetAction>>(
Response::create),
this->client->add_internal(key, value, resp.value().lease())); this->client->add_internal(key, value, resp.value().lease()));
} else { } else {
return pplx::task_from_result(resp); return pplx::task_from_result(resp);
@ -276,28 +283,34 @@ pplx::task<etcd::Response> etcd::Client::add(std::string const & key, std::strin
} }
} }
pplx::task<etcd::Response> etcd::Client::add(std::string const & key, std::string const & value, int64_t leaseid) pplx::task<etcd::Response> etcd::Client::add(std::string const& key,
{ std::string const& value,
int64_t leaseid) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncSetAction>>(Response::create),
this->client->add_internal(key, value, leaseid)); this->client->add_internal(key, value, leaseid));
} }
pplx::task<etcd::Response> etcd::Client::put(std::string const & key, std::string const & value) { pplx::task<etcd::Response> etcd::Client::put(std::string const& key,
std::string const& value) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncPutAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncPutAction>>(Response::create),
this->client->put_internal(key, value)); this->client->put_internal(key, value));
} }
pplx::task<etcd::Response> etcd::Client::modify(std::string const & key, std::string const & value, int ttl) pplx::task<etcd::Response> etcd::Client::modify(std::string const& key,
{ std::string const& value,
int ttl) {
if (ttl > 0) { if (ttl > 0) {
return this->leasegrant(ttl).then([this, key, value](pplx::task<etcd::Response> const &task) { return this->leasegrant(ttl).then(
[this, key, value](pplx::task<etcd::Response> const& task) {
auto resp = task.get(); auto resp = task.get();
if (resp.error_code() == 0) { if (resp.error_code() == 0) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncUpdateAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncUpdateAction>>(
this->client->modify_internal(key, value, resp.value().lease())); Response::create),
this->client->modify_internal(key, value,
resp.value().lease()));
} else { } else {
return pplx::task_from_result(resp); return pplx::task_from_result(resp);
} }
@ -309,268 +322,303 @@ pplx::task<etcd::Response> etcd::Client::modify(std::string const & key, std::st
} }
} }
pplx::task<etcd::Response> etcd::Client::modify(std::string const & key, std::string const & value, int64_t leaseid) pplx::task<etcd::Response> etcd::Client::modify(std::string const& key,
{ std::string const& value,
int64_t leaseid) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncUpdateAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncUpdateAction>>(Response::create),
this->client->modify_internal(key, value, leaseid)); this->client->modify_internal(key, value, leaseid));
} }
pplx::task<etcd::Response> etcd::Client::modify_if(std::string const & key, std::string const & value, std::string const & old_value, int ttl) pplx::task<etcd::Response> etcd::Client::modify_if(std::string const& key,
{ std::string const& value,
std::string const& old_value,
int ttl) {
if (ttl > 0) { if (ttl > 0) {
return this->leasegrant(ttl).then([this, key, value, old_value](pplx::task<etcd::Response> const &task) { return this->leasegrant(ttl).then(
[this, key, value, old_value](pplx::task<etcd::Response> const& task) {
auto resp = task.get(); auto resp = task.get();
if (resp.error_code() == 0) { if (resp.error_code() == 0) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, 0, old_value, resp.value().lease(), etcdv3::AtomicityType::PREV_VALUE)); Response::create),
this->client->modify_if_internal(
key, value, 0, old_value, resp.value().lease(),
etcdv3::AtomicityType::PREV_VALUE));
} else { } else {
return pplx::task_from_result(resp); return pplx::task_from_result(resp);
} }
}); });
} else { } else {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, 0, old_value, 0, etcdv3::AtomicityType::PREV_VALUE)); Response::create),
this->client->modify_if_internal(key, value, 0, old_value, 0,
etcdv3::AtomicityType::PREV_VALUE));
} }
} }
pplx::task<etcd::Response> etcd::Client::modify_if(std::string const & key, std::string const & value, std::string const & old_value, int64_t leaseid) pplx::task<etcd::Response> etcd::Client::modify_if(std::string const& key,
{ std::string const& value,
std::string const& old_value,
int64_t leaseid) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, 0, old_value, leaseid, etcdv3::AtomicityType::PREV_VALUE)); Response::create),
this->client->modify_if_internal(key, value, 0, old_value, leaseid,
etcdv3::AtomicityType::PREV_VALUE));
} }
pplx::task<etcd::Response> etcd::Client::modify_if(std::string const & key, std::string const & value, int64_t old_index, int ttl) pplx::task<etcd::Response> etcd::Client::modify_if(std::string const& key,
{ std::string const& value,
int64_t old_index, int ttl) {
if (ttl > 0) { if (ttl > 0) {
return this->leasegrant(ttl).then([this, key, value, old_index](pplx::task<etcd::Response> const &task) { return this->leasegrant(ttl).then(
[this, key, value, old_index](pplx::task<etcd::Response> const& task) {
auto resp = task.get(); auto resp = task.get();
if (resp.error_code() == 0) { if (resp.error_code() == 0) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, old_index, "", resp.value().lease(), etcdv3::AtomicityType::PREV_INDEX)); Response::create),
this->client->modify_if_internal(
key, value, old_index, "", resp.value().lease(),
etcdv3::AtomicityType::PREV_INDEX));
} else { } else {
return pplx::task_from_result(resp); return pplx::task_from_result(resp);
} }
}); });
} else { } else {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, old_index, "", 0, etcdv3::AtomicityType::PREV_INDEX)); Response::create),
this->client->modify_if_internal(key, value, old_index, "", 0,
etcdv3::AtomicityType::PREV_INDEX));
} }
} }
pplx::task<etcd::Response> etcd::Client::modify_if(std::string const & key, std::string const & value, int64_t old_index, int64_t leaseid) pplx::task<etcd::Response> etcd::Client::modify_if(std::string const& key,
{ std::string const& value,
int64_t old_index,
int64_t leaseid) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndSwapAction>>(
this->client->modify_if_internal(key, value, old_index, "", leaseid, etcdv3::AtomicityType::PREV_INDEX)); Response::create),
this->client->modify_if_internal(key, value, old_index, "", leaseid,
etcdv3::AtomicityType::PREV_INDEX));
} }
pplx::task<etcd::Response> etcd::Client::rm(std::string const & key) pplx::task<etcd::Response> etcd::Client::rm(std::string const& key) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create),
this->client->rm_internal(key)); this->client->rm_internal(key));
} }
pplx::task<etcd::Response> etcd::Client::rm_if(std::string const & key, std::string const & old_value) pplx::task<etcd::Response> etcd::Client::rm_if(std::string const& key,
{ std::string const& old_value) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndDeleteAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndDeleteAction>>(
this->client->rm_if_internal(key, 0, old_value, etcdv3::AtomicityType::PREV_VALUE)); Response::create),
this->client->rm_if_internal(key, 0, old_value,
etcdv3::AtomicityType::PREV_VALUE));
} }
pplx::task<etcd::Response> etcd::Client::rm_if(std::string const & key, int64_t old_index) pplx::task<etcd::Response> etcd::Client::rm_if(std::string const& key,
{ int64_t old_index) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCompareAndDeleteAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCompareAndDeleteAction>>(
this->client->rm_if_internal(key, old_index, "", etcdv3::AtomicityType::PREV_INDEX)); Response::create),
this->client->rm_if_internal(key, old_index, "",
etcdv3::AtomicityType::PREV_INDEX));
} }
pplx::task<etcd::Response> etcd::Client::rmdir(std::string const & key, bool recursive) pplx::task<etcd::Response> etcd::Client::rmdir(std::string const& key,
{ bool recursive) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create),
this->client->rmdir_internal(key, recursive)); this->client->rmdir_internal(key, recursive));
} }
pplx::task<etcd::Response> etcd::Client::rmdir(std::string const & key, const char *range_end) pplx::task<etcd::Response> etcd::Client::rmdir(std::string const& key,
{ const char* range_end) {
return this->rmdir(key, std::string(range_end)); return this->rmdir(key, std::string(range_end));
} }
pplx::task<etcd::Response> etcd::Client::rmdir(std::string const & key, std::string const &range_end) pplx::task<etcd::Response> etcd::Client::rmdir(std::string const& key,
{ std::string const& range_end) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncDeleteAction>>(Response::create),
this->client->rmdir_internal(key, range_end)); this->client->rmdir_internal(key, range_end));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, 0)); this->client->ls_internal(key, 0));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key, size_t const limit) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key,
{ size_t const limit) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, limit)); this->client->ls_internal(key, limit));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key, size_t const limit, int64_t revision) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key,
{ size_t const limit,
int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, limit, false, revision)); this->client->ls_internal(key, limit, false, revision));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key, std::string const &range_end) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key,
{ std::string const& range_end) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, 0)); this->client->ls_internal(key, range_end, 0));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key, std::string const &range_end, size_t const limit) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key,
{ std::string const& range_end,
size_t const limit) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, limit)); this->client->ls_internal(key, range_end, limit));
} }
pplx::task<etcd::Response> etcd::Client::ls(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision) pplx::task<etcd::Response> etcd::Client::ls(std::string const& key,
{ std::string const& range_end,
size_t const limit,
int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, limit, false, revision)); this->client->ls_internal(key, range_end, limit, false, revision));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, 0, true)); this->client->ls_internal(key, 0, true));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key, size_t const limit) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key,
{ size_t const limit) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, limit, true)); this->client->ls_internal(key, limit, true));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key, size_t const limit, int64_t revision) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key,
{ size_t const limit,
int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, limit, true, revision)); this->client->ls_internal(key, limit, true, revision));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key, std::string const &range_end) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key,
{ std::string const& range_end) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, 0, true)); this->client->ls_internal(key, range_end, 0, true));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key, std::string const &range_end, size_t const limit) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key,
{ std::string const& range_end,
size_t const limit) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, limit, true)); this->client->ls_internal(key, range_end, limit, true));
} }
pplx::task<etcd::Response> etcd::Client::keys(std::string const & key, std::string const &range_end, size_t const limit, int64_t revision) pplx::task<etcd::Response> etcd::Client::keys(std::string const& key,
{ std::string const& range_end,
size_t const limit,
int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncRangeAction>>(Response::create),
this->client->ls_internal(key, range_end, limit, true, revision)); this->client->ls_internal(key, range_end, limit, true, revision));
} }
pplx::task<etcd::Response> etcd::Client::watch(std::string const & key, bool recursive) pplx::task<etcd::Response> etcd::Client::watch(std::string const& key,
{ bool recursive) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create),
this->client->watch_internal(key, 0, recursive)); this->client->watch_internal(key, 0, recursive));
} }
pplx::task<etcd::Response> etcd::Client::watch(std::string const & key, int64_t fromIndex, bool recursive) pplx::task<etcd::Response> etcd::Client::watch(std::string const& key,
{ int64_t fromIndex,
bool recursive) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create),
this->client->watch_internal(key, fromIndex, recursive)); this->client->watch_internal(key, fromIndex, recursive));
} }
pplx::task<etcd::Response> etcd::Client::watch(std::string const & key, const char *range_end) pplx::task<etcd::Response> etcd::Client::watch(std::string const& key,
{ const char* range_end) {
return this->watch(key, std::string(range_end)); return this->watch(key, std::string(range_end));
} }
pplx::task<etcd::Response> etcd::Client::watch(std::string const & key, std::string const & range_end) pplx::task<etcd::Response> etcd::Client::watch(std::string const& key,
{ std::string const& range_end) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create),
this->client->watch_internal(key, range_end, 0)); this->client->watch_internal(key, range_end, 0));
} }
pplx::task<etcd::Response> etcd::Client::watch(std::string const & key, std::string const & range_end, int64_t fromIndex) pplx::task<etcd::Response> etcd::Client::watch(std::string const& key,
{ std::string const& range_end,
int64_t fromIndex) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncWatchAction>>(Response::create),
this->client->watch_internal(key, range_end, fromIndex)); this->client->watch_internal(key, range_end, fromIndex));
} }
pplx::task<etcd::Response> etcd::Client::leasegrant(int ttl) pplx::task<etcd::Response> etcd::Client::leasegrant(int ttl) {
{
// See Note [lease with TTL and issue the actual request] // See Note [lease with TTL and issue the actual request]
return pplx::task<etcd::Response>([this, ttl]() { return pplx::task<etcd::Response>(
return this->client->leasegrant(ttl); [this, ttl]() { return this->client->leasegrant(ttl); });
});
} }
pplx::task<std::shared_ptr<etcd::KeepAlive>> etcd::Client::leasekeepalive(int ttl) { pplx::task<std::shared_ptr<etcd::KeepAlive>> etcd::Client::leasekeepalive(
int ttl) {
// See Note [lease with TTL and issue the actual request] // See Note [lease with TTL and issue the actual request]
return pplx::task<std::shared_ptr<etcd::KeepAlive>>([this, ttl]() { return pplx::task<std::shared_ptr<etcd::KeepAlive>>(
return this->client->leasekeepalive(ttl); [this, ttl]() { return this->client->leasekeepalive(ttl); });
});
} }
pplx::task<etcd::Response> etcd::Client::leaserevoke(int64_t lease_id) pplx::task<etcd::Response> etcd::Client::leaserevoke(int64_t lease_id) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncLeaseRevokeAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncLeaseRevokeAction>>(
Response::create),
this->client->leaserevoke_internal(lease_id)); this->client->leaserevoke_internal(lease_id));
} }
pplx::task<etcd::Response> etcd::Client::leasetimetolive(int64_t lease_id) pplx::task<etcd::Response> etcd::Client::leasetimetolive(int64_t lease_id) {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncLeaseTimeToLiveAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncLeaseTimeToLiveAction>>(
Response::create),
this->client->leasetimetolive_internal(lease_id)); this->client->leasetimetolive_internal(lease_id));
} }
pplx::task<etcd::Response> etcd::Client::leases() pplx::task<etcd::Response> etcd::Client::leases() {
{
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncLeaseLeasesAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncLeaseLeasesAction>>(
Response::create),
this->client->leases_internal()); this->client->leases_internal());
} }
pplx::task<etcd::Response> etcd::Client::lock(std::string const& key) { pplx::task<etcd::Response> etcd::Client::lock(std::string const& key) {
static const int DEFAULT_LEASE_TTL_FOR_LOCK = 10; // see also etcd::SyncClient::lock static const int DEFAULT_LEASE_TTL_FOR_LOCK =
10; // see also etcd::SyncClient::lock
return this->lock(key, DEFAULT_LEASE_TTL_FOR_LOCK); return this->lock(key, DEFAULT_LEASE_TTL_FOR_LOCK);
} }
pplx::task<etcd::Response> etcd::Client::lock(std::string const& key, pplx::task<etcd::Response> etcd::Client::lock(std::string const& key,
const bool sync) { const bool sync) {
static const int DEFAULT_LEASE_TTL_FOR_LOCK = 10; // see also etcd::SyncClient::lock static const int DEFAULT_LEASE_TTL_FOR_LOCK =
10; // see also etcd::SyncClient::lock
return this->lock(key, DEFAULT_LEASE_TTL_FOR_LOCK, sync); return this->lock(key, DEFAULT_LEASE_TTL_FOR_LOCK, sync);
} }
@ -580,16 +628,14 @@ pplx::task<etcd::Response> etcd::Client::lock(std::string const &key,
// See also SyncClient::lock // See also SyncClient::lock
// //
// We don't separate the keepalive step and lock step to avoid leaving many // We don't separate the keepalive step and lock step to avoid leaving many
// busy-waiting keepalive tasks when waiting for the locks due to the contention // busy-waiting keepalive tasks when waiting for the locks due to the
// of async threadpool. // contention of async threadpool.
return pplx::task<etcd::Response>([this, key, lease_ttl]() { return pplx::task<etcd::Response>(
return this->client->lock(key, lease_ttl); [this, key, lease_ttl]() { return this->client->lock(key, lease_ttl); });
});
} }
pplx::task<etcd::Response> etcd::Client::lock(std::string const& key, pplx::task<etcd::Response> etcd::Client::lock(std::string const& key,
int lease_ttl, int lease_ttl, const bool sync) {
const bool sync) {
if (sync) { if (sync) {
pplx::task_completion_event<etcd::Response> event; pplx::task_completion_event<etcd::Response> event;
event.set(this->client->lock(key, lease_ttl)); event.set(this->client->lock(key, lease_ttl));
@ -630,16 +676,19 @@ pplx::task<etcd::Response> etcd::Client::txn(etcdv3::Transaction const &txn) {
this->client->txn_internal(txn)); this->client->txn_internal(txn));
} }
pplx::task<etcd::Response> etcd::Client::campaign( pplx::task<etcd::Response> etcd::Client::campaign(std::string const& name,
std::string const &name, int64_t lease_id, std::string const &value) { int64_t lease_id,
std::string const& value) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncCampaignAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncCampaignAction>>(Response::create),
this->client->campaign_internal(name, lease_id, value)); this->client->campaign_internal(name, lease_id, value));
} }
pplx::task<etcd::Response> etcd::Client::proclaim( pplx::task<etcd::Response> etcd::Client::proclaim(std::string const& name,
std::string const &name, int64_t lease_id, int64_t lease_id,
std::string const &key, int64_t revision, std::string const &value) { std::string const& key,
int64_t revision,
std::string const& value) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncProclaimAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncProclaimAction>>(Response::create),
this->client->proclaim_internal(name, lease_id, key, revision, value)); this->client->proclaim_internal(name, lease_id, key, revision, value));
@ -651,12 +700,15 @@ pplx::task<etcd::Response> etcd::Client::leader(std::string const &name) {
this->client->leader_internal(name)); this->client->leader_internal(name));
} }
std::unique_ptr<etcd::Client::Observer> etcd::Client::observe(std::string const &name) { std::unique_ptr<etcd::Client::Observer> etcd::Client::observe(
std::string const& name) {
return this->client->observe(name); return this->client->observe(name);
} }
pplx::task<etcd::Response> etcd::Client::resign( pplx::task<etcd::Response> etcd::Client::resign(std::string const& name,
std::string const &name, int64_t lease_id, std::string const &key, int64_t revision) { int64_t lease_id,
std::string const& key,
int64_t revision) {
return etcd::detail::asyncify( return etcd::detail::asyncify(
static_cast<responser_t<etcdv3::AsyncResignAction>>(Response::create), static_cast<responser_t<etcdv3::AsyncResignAction>>(Response::create),
this->client->resign_internal(name, lease_id, key, revision)); this->client->resign_internal(name, lease_id, key, revision));
@ -670,72 +722,61 @@ std::shared_ptr<grpc::Channel> etcd::Client::grpc_channel() const {
return this->client->grpc_channel(); return this->client->grpc_channel();
} }
etcd::SyncClient* etcd::Client::sync_client() const { etcd::SyncClient* etcd::Client::sync_client() const { return this->client; }
return this->client;
}
// watchers from the async client // watchers from the async client
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : Watcher(*client.sync_client(), key, callback, wait_callback, recursive) {}
Watcher(*client.sync_client(), key, callback, wait_callback, recursive) {
}
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
Watcher(*client.sync_client(), key, range_end, callback, wait_callback) { : Watcher(*client.sync_client(), key, range_end, callback, wait_callback) {}
}
etcd::Watcher::Watcher(Client const &client, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(Client const& client, std::string const& key,
int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : Watcher(*client.sync_client(), key, fromIndex, callback, wait_callback,
Watcher(*client.sync_client(), key, fromIndex, callback, wait_callback, recursive) { recursive) {}
}
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
Watcher(*client.sync_client(), key, range_end, fromIndex, callback, wait_callback) { : Watcher(*client.sync_client(), key, range_end, fromIndex, callback,
} wait_callback) {}
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive)
bool recursive): : Watcher(*client.sync_client(), key, callback, recursive) {}
Watcher(*client.sync_client(), key, callback, recursive) {
}
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(*client.sync_client(), key, range_end, callback) { : Watcher(*client.sync_client(), key, range_end, callback) {}
}
etcd::Watcher::Watcher(Client const &client, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::function<void(Response)> callback, int64_t fromIndex,
bool recursive): std::function<void(Response)> callback, bool recursive)
Watcher(*client.sync_client(), key, fromIndex, callback, recursive) { : Watcher(*client.sync_client(), key, fromIndex, callback, recursive) {}
}
etcd::Watcher::Watcher(Client const& client, std::string const& key, etcd::Watcher::Watcher(Client const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(*client.sync_client(), key, range_end, fromIndex, callback) { : Watcher(*client.sync_client(), key, range_end, fromIndex, callback) {}
}
// keepalive from then async client // keepalive from then async client
etcd::KeepAlive::KeepAlive(Client const &client, int ttl, int64_t lease_id): etcd::KeepAlive::KeepAlive(Client const& client, int ttl, int64_t lease_id)
KeepAlive(*client.sync_client(), ttl, lease_id) { : KeepAlive(*client.sync_client(), ttl, lease_id) {}
}
etcd::KeepAlive::KeepAlive(Client const &client, etcd::KeepAlive::KeepAlive(
std::function<void (std::exception_ptr)> const &handler, Client const& client,
int ttl, int64_t lease_id): std::function<void(std::exception_ptr)> const& handler, int ttl,
KeepAlive(*client.sync_client(), handler, ttl, lease_id) { int64_t lease_id)
} : KeepAlive(*client.sync_client(), handler, ttl, lease_id) {}

View File

@ -16,14 +16,17 @@ struct etcd::KeepAlive::EtcdServerStubs {
std::unique_ptr<etcdv3::AsyncLeaseKeepAliveAction> call; std::unique_ptr<etcdv3::AsyncLeaseKeepAliveAction> call;
}; };
void etcd::KeepAlive::EtcdServerStubsDeleter::operator()(etcd::KeepAlive::EtcdServerStubs *stubs) { void etcd::KeepAlive::EtcdServerStubsDeleter::operator()(
etcd::KeepAlive::EtcdServerStubs* stubs) {
if (stubs) { if (stubs) {
delete stubs; delete stubs;
} }
} }
etcd::KeepAlive::KeepAlive(SyncClient const &client, int ttl, int64_t lease_id): etcd::KeepAlive::KeepAlive(SyncClient const& client, int ttl, int64_t lease_id)
ttl(ttl), lease_id(lease_id), continue_next(true), : ttl(ttl),
lease_id(lease_id),
continue_next(true),
grpc_timeout(client.get_grpc_timeout()) { grpc_timeout(client.get_grpc_timeout()) {
stubs.reset(new EtcdServerStubs{}); stubs.reset(new EtcdServerStubs{});
stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel()); stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel());
@ -48,30 +51,33 @@ etcd::KeepAlive::KeepAlive(SyncClient const &client, int ttl, int64_t lease_id):
}); });
} }
etcd::KeepAlive::KeepAlive(std::string const & address, int ttl, int64_t lease_id): etcd::KeepAlive::KeepAlive(std::string const& address, int ttl,
KeepAlive(SyncClient(address), ttl, lease_id) { int64_t lease_id)
} : KeepAlive(SyncClient(address), ttl, lease_id) {}
etcd::KeepAlive::KeepAlive(std::string const& address, etcd::KeepAlive::KeepAlive(std::string const& address,
std::string const & username, std::string const & password, std::string const& username,
int ttl, int64_t lease_id, int const auth_token_ttl): std::string const& password, int ttl,
KeepAlive(SyncClient(address, username, password, auth_token_ttl), ttl, lease_id) { int64_t lease_id, int const auth_token_ttl)
} : KeepAlive(SyncClient(address, username, password, auth_token_ttl), ttl,
lease_id) {}
etcd::KeepAlive::KeepAlive(std::string const & address, etcd::KeepAlive::KeepAlive(
std::string const & ca, std::string const& address, std::string const& ca, std::string const& cert,
std::string const & cert,
std::string const& privkey, std::string const& privkey,
std::function<void (std::exception_ptr)> const &handler, std::function<void(std::exception_ptr)> const& handler, int ttl,
int ttl, int64_t lease_id, int64_t lease_id, std::string const& target_name_override)
std::string const & target_name_override): : KeepAlive(SyncClient(address, ca, cert, privkey, target_name_override),
KeepAlive(SyncClient(address, ca, cert, privkey, target_name_override), ttl, lease_id) { ttl, lease_id) {}
}
etcd::KeepAlive::KeepAlive(SyncClient const &client, etcd::KeepAlive::KeepAlive(
std::function<void (std::exception_ptr)> const &handler, SyncClient const& client,
int ttl, int64_t lease_id): std::function<void(std::exception_ptr)> const& handler, int ttl,
handler_(handler), ttl(ttl), lease_id(lease_id), continue_next(true), int64_t lease_id)
: handler_(handler),
ttl(ttl),
lease_id(lease_id),
continue_next(true),
grpc_timeout(client.get_grpc_timeout()) { grpc_timeout(client.get_grpc_timeout()) {
stubs.reset(new EtcdServerStubs{}); stubs.reset(new EtcdServerStubs{});
stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel()); stubs->leaseServiceStub = Lease::NewStub(client.grpc_channel());
@ -97,26 +103,23 @@ etcd::KeepAlive::KeepAlive(SyncClient const &client,
}); });
} }
etcd::KeepAlive::KeepAlive(std::string const & address, etcd::KeepAlive::KeepAlive(
std::function<void (std::exception_ptr)> const &handler, std::string const& address,
int ttl, int64_t lease_id): std::function<void(std::exception_ptr)> const& handler, int ttl,
KeepAlive(SyncClient(address), handler, ttl, lease_id) { int64_t lease_id)
} : KeepAlive(SyncClient(address), handler, ttl, lease_id) {}
etcd::KeepAlive::KeepAlive(std::string const & address, etcd::KeepAlive::KeepAlive(
std::string const & username, std::string const & password, std::string const& address, std::string const& username,
std::function<void (std::exception_ptr)> const &handler, std::string const& password,
int ttl, int64_t lease_id, const int auth_token_ttl): std::function<void(std::exception_ptr)> const& handler, int ttl,
KeepAlive(SyncClient(address, username, password, auth_token_ttl), handler, ttl, lease_id) { int64_t lease_id, const int auth_token_ttl)
} : KeepAlive(SyncClient(address, username, password, auth_token_ttl),
handler, ttl, lease_id) {}
etcd::KeepAlive::~KeepAlive() etcd::KeepAlive::~KeepAlive() { this->Cancel(); }
{
this->Cancel();
}
void etcd::KeepAlive::Cancel() void etcd::KeepAlive::Cancel() {
{
if (!continue_next.exchange(false)) { if (!continue_next.exchange(false)) {
return; return;
} }
@ -143,7 +146,8 @@ void etcd::KeepAlive::Check() {
// run canceller first // run canceller first
this->Cancel(); this->Cancel();
// propagate the exception, as we throw in `Check()`, the `handler` won't be touched // propagate the exception, as we throw in `Check()`, the `handler` won't be
// touched
eptr_ = std::current_exception(); eptr_ = std::current_exception();
if (handler_) { if (handler_) {
handler_(eptr_); handler_(eptr_);
@ -154,8 +158,7 @@ void etcd::KeepAlive::Check() {
} }
} }
void etcd::KeepAlive::refresh() void etcd::KeepAlive::refresh() {
{
while (true) { while (true) {
if (!continue_next.load()) { if (!continue_next.load()) {
return; return;
@ -164,7 +167,8 @@ void etcd::KeepAlive::refresh()
int keepalive_ttl = std::max(ttl - 1, 1); int keepalive_ttl = std::max(ttl - 1, 1);
{ {
std::unique_lock<std::mutex> lock(mutex_for_refresh_); std::unique_lock<std::mutex> lock(mutex_for_refresh_);
if (cv_for_refresh_.wait_for(lock, std::chrono::seconds(keepalive_ttl)) == std::cv_status::no_timeout) { if (cv_for_refresh_.wait_for(lock, std::chrono::seconds(keepalive_ttl)) ==
std::cv_status::no_timeout) {
return; return;
} }
} }
@ -174,8 +178,7 @@ void etcd::KeepAlive::refresh()
} }
} }
void etcd::KeepAlive::refresh_once() void etcd::KeepAlive::refresh_once() {
{
std::lock_guard<std::mutex> scope_lock(mutex_for_refresh_); std::lock_guard<std::mutex> scope_lock(mutex_for_refresh_);
if (!continue_next.load()) { if (!continue_next.load()) {
return; return;
@ -183,10 +186,12 @@ void etcd::KeepAlive::refresh_once()
this->stubs->call->mutable_parameters().grpc_timeout = this->grpc_timeout; this->stubs->call->mutable_parameters().grpc_timeout = this->grpc_timeout;
auto resp = this->stubs->call->Refresh(); auto resp = this->stubs->call->Refresh();
if (!resp.is_ok()) { if (!resp.is_ok()) {
throw std::runtime_error("Failed to refresh lease: error code: " + std::to_string(resp.error_code()) + throw std::runtime_error("Failed to refresh lease: error code: " +
std::to_string(resp.error_code()) +
", message: " + resp.error_message()); ", message: " + resp.error_message());
} }
if (resp.value().ttl() == 0) { if (resp.value().ttl() == 0) {
throw std::out_of_range("Failed to refresh lease due to expiration: the new TTL is 0."); throw std::out_of_range(
"Failed to refresh lease due to expiration: the new TTL is 0.");
} }
} }

View File

@ -3,11 +3,7 @@
#include <iostream> #include <iostream>
etcd::Response::Response() etcd::Response::Response() : _error_code(0), _index(0) {}
: _error_code(0),
_index(0)
{
}
etcd::Response::Response(const etcd::Response& response) { etcd::Response::Response(const etcd::Response& response) {
this->_error_code = response._error_code; this->_error_code = response._error_code;
@ -31,23 +27,19 @@ etcd::Response::Response(const etcd::Response & response) {
this->_leases = response._leases; this->_leases = response._leases;
} }
etcd::Response::Response(const etcdv3::V3Response& reply, std::chrono::microseconds const& duration) etcd::Response::Response(const etcdv3::V3Response& reply,
{ std::chrono::microseconds const& duration) {
_index = reply.get_index(); _index = reply.get_index();
_action = reply.get_action(); _action = reply.get_action();
_error_code = reply.get_error_code(); _error_code = reply.get_error_code();
_error_message = reply.get_error_message(); _error_message = reply.get_error_message();
if(reply.has_values()) if (reply.has_values()) {
{
auto val = reply.get_values(); auto val = reply.get_values();
for(unsigned int index = 0; index < val.size(); index++) for (unsigned int index = 0; index < val.size(); index++) {
{
_values.push_back(Value(val[index])); _values.push_back(Value(val[index]));
_keys.push_back(val[index].kvs.key()); _keys.push_back(val[index].kvs.key());
} }
} } else {
else
{
_value = Value(reply.get_value()); _value = Value(reply.get_value());
} }
_prev_value = Value(reply.get_prev_value()); _prev_value = Value(reply.get_prev_value());
@ -74,101 +66,52 @@ etcd::Response::Response(const etcdv3::V3Response& reply, std::chrono::microseco
} }
etcd::Response::Response(int error_code, std::string const& error_message) etcd::Response::Response(int error_code, std::string const& error_message)
: _error_code(error_code), : _error_code(error_code), _error_message(error_message), _index(0) {}
_error_message(error_message),
_index(0)
{
}
etcd::Response::Response(int error_code, char const* error_message) etcd::Response::Response(int error_code, char const* error_message)
: _error_code(error_code), : _error_code(error_code), _error_message(error_message), _index(0) {}
_error_message(error_message),
_index(0)
{
}
int etcd::Response::error_code() const int etcd::Response::error_code() const { return _error_code; }
{
return _error_code;
}
std::string const & etcd::Response::error_message() const std::string const& etcd::Response::error_message() const {
{
return _error_message; return _error_message;
} }
bool etcd::Response::is_ok() const bool etcd::Response::is_ok() const { return error_code() == 0; }
{
return error_code() == 0;
}
bool etcd::Response::is_network_unavailable() const bool etcd::Response::is_network_unavailable() const {
{
return error_code() == ::grpc::StatusCode::UNAVAILABLE; return error_code() == ::grpc::StatusCode::UNAVAILABLE;
} }
bool etcd::Response::is_grpc_timeout() const bool etcd::Response::is_grpc_timeout() const {
{
return _error_code == grpc::StatusCode::DEADLINE_EXCEEDED; return _error_code == grpc::StatusCode::DEADLINE_EXCEEDED;
} }
std::string const & etcd::Response::action() const std::string const& etcd::Response::action() const { return _action; }
{
return _action;
}
int64_t etcd::Response::index() const int64_t etcd::Response::index() const { return _index; }
{
return _index;
}
etcd::Value const & etcd::Response::value() const etcd::Value const& etcd::Response::value() const { return _value; }
{
return _value;
}
etcd::Value const & etcd::Response::prev_value() const etcd::Value const& etcd::Response::prev_value() const { return _prev_value; }
{
return _prev_value;
}
etcd::Values const & etcd::Response::values() const etcd::Values const& etcd::Response::values() const { return _values; }
{
return _values;
}
etcd::Value const & etcd::Response::value(int index) const etcd::Value const& etcd::Response::value(int index) const {
{
return _values[index]; return _values[index];
} }
etcd::Keys const & etcd::Response::keys() const etcd::Keys const& etcd::Response::keys() const { return _keys; }
{
return _keys;
}
std::string const & etcd::Response::key(int index) const std::string const& etcd::Response::key(int index) const { return _keys[index]; }
{
return _keys[index];
}
int64_t etcd::Response::compact_revision() const int64_t etcd::Response::compact_revision() const { return _compact_revision; }
{
return _compact_revision;
}
int64_t etcd::Response::watch_id() const int64_t etcd::Response::watch_id() const { return _watch_id; }
{
return _watch_id;
}
std::string const & etcd::Response::lock_key() const { std::string const& etcd::Response::lock_key() const { return _lock_key; }
return _lock_key;
}
std::string const & etcd::Response::name() const { std::string const& etcd::Response::name() const { return _name; }
return _name;
}
std::vector<etcd::Event> const& etcd::Response::events() const { std::vector<etcd::Event> const& etcd::Response::events() const {
return this->_events; return this->_events;
@ -178,17 +121,11 @@ std::chrono::microseconds const& etcd::Response::duration() const {
return this->_duration; return this->_duration;
} }
uint64_t etcd::Response::cluster_id() const { uint64_t etcd::Response::cluster_id() const { return this->_cluster_id; }
return this->_cluster_id;
}
uint64_t etcd::Response::member_id() const { uint64_t etcd::Response::member_id() const { return this->_member_id; }
return this->_member_id;
}
uint64_t etcd::Response::raft_term() const { uint64_t etcd::Response::raft_term() const { return this->_raft_term; }
return this->_raft_term;
}
std::vector<int64_t> const& etcd::Response::leases() const { std::vector<int64_t> const& etcd::Response::leases() const {
return this->_leases; return this->_leases;

File diff suppressed because it is too large Load Diff

View File

@ -4,18 +4,9 @@
#include "etcd/v3/KeyValue.hpp" #include "etcd/v3/KeyValue.hpp"
etcd::Value::Value() etcd::Value::Value()
: dir(false), : dir(false), created(0), modified(0), _version(0), _ttl(0), leaseId(0) {}
created(0),
modified(0),
_version(0),
_ttl(0),
leaseId(0)
{
}
etcd::Value::Value(etcdv3::KeyValue const& kv) {
etcd::Value::Value(etcdv3::KeyValue const & kv)
{
dir = false; dir = false;
_key = kv.kvs.key(); _key = kv.kvs.key();
value = kv.kvs.value(); value = kv.kvs.value();
@ -26,8 +17,7 @@ etcd::Value::Value(etcdv3::KeyValue const & kv)
_ttl = kv.get_ttl(); _ttl = kv.get_ttl();
} }
etcd::Value::Value(mvccpb::KeyValue const & kv) etcd::Value::Value(mvccpb::KeyValue const& kv) {
{
dir = false; dir = false;
_key = kv.key(); _key = kv.key();
value = kv.value(); value = kv.value();
@ -38,45 +28,21 @@ etcd::Value::Value(mvccpb::KeyValue const & kv)
_ttl = -1; _ttl = -1;
} }
std::string const & etcd::Value::key() const std::string const& etcd::Value::key() const { return _key; }
{
return _key;
}
bool etcd::Value::is_dir() const bool etcd::Value::is_dir() const { return dir; }
{
return dir;
}
std::string const & etcd::Value::as_string() const std::string const& etcd::Value::as_string() const { return value; }
{
return value;
}
int64_t etcd::Value::created_index() const int64_t etcd::Value::created_index() const { return created; }
{
return created;
}
int64_t etcd::Value::modified_index() const int64_t etcd::Value::modified_index() const { return modified; }
{
return modified;
}
int64_t etcd::Value::version() const int64_t etcd::Value::version() const { return _version; }
{
return _version;
}
int etcd::Value::ttl() const int etcd::Value::ttl() const { return _ttl; }
{
return _ttl;
}
int64_t etcd::Value::lease() const int64_t etcd::Value::lease() const { return leaseId; }
{
return leaseId;
}
etcd::Event::Event(mvccpb::Event const& event) { etcd::Event::Event(mvccpb::Event const& event) {
_has_kv = event.has_kv(); _has_kv = event.has_kv();
@ -100,18 +66,10 @@ enum etcd::Event::EventType etcd::Event::event_type() const {
return event_type_; return event_type_;
} }
bool etcd::Event::has_kv() const { bool etcd::Event::has_kv() const { return _has_kv; }
return _has_kv;
}
bool etcd::Event::has_prev_kv() const { bool etcd::Event::has_prev_kv() const { return _has_prev_kv; }
return _has_prev_kv;
}
const etcd::Value &etcd::Event::kv() const { const etcd::Value& etcd::Event::kv() const { return _kv; }
return _kv;
}
const etcd::Value &etcd::Event::prev_kv() const { const etcd::Value& etcd::Event::prev_kv() const { return _prev_kv; }
return _prev_kv;
}

View File

@ -9,7 +9,8 @@ struct etcd::Watcher::EtcdServerStubs {
std::unique_ptr<etcdv3::AsyncWatchAction> call; std::unique_ptr<etcdv3::AsyncWatchAction> call;
}; };
void etcd::Watcher::EtcdServerStubsDeleter::operator()(etcd::Watcher::EtcdServerStubs *stubs) { void etcd::Watcher::EtcdServerStubsDeleter::operator()(
etcd::Watcher::EtcdServerStubs* stubs) {
if (stubs) { if (stubs) {
if (stubs->watchServiceStub) { if (stubs->watchServiceStub) {
stubs->watchServiceStub.reset(); stubs->watchServiceStub.reset();
@ -23,23 +24,20 @@ void etcd::Watcher::EtcdServerStubsDeleter::operator()(etcd::Watcher::EtcdServer
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : Watcher(client, key, -1, callback, wait_callback, recursive) {}
Watcher(client, key, -1, callback, wait_callback, recursive) {
}
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
Watcher(client, key, range_end, -1, callback, wait_callback) { : Watcher(client, key, range_end, -1, callback, wait_callback) {}
}
etcd::Watcher::Watcher(SyncClient const &client, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : wait_callback(wait_callback), fromIndex(fromIndex), recursive(recursive) {
wait_callback(wait_callback), fromIndex(fromIndex), recursive(recursive) {
stubs.reset(new EtcdServerStubs{}); stubs.reset(new EtcdServerStubs{});
stubs->watchServiceStub = Watch::NewStub(client.channel); stubs->watchServiceStub = Watch::NewStub(client.channel);
doWatch(key, "", client.current_auth_token(), callback); doWatch(key, "", client.current_auth_token(), callback);
@ -48,8 +46,8 @@ etcd::Watcher::Watcher(SyncClient const &client, std::string const & key, int64_
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
wait_callback(wait_callback), fromIndex(fromIndex), recursive(false) { : wait_callback(wait_callback), fromIndex(fromIndex), recursive(false) {
stubs.reset(new EtcdServerStubs{}); stubs.reset(new EtcdServerStubs{});
stubs->watchServiceStub = Watch::NewStub(client.channel); stubs->watchServiceStub = Watch::NewStub(client.channel);
doWatch(key, range_end, client.current_auth_token(), callback); doWatch(key, range_end, client.current_auth_token(), callback);
@ -57,203 +55,172 @@ etcd::Watcher::Watcher(SyncClient const &client, std::string const & key,
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : Watcher(address, key, -1, callback, wait_callback, recursive) {}
Watcher(address, key, -1, callback, wait_callback, recursive) {
}
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
Watcher(address, key, range_end, -1, callback, wait_callback) { : Watcher(address, key, range_end, -1, callback, wait_callback) {}
}
etcd::Watcher::Watcher(std::string const & address, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback, bool recursive)
bool recursive): : Watcher(SyncClient(address), key, fromIndex, callback, wait_callback,
Watcher(SyncClient(address), key, fromIndex, callback, wait_callback, recursive) { recursive) {}
}
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback): std::function<void(bool)> wait_callback)
Watcher(SyncClient(address), key, range_end, fromIndex, callback, wait_callback) { : Watcher(SyncClient(address), key, range_end, fromIndex, callback,
} wait_callback) {}
etcd::Watcher::Watcher(std::string const & address, etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, bool recursive,
int const auth_token_ttl)
: Watcher(address, username, password, key, -1, callback, wait_callback,
recursive, auth_token_ttl) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback,
bool recursive, int const auth_token_ttl)
int const auth_token_ttl): : Watcher(address, username, password, key, range_end, -1, callback,
Watcher(address, username, password, key, -1, callback, wait_callback, recursive, auth_token_ttl) { wait_callback, auth_token_ttl) {}
}
etcd::Watcher::Watcher(std::string const & address, etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, bool recursive,
int const auth_token_ttl)
: Watcher(SyncClient(address, username, password, auth_token_ttl), key,
fromIndex, callback, wait_callback, recursive) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
int const auth_token_ttl)
: Watcher(SyncClient(address, username, password, auth_token_ttl), key,
range_end, fromIndex, callback, wait_callback) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& ca,
std::string const& cert, std::string const& privkey,
std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, bool recursive,
std::string const& target_name_override)
: Watcher(SyncClient(address, ca, cert, privkey, target_name_override), key,
fromIndex, callback, wait_callback, recursive) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& ca,
std::string const& cert, std::string const& privkey,
std::string const& key, std::string const& range_end, std::string const& key, std::string const& range_end,
int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
std::function<void(bool)> wait_callback, std::function<void(bool)> wait_callback,
int const auth_token_ttl): std::string const& target_name_override)
Watcher(address, username, password, key, range_end, -1, callback, wait_callback, auth_token_ttl) { : Watcher(SyncClient(address, ca, cert, privkey, target_name_override), key,
} range_end, fromIndex, callback, wait_callback) {}
etcd::Watcher::Watcher(std::string const & address,
std::string const & username, std::string const & password,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
bool recursive,
int const auth_token_ttl):
Watcher(SyncClient(address, username, password, auth_token_ttl), key, fromIndex, callback, wait_callback, recursive) {
}
etcd::Watcher::Watcher(std::string const & address,
std::string const & username, std::string const & password,
std::string const & key, std::string const & range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
int const auth_token_ttl):
Watcher(SyncClient(address, username, password, auth_token_ttl), key, range_end, fromIndex, callback, wait_callback) {
}
etcd::Watcher::Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
bool recursive,
std::string const & target_name_override):
Watcher(SyncClient(address, ca, cert, privkey, target_name_override), key, fromIndex, callback, wait_callback, recursive) {
}
etcd::Watcher::Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const & key, std::string const & range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::function<void(bool)> wait_callback,
std::string const & target_name_override):
Watcher(SyncClient(address, ca, cert, privkey, target_name_override), key, range_end, fromIndex, callback, wait_callback) {
}
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive)
bool recursive): : Watcher(client, key, callback, nullptr, recursive) {}
Watcher(client, key, callback, nullptr, recursive) {
}
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(client, key, range_end, callback, nullptr) { : Watcher(client, key, range_end, callback, nullptr) {}
}
etcd::Watcher::Watcher(SyncClient const &client, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::function<void(Response)> callback, int64_t fromIndex,
bool recursive): std::function<void(Response)> callback, bool recursive)
Watcher(client, key, fromIndex, callback, nullptr, recursive) { : Watcher(client, key, fromIndex, callback, nullptr, recursive) {}
}
etcd::Watcher::Watcher(SyncClient const& client, std::string const& key, etcd::Watcher::Watcher(SyncClient const& client, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(client, key, range_end, fromIndex, callback, nullptr) { : Watcher(client, key, range_end, fromIndex, callback, nullptr) {}
}
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::function<void(Response)> callback, std::function<void(Response)> callback, bool recursive)
bool recursive): : Watcher(address, key, callback, nullptr, recursive) {}
Watcher(address, key, callback, nullptr, recursive) {
}
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::string const& range_end, std::string const& range_end,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(address, key, range_end, callback, nullptr) { : Watcher(address, key, range_end, callback, nullptr) {}
}
etcd::Watcher::Watcher(std::string const & address, std::string const & key, int64_t fromIndex, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::function<void(Response)> callback, int64_t fromIndex,
bool recursive): std::function<void(Response)> callback, bool recursive)
Watcher(address, key, fromIndex, callback, nullptr, recursive) { : Watcher(address, key, fromIndex, callback, nullptr, recursive) {}
}
etcd::Watcher::Watcher(std::string const& address, std::string const& key, etcd::Watcher::Watcher(std::string const& address, std::string const& key,
std::string const& range_end, int64_t fromIndex, std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback): std::function<void(Response)> callback)
Watcher(address, key, range_end, fromIndex, callback, nullptr) { : Watcher(address, key, range_end, fromIndex, callback, nullptr) {}
}
etcd::Watcher::Watcher(std::string const & address, etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
std::string const & key, std::function<void(Response)> callback, bool recursive,
int const auth_token_ttl)
: Watcher(address, username, password, key, callback, nullptr, recursive,
auth_token_ttl) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end,
std::function<void(Response)> callback, std::function<void(Response)> callback,
bool recursive, int const auth_token_ttl)
int const auth_token_ttl): : Watcher(address, username, password, key, range_end, callback, nullptr,
Watcher(address, username, password, key, callback, nullptr, recursive, auth_token_ttl) { auth_token_ttl) {}
}
etcd::Watcher::Watcher(std::string const & address, etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const & username, std::string const & password, std::string const& password, std::string const& key,
int64_t fromIndex,
std::function<void(Response)> callback, bool recursive,
int const auth_token_ttl)
: Watcher(address, username, password, key, fromIndex, callback, nullptr,
recursive, auth_token_ttl) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& username,
std::string const& password, std::string const& key,
std::string const& range_end, int64_t fromIndex,
std::function<void(Response)> callback,
int const auth_token_ttl)
: Watcher(address, username, password, key, range_end, fromIndex, callback,
nullptr, auth_token_ttl) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& ca,
std::string const& cert, std::string const& privkey,
std::string const& key, int64_t fromIndex,
std::function<void(Response)> callback, bool recursive,
std::string const& target_name_override)
: Watcher(address, ca, cert, privkey, key, fromIndex, callback, nullptr,
recursive, target_name_override) {}
etcd::Watcher::Watcher(std::string const& address, std::string const& ca,
std::string const& cert, std::string const& privkey,
std::string const& key, std::string const& range_end, std::string const& key, std::string const& range_end,
int64_t fromIndex,
std::function<void(Response)> callback, std::function<void(Response)> callback,
int const auth_token_ttl): std::string const& target_name_override)
Watcher(address, username, password, key, range_end, callback, nullptr, auth_token_ttl) { : Watcher(address, ca, cert, privkey, key, range_end, fromIndex, callback,
} nullptr, target_name_override) {}
etcd::Watcher::Watcher(std::string const & address, etcd::Watcher::~Watcher() { this->Cancel(); }
std::string const & username, std::string const & password,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
bool recursive,
int const auth_token_ttl):
Watcher(address, username, password, key, fromIndex, callback, nullptr, recursive, auth_token_ttl) {
}
etcd::Watcher::Watcher(std::string const & address, bool etcd::Watcher::Wait() {
std::string const & username, std::string const & password,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
int const auth_token_ttl):
Watcher(address, username, password, key, range_end, fromIndex, callback, nullptr, auth_token_ttl) {
}
etcd::Watcher::Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const & key, int64_t fromIndex,
std::function<void(Response)> callback,
bool recursive,
std::string const & target_name_override):
Watcher(address, ca, cert, privkey, key, fromIndex, callback, nullptr, recursive, target_name_override) {
}
etcd::Watcher::Watcher(std::string const & address,
std::string const & ca,
std::string const & cert,
std::string const & privkey,
std::string const & key, std::string const &range_end, int64_t fromIndex,
std::function<void(Response)> callback,
std::string const & target_name_override):
Watcher(address, ca, cert, privkey, key, range_end, fromIndex, callback, nullptr, target_name_override) {
}
etcd::Watcher::~Watcher()
{
this->Cancel();
}
bool etcd::Watcher::Wait()
{
if (!cancelled.exchange(true)) { if (!cancelled.exchange(true)) {
if (task_.joinable()) { if (task_.joinable()) {
task_.join(); task_.join();
@ -262,31 +229,29 @@ bool etcd::Watcher::Wait()
return stubs->call->Cancelled(); return stubs->call->Cancelled();
} }
void etcd::Watcher::Wait(std::function<void(bool)> callback) void etcd::Watcher::Wait(std::function<void(bool)> callback) {
{
if (wait_callback == nullptr) { if (wait_callback == nullptr) {
wait_callback = callback; wait_callback = callback;
} else { } else {
std::cerr << "Failed to set a asynchronous wait callback since it has already been set" << std::endl; std::cerr << "Failed to set a asynchronous wait callback since it has "
"already been set"
<< std::endl;
} }
} }
bool etcd::Watcher::Cancel() bool etcd::Watcher::Cancel() {
{
stubs->call->CancelWatch(); stubs->call->CancelWatch();
return this->Wait(); return this->Wait();
} }
bool etcd::Watcher::Cancelled() const bool etcd::Watcher::Cancelled() const {
{
return cancelled.load() || stubs->call->Cancelled(); return cancelled.load() || stubs->call->Cancelled();
} }
void etcd::Watcher::doWatch(std::string const& key, void etcd::Watcher::doWatch(std::string const& key,
std::string const& range_end, std::string const& range_end,
std::string const& auth_token, std::string const& auth_token,
std::function<void(Response)> callback) std::function<void(Response)> callback) {
{
etcdv3::ActionParameters params; etcdv3::ActionParameters params;
params.auth_token.assign(auth_token); params.auth_token.assign(auth_token);
// n.b.: watch: no need for timeout // n.b.: watch: no need for timeout
@ -304,13 +269,12 @@ void etcd::Watcher::doWatch(std::string const & key,
stubs->call->waitForResponse(callback); stubs->call->waitForResponse(callback);
if (wait_callback != nullptr) { if (wait_callback != nullptr) {
// issue the callback in another thread (detached) to avoid deadlock, // issue the callback in another thread (detached) to avoid deadlock,
// it is ok to detach a pplx::task, but we don't want to use the pplx::task // it is ok to detach a pplx::task, but we don't want to use the
// in the core library // pplx::task in the core library
bool cancelled = stubs->call->Cancelled(); bool cancelled = stubs->call->Cancelled();
std::function<void(bool)> wait_callback = this->wait_callback; std::function<void(bool)> wait_callback = this->wait_callback;
std::thread canceller([wait_callback, cancelled]() { std::thread canceller(
wait_callback(cancelled); [wait_callback, cancelled]() { wait_callback(cancelled); });
});
canceller.detach(); canceller.detach();
} }
}); });

View File

@ -1,16 +1,14 @@
#include "etcd/v3/Action.hpp"
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/support/status.h> #include <grpcpp/support/status.h>
#include "etcd/v3/action_constants.hpp" #include "etcd/v3/action_constants.hpp"
#include "etcd/v3/Action.hpp"
etcdv3::Action::Action(etcdv3::ActionParameters const &params) etcdv3::Action::Action(etcdv3::ActionParameters const& params) {
{
parameters = params; parameters = params;
this->InitAction(); this->InitAction();
} }
etcdv3::Action::Action(etcdv3::ActionParameters && params) etcdv3::Action::Action(etcdv3::ActionParameters&& params) {
{
parameters = std::move(params); parameters = std::move(params);
this->InitAction(); this->InitAction();
} }
@ -32,8 +30,7 @@ void etcdv3::Action::InitAction() {
start_timepoint = std::chrono::high_resolution_clock::now(); start_timepoint = std::chrono::high_resolution_clock::now();
} }
etcdv3::ActionParameters::ActionParameters() etcdv3::ActionParameters::ActionParameters() {
{
withPrefix = false; withPrefix = false;
revision = 0; revision = 0;
old_revision = 0; old_revision = 0;
@ -50,7 +47,8 @@ bool etcdv3::ActionParameters::has_grpc_timeout() const {
return this->grpc_timeout != std::chrono::microseconds::zero(); return this->grpc_timeout != std::chrono::microseconds::zero();
} }
std::chrono::system_clock::time_point etcdv3::ActionParameters::grpc_deadline() const { std::chrono::system_clock::time_point etcdv3::ActionParameters::grpc_deadline()
const {
return std::chrono::system_clock::now() + this->grpc_timeout; return std::chrono::system_clock::now() + this->grpc_timeout;
} }
@ -73,24 +71,27 @@ void etcdv3::ActionParameters::dump(std::ostream &os) const {
os << " grpc_timeout: " << grpc_timeout.count() << "(ms)" << std::endl; os << " grpc_timeout: " << grpc_timeout.count() << "(ms)" << std::endl;
} }
void etcdv3::Action::waitForResponse() void etcdv3::Action::waitForResponse() {
{
void* got_tag; void* got_tag;
bool ok = false; bool ok = false;
if (parameters.has_grpc_timeout()) { if (parameters.has_grpc_timeout()) {
switch (cq_.AsyncNext(&got_tag, &ok, parameters.grpc_deadline())) { switch (cq_.AsyncNext(&got_tag, &ok, parameters.grpc_deadline())) {
case CompletionQueue::NextStatus::TIMEOUT: { case CompletionQueue::NextStatus::TIMEOUT: {
status = grpc::Status(grpc::StatusCode::DEADLINE_EXCEEDED, "gRPC timeout"); status =
grpc::Status(grpc::StatusCode::DEADLINE_EXCEEDED, "gRPC timeout");
break; break;
} }
case CompletionQueue::NextStatus::SHUTDOWN: { case CompletionQueue::NextStatus::SHUTDOWN: {
status = grpc::Status(grpc::StatusCode::UNAVAILABLE, "gRPC already shutdown"); status =
grpc::Status(grpc::StatusCode::UNAVAILABLE, "gRPC already shutdown");
break; break;
} }
case CompletionQueue::NextStatus::GOT_EVENT: { case CompletionQueue::NextStatus::GOT_EVENT: {
if (!ok) { if (!ok) {
status = grpc::Status(grpc::StatusCode::ABORTED, "Failed to execute the action: not ok or invalid tag"); status =
grpc::Status(grpc::StatusCode::ABORTED,
"Failed to execute the action: not ok or invalid tag");
} }
break; break;
} }
@ -101,7 +102,8 @@ void etcdv3::Action::waitForResponse()
} }
} }
const std::chrono::high_resolution_clock::time_point etcdv3::Action::startTimepoint() { const std::chrono::high_resolution_clock::time_point
etcdv3::Action::startTimepoint() {
return this->start_timepoint; return this->start_timepoint;
} }
@ -117,7 +119,8 @@ std::string etcdv3::detail::string_plus_one(std::string const &value) {
return {etcdv3::NUL}; return {etcdv3::NUL};
} }
std::string etcdv3::detail::resolve_etcd_endpoints(std::string const&default_endpoints) { std::string etcdv3::detail::resolve_etcd_endpoints(
std::string const& default_endpoints) {
const char* ep = std::getenv("ETCD_ENDPOINTS"); const char* ep = std::getenv("ETCD_ENDPOINTS");
return ep ? ep : default_endpoints; return ep ? ep : default_endpoints;
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,7 @@
#include "etcd/v3/KeyValue.hpp" #include "etcd/v3/KeyValue.hpp"
etcdv3::KeyValue::KeyValue() etcdv3::KeyValue::KeyValue() { ttl = 0; }
{
ttl = 0;
}
void etcdv3::KeyValue::set_ttl(int ttl) void etcdv3::KeyValue::set_ttl(int ttl) { this->ttl = ttl; }
{
this->ttl = ttl;
}
int etcdv3::KeyValue::get_ttl() const int etcdv3::KeyValue::get_ttl() const { return ttl; }
{
return ttl;
}

View File

@ -3,10 +3,10 @@
#include "proto/rpc.grpc.pb.h" #include "proto/rpc.grpc.pb.h"
using etcdserverpb::Compare; using etcdserverpb::Compare;
using etcdserverpb::RangeRequest;
using etcdserverpb::PutRequest;
using etcdserverpb::RequestOp;
using etcdserverpb::DeleteRangeRequest; using etcdserverpb::DeleteRangeRequest;
using etcdserverpb::PutRequest;
using etcdserverpb::RangeRequest;
using etcdserverpb::RequestOp;
namespace etcdv3 { namespace etcdv3 {
@ -20,9 +20,9 @@ static etcdserverpb::Compare::CompareTarget to_compare_target(CompareTarget t) {
return static_cast<etcdserverpb::Compare::CompareTarget>(static_cast<int>(t)); return static_cast<etcdserverpb::Compare::CompareTarget>(static_cast<int>(t));
} }
} } // namespace detail
} } // namespace etcdv3
etcdv3::Transaction::Transaction() { etcdv3::Transaction::Transaction() {
txn_request.reset(new etcdserverpb::TxnRequest{}); txn_request.reset(new etcdserverpb::TxnRequest{});
@ -32,11 +32,10 @@ etcdv3::Transaction::Transaction(const std::string& key) : key(key) {
txn_request.reset(new etcdserverpb::TxnRequest{}); txn_request.reset(new etcdserverpb::TxnRequest{});
} }
void etcdv3::Transaction::reset_key(std::string const& newkey) { void etcdv3::Transaction::reset_key(std::string const& newkey) { key = newkey; }
key = newkey;
}
void etcdv3::Transaction::init_compare(CompareResult result, CompareTarget target){ void etcdv3::Transaction::init_compare(CompareResult result,
CompareTarget target) {
Compare* compare = txn_request->add_compare(); Compare* compare = txn_request->add_compare();
compare->set_result(detail::to_compare_result(result)); compare->set_result(detail::to_compare_result(result));
compare->set_target(detail::to_compare_target(target)); compare->set_target(detail::to_compare_target(target));
@ -45,7 +44,9 @@ void etcdv3::Transaction::init_compare(CompareResult result, CompareTarget targe
compare->set_version(0); compare->set_version(0);
} }
void etcdv3::Transaction::init_compare(std::string const& old_value, CompareResult result, CompareTarget target){ void etcdv3::Transaction::init_compare(std::string const& old_value,
CompareResult result,
CompareTarget target) {
Compare* compare = txn_request->add_compare(); Compare* compare = txn_request->add_compare();
compare->set_result(detail::to_compare_result(result)); compare->set_result(detail::to_compare_result(result));
compare->set_target(detail::to_compare_target(target)); compare->set_target(detail::to_compare_target(target));
@ -54,7 +55,8 @@ void etcdv3::Transaction::init_compare(std::string const& old_value, CompareResu
compare->set_value(old_value); compare->set_value(old_value);
} }
void etcdv3::Transaction::init_compare(int64_t old_index, CompareResult result, CompareTarget target){ void etcdv3::Transaction::init_compare(int64_t old_index, CompareResult result,
CompareTarget target) {
Compare* compare = txn_request->add_compare(); Compare* compare = txn_request->add_compare();
compare->set_result(detail::to_compare_result(result)); compare->set_result(detail::to_compare_result(result));
compare->set_target(detail::to_compare_target(target)); compare->set_target(detail::to_compare_target(target));
@ -66,7 +68,8 @@ void etcdv3::Transaction::init_compare(int64_t old_index, CompareResult result,
/** /**
* get key on failure * get key on failure
*/ */
void etcdv3::Transaction::setup_basic_failure_operation(std::string const& key) { void etcdv3::Transaction::setup_basic_failure_operation(
std::string const& key) {
std::unique_ptr<RangeRequest> get_request(new RangeRequest()); std::unique_ptr<RangeRequest> get_request(new RangeRequest());
get_request->set_key(key); get_request->set_key(key);
RequestOp* req_failure = txn_request->add_failure(); RequestOp* req_failure = txn_request->add_failure();
@ -76,7 +79,9 @@ void etcdv3::Transaction::setup_basic_failure_operation(std::string const& key)
/** /**
* get key on failure, get key before put, modify and then get updated key * get key on failure, get key before put, modify and then get updated key
*/ */
void etcdv3::Transaction::setup_set_failure_operation(std::string const &key, std::string const &value, int64_t leaseid) { void etcdv3::Transaction::setup_set_failure_operation(std::string const& key,
std::string const& value,
int64_t leaseid) {
std::unique_ptr<PutRequest> put_request(new PutRequest()); std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key); put_request->set_key(key);
put_request->set_value(value); put_request->set_value(value);
@ -94,7 +99,9 @@ void etcdv3::Transaction::setup_set_failure_operation(std::string const &key, st
/** /**
* add key and then get new value of key * add key and then get new value of key
*/ */
void etcdv3::Transaction::setup_basic_create_sequence(std::string const& key, std::string const& value, int64_t leaseid) { void etcdv3::Transaction::setup_basic_create_sequence(std::string const& key,
std::string const& value,
int64_t leaseid) {
std::unique_ptr<PutRequest> put_request(new PutRequest()); std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key); put_request->set_key(key);
put_request->set_value(value); put_request->set_value(value);
@ -112,7 +119,8 @@ void etcdv3::Transaction::setup_basic_create_sequence(std::string const& key, st
/** /**
* get key value then modify and get new value * get key value then modify and get new value
*/ */
void etcdv3::Transaction::setup_compare_and_swap_sequence(std::string const& value, int64_t leaseid) { void etcdv3::Transaction::setup_compare_and_swap_sequence(
std::string const& value, int64_t leaseid) {
std::unique_ptr<PutRequest> put_request(new PutRequest()); std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key); put_request->set_key(key);
put_request->set_value(value); put_request->set_value(value);
@ -130,12 +138,13 @@ void etcdv3::Transaction::setup_compare_and_swap_sequence(std::string const& val
/** /**
* get key, delete * get key, delete
*/ */
void etcdv3::Transaction::setup_delete_sequence(std::string const &key, std::string const &range_end, bool recursive) { void etcdv3::Transaction::setup_delete_sequence(std::string const& key,
std::string const& range_end,
bool recursive) {
std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest()); std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest());
del_request->set_key(key); del_request->set_key(key);
del_request->set_prev_kv(true); del_request->set_prev_kv(true);
if(recursive) if (recursive) {
{
del_request->set_range_end(range_end); del_request->set_range_end(range_end);
} }
@ -146,24 +155,25 @@ void etcdv3::Transaction::setup_delete_sequence(std::string const &key, std::str
/** /**
* get key, delete * get key, delete
*/ */
void etcdv3::Transaction::setup_delete_failure_operation(std::string const &key, std::string const &range_end, bool recursive) { void etcdv3::Transaction::setup_delete_failure_operation(
std::string const& key, std::string const& range_end, bool recursive) {
std::unique_ptr<RangeRequest> get_request(new RangeRequest()); std::unique_ptr<RangeRequest> get_request(new RangeRequest());
std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest()); std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest());
get_request.reset(new RangeRequest()); get_request.reset(new RangeRequest());
get_request->set_key(key); get_request->set_key(key);
if(recursive) if (recursive) {
{
get_request->set_range_end(range_end); get_request->set_range_end(range_end);
get_request->set_sort_target(RangeRequest::SortTarget::RangeRequest_SortTarget_KEY); get_request->set_sort_target(
get_request->set_sort_order(RangeRequest::SortOrder::RangeRequest_SortOrder_ASCEND); RangeRequest::SortTarget::RangeRequest_SortTarget_KEY);
get_request->set_sort_order(
RangeRequest::SortOrder::RangeRequest_SortOrder_ASCEND);
} }
RequestOp* req_failure = txn_request->add_failure(); RequestOp* req_failure = txn_request->add_failure();
req_failure->set_allocated_request_range(get_request.release()); req_failure->set_allocated_request_range(get_request.release());
del_request.reset(new DeleteRangeRequest()); del_request.reset(new DeleteRangeRequest());
del_request->set_key(key); del_request->set_key(key);
if(recursive) if (recursive) {
{
del_request->set_range_end(range_end); del_request->set_range_end(range_end);
} }
@ -171,7 +181,8 @@ void etcdv3::Transaction::setup_delete_failure_operation(std::string const &key,
req_failure->set_allocated_request_delete_range(del_request.release()); req_failure->set_allocated_request_delete_range(del_request.release());
} }
void etcdv3::Transaction::setup_compare_and_delete_operation(std::string const& key) { void etcdv3::Transaction::setup_compare_and_delete_operation(
std::string const& key) {
std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest()); std::unique_ptr<DeleteRangeRequest> del_request(new DeleteRangeRequest());
del_request->set_key(key); del_request->set_key(key);
del_request->set_prev_kv(true); del_request->set_prev_kv(true);
@ -179,7 +190,8 @@ void etcdv3::Transaction::setup_compare_and_delete_operation(std::string const&
req_success->set_allocated_request_delete_range(del_request.release()); req_success->set_allocated_request_delete_range(del_request.release());
} }
void etcdv3::Transaction::setup_put(std::string const &key, std::string const &value) { void etcdv3::Transaction::setup_put(std::string const& key,
std::string const& value) {
std::unique_ptr<PutRequest> put_request(new PutRequest()); std::unique_ptr<PutRequest> put_request(new PutRequest());
put_request->set_key(key); put_request->set_key(key);
put_request->set_value(value); put_request->set_value(value);
@ -197,5 +209,4 @@ void etcdv3::Transaction::setup_delete(std::string const &key) {
req_success->set_allocated_request_delete_range(del_request.release()); req_success->set_allocated_request_delete_range(del_request.release());
} }
etcdv3::Transaction::~Transaction() { etcdv3::Transaction::~Transaction() {}
}

View File

@ -1,83 +1,54 @@
#include "etcd/v3/V3Response.hpp" #include "etcd/v3/V3Response.hpp"
#include "etcd/v3/action_constants.hpp" #include "etcd/v3/action_constants.hpp"
void etcdv3::V3Response::set_error_code(int code) void etcdv3::V3Response::set_error_code(int code) { error_code = code; }
{
error_code = code;
}
void etcdv3::V3Response::set_error_message(std::string msg) void etcdv3::V3Response::set_error_message(std::string msg) {
{
error_message = msg; error_message = msg;
} }
int64_t etcdv3::V3Response::get_index() const int64_t etcdv3::V3Response::get_index() const { return index; }
{
return index;
}
std::string const & etcdv3::V3Response::get_action() const std::string const& etcdv3::V3Response::get_action() const { return action; }
{
return action;
}
int etcdv3::V3Response::get_error_code() const int etcdv3::V3Response::get_error_code() const { return error_code; }
{
return error_code;
}
std::string const & etcdv3::V3Response::get_error_message() const std::string const& etcdv3::V3Response::get_error_message() const {
{
return error_message; return error_message;
} }
void etcdv3::V3Response::set_action(std::string action) void etcdv3::V3Response::set_action(std::string action) {
{
this->action = action; this->action = action;
} }
std::vector<etcdv3::KeyValue> const & etcdv3::V3Response::get_values() const std::vector<etcdv3::KeyValue> const& etcdv3::V3Response::get_values() const {
{
return values; return values;
} }
std::vector<etcdv3::KeyValue> const & etcdv3::V3Response::get_prev_values() const std::vector<etcdv3::KeyValue> const& etcdv3::V3Response::get_prev_values()
{ const {
return prev_values; return prev_values;
} }
etcdv3::KeyValue const & etcdv3::V3Response::get_value() const etcdv3::KeyValue const& etcdv3::V3Response::get_value() const { return value; }
{
return value;
}
etcdv3::KeyValue const & etcdv3::V3Response::get_prev_value() const etcdv3::KeyValue const& etcdv3::V3Response::get_prev_value() const {
{
return prev_value; return prev_value;
} }
bool etcdv3::V3Response::has_values() const bool etcdv3::V3Response::has_values() const { return values.size() > 0; }
{
return values.size() > 0;
}
int64_t etcdv3::V3Response::get_compact_revision() const int64_t etcdv3::V3Response::get_compact_revision() const {
{
return compact_revision; return compact_revision;
} }
void etcdv3::V3Response::set_compact_revision(const int64_t compact_revision) void etcdv3::V3Response::set_compact_revision(const int64_t compact_revision) {
{
this->compact_revision = compact_revision; this->compact_revision = compact_revision;
} }
int64_t etcdv3::V3Response::get_watch_id() const int64_t etcdv3::V3Response::get_watch_id() const { return watch_id; }
{
return watch_id;
}
void etcdv3::V3Response::set_watch_id(const int64_t watch_id) void etcdv3::V3Response::set_watch_id(const int64_t watch_id) {
{
this->watch_id = watch_id; this->watch_id = watch_id;
} }
@ -93,25 +64,17 @@ void etcdv3::V3Response::set_name(std::string const &name) {
this->name = name; this->name = name;
} }
std::string const & etcdv3::V3Response::get_name() const { std::string const& etcdv3::V3Response::get_name() const { return this->name; }
return this->name;
}
std::vector<mvccpb::Event> const& etcdv3::V3Response::get_events() const { std::vector<mvccpb::Event> const& etcdv3::V3Response::get_events() const {
return this->events; return this->events;
} }
uint64_t etcdv3::V3Response::get_cluster_id() const { uint64_t etcdv3::V3Response::get_cluster_id() const { return this->cluster_id; }
return this->cluster_id;
}
uint64_t etcdv3::V3Response::get_member_id() const { uint64_t etcdv3::V3Response::get_member_id() const { return this->member_id; }
return this->member_id;
}
uint64_t etcdv3::V3Response::get_raft_term() const { uint64_t etcdv3::V3Response::get_raft_term() const { return this->raft_term; }
return this->raft_term;
}
std::vector<int64_t> const& etcdv3::V3Response::get_leases() const { std::vector<int64_t> const& etcdv3::V3Response::get_leases() const {
return this->leases; return this->leases;

View File

@ -5,16 +5,15 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("setup with auth") TEST_CASE("setup with auth") {
{
etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root"); etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root");
etcd->rmdir("/test", true).wait(); etcd->rmdir("/test", true).wait();
} }
TEST_CASE("add a new key after authenticate") TEST_CASE("add a new key after authenticate") {
{
etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root"); etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root");
etcd->rmdir("/test", true).wait(); etcd->rmdir("/test", true).wait();
etcd::Response resp = etcd->add("/test/key1", "42").get(); etcd::Response resp = etcd->add("/test/key1", "42").get();
@ -28,24 +27,28 @@ TEST_CASE("add a new key after authenticate")
CHECK(0 < val.modified_index()); CHECK(0 < val.modified_index());
CHECK(1 == val.version()); CHECK(1 == val.version());
CHECK(0 < resp.index()); CHECK(0 < resp.index());
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd->add("/test/key1", "43").get().error_code()); // Key already exists CHECK(
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd->add("/test/key1", "42").get().error_code()); // Key already exists etcd::ERROR_KEY_ALREADY_EXISTS ==
CHECK("etcd-cpp-apiv3: key already exists" == etcd->add("/test/key1", "42").get().error_message()); etcd->add("/test/key1", "43").get().error_code()); // Key already exists
CHECK(
etcd::ERROR_KEY_ALREADY_EXISTS ==
etcd->add("/test/key1", "42").get().error_code()); // Key already exists
CHECK("etcd-cpp-apiv3: key already exists" ==
etcd->add("/test/key1", "42").get().error_message());
} }
TEST_CASE("read a value from etcd") TEST_CASE("read a value from etcd") {
{
etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root"); etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root");
etcd::Response resp = etcd->get("/test/key1").get(); etcd::Response resp = etcd->get("/test/key1").get();
CHECK("get" == resp.action()); CHECK("get" == resp.action());
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
REQUIRE(0 == resp.error_code()); REQUIRE(0 == resp.error_code());
CHECK("42" == resp.value().as_string()); CHECK("42" == resp.value().as_string());
CHECK("" == etcd->get("/test").get().value().as_string()); // key points to a directory CHECK("" == etcd->get("/test").get().value().as_string()); // key points to a
// directory
} }
TEST_CASE("cleanup") TEST_CASE("cleanup") {
{
etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root"); etcd::Client* etcd = etcd::Client::WithUser(etcd_url, "root", "root");
REQUIRE(0 == etcd->rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd->rmdir("/test", true).get().error_code());
} }

View File

@ -39,13 +39,14 @@ TEST_CASE("campaign and leadership using keepalive") {
std::cout << "finish leader" << std::endl; std::cout << "finish leader" << std::endl;
auto resp3 = etcd.resign("/leader", resp1.value().lease(), resp1.value().key(), resp1.value().created_index()).get(); auto resp3 = etcd.resign("/leader", resp1.value().lease(),
resp1.value().key(), resp1.value().created_index())
.get();
CHECK(0 == resp3.error_code()); CHECK(0 == resp3.error_code());
std::cout << "finish resign" << std::endl; std::cout << "finish resign" << std::endl;
} }
TEST_CASE("concurrent campaign with grpc timeout") { TEST_CASE("concurrent campaign with grpc timeout") {
std::string value1 = std::string("192.168.1.6:1880"); std::string value1 = std::string("192.168.1.6:1880");
std::string value2 = std::string("192.168.1.6:1890"); std::string value2 = std::string("192.168.1.6:1890");
@ -60,7 +61,9 @@ TEST_CASE("concurrent campaign with grpc timeout") {
std::this_thread::sleep_for(std::chrono::seconds(10)); std::this_thread::sleep_for(std::chrono::seconds(10));
// resign // resign
auto resp2 = etcd.resign("/leader", resp1.value().lease(), resp1.value().key(), resp1.value().created_index()).get(); auto resp2 = etcd.resign("/leader", resp1.value().lease(),
resp1.value().key(), resp1.value().created_index())
.get();
CHECK(0 == resp2.error_code()); CHECK(0 == resp2.error_code());
}; };
@ -92,7 +95,9 @@ TEST_CASE("concurrent campaign with grpc timeout") {
} }
} }
auto resp2 = etcd.resign("/leader", resp1.value().lease(), resp1.value().key(), resp1.value().created_index()).get(); auto resp2 = etcd.resign("/leader", resp1.value().lease(),
resp1.value().key(), resp1.value().created_index())
.get();
CHECK(0 == resp2.error_code()); CHECK(0 == resp2.error_code());
}; };

View File

@ -8,16 +8,15 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("setup") TEST_CASE("setup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
} }
TEST_CASE("campaign and resign") TEST_CASE("campaign and resign") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
auto keepalive = etcd.leasekeepalive(60).get(); auto keepalive = etcd.leasekeepalive(60).get();
@ -36,9 +35,9 @@ TEST_CASE("campaign and resign")
} }
// proclaim // proclaim
auto resp3 = etcd.proclaim("test", lease_id, auto resp3 = etcd.proclaim("test", lease_id, resp1.value().key(),
resp1.value().key(), resp1.value().created_index(), resp1.value().created_index(), "tttt")
"tttt").get(); .get();
REQUIRE(0 == resp3.error_code()); REQUIRE(0 == resp3.error_code());
// leader // leader
@ -50,13 +49,13 @@ TEST_CASE("campaign and resign")
} }
// resign // resign
auto resp5 = etcd.resign("test", lease_id, auto resp5 = etcd.resign("test", lease_id, resp1.value().key(),
resp1.value().key(), resp1.value().created_index()).get(); resp1.value().created_index())
.get();
REQUIRE(0 == resp5.error_code()); REQUIRE(0 == resp5.error_code());
} }
TEST_CASE("campaign and observe") TEST_CASE("campaign and observe") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
auto keepalive = etcd.leasekeepalive(60).get(); auto keepalive = etcd.leasekeepalive(60).get();
@ -67,7 +66,8 @@ TEST_CASE("campaign and observe")
// wait many change events, blocked execution // wait many change events, blocked execution
for (size_t i = 0; i < 10; ++i) { for (size_t i = 0; i < 10; ++i) {
etcd::Response resp = observer->WaitOnce(); etcd::Response resp = observer->WaitOnce();
std::cout << "observe " << resp.value().key() << " as the leader: " << resp.value().as_string() << std::endl; std::cout << "observe " << resp.value().key()
<< " as the leader: " << resp.value().as_string() << std::endl;
} }
std::cout << "finish the observe" << std::endl; std::cout << "finish the observe" << std::endl;
// cancel the observers // cancel the observers
@ -109,8 +109,7 @@ TEST_CASE("campaign and observe")
observer_thread.join(); observer_thread.join();
} }
TEST_CASE("cleanup") TEST_CASE("cleanup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).get(); etcd.rmdir("/test", true).get();
} }

View File

@ -5,21 +5,23 @@
#include "etcd/SyncClient.hpp" #include "etcd/SyncClient.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("sync operations") TEST_CASE("sync operations") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
// add // add
CHECK(0 == etcd.add("/test/key1", "42").error_code()); CHECK(0 == etcd.add("/test/key1", "42").error_code());
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd.add("/test/key1", "42").error_code()); // Key already exists CHECK(etcd::ERROR_KEY_ALREADY_EXISTS ==
etcd.add("/test/key1", "42").error_code()); // Key already exists
CHECK("42" == etcd.get("/test/key1").value().as_string()); CHECK("42" == etcd.get("/test/key1").value().as_string());
// modify // modify
CHECK(0 == etcd.modify("/test/key1", "43").error_code()); CHECK(0 == etcd.modify("/test/key1", "43").error_code());
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.modify("/test/key2", "43").error_code()); // Key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.modify("/test/key2", "43").error_code()); // Key not found
CHECK("43" == etcd.modify("/test/key1", "42").prev_value().as_string()); CHECK("43" == etcd.modify("/test/key1", "42").prev_value().as_string());
// set // set
@ -32,7 +34,8 @@ TEST_CASE("sync operations")
CHECK("43" == etcd.get("/test/key1").value().as_string()); CHECK("43" == etcd.get("/test/key1").value().as_string());
CHECK("44" == etcd.get("/test/key2").value().as_string()); CHECK("44" == etcd.get("/test/key2").value().as_string());
CHECK("44" == etcd.get("/test/key3").value().as_string()); CHECK("44" == etcd.get("/test/key3").value().as_string());
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.get("/test/key4").error_code()); // key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.get("/test/key4").error_code()); // key not found
// rm // rm
CHECK(3 == etcd.ls("/test").keys().size()); CHECK(3 == etcd.ls("/test").keys().size());
@ -51,24 +54,29 @@ TEST_CASE("sync operations")
CHECK(2 == etcd.keys("/test/new_dir").keys().size()); CHECK(2 == etcd.keys("/test/new_dir").keys().size());
// rmdir // rmdir
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.rmdir("/test/new_dir").error_code()); // key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.rmdir("/test/new_dir").error_code()); // key not found
CHECK(0 == etcd.rmdir("/test/new_dir", true).error_code()); CHECK(0 == etcd.rmdir("/test/new_dir", true).error_code());
// compare and swap // compare and swap
etcd.set("/test/key1", "42"); etcd.set("/test/key1", "42");
int64_t index = etcd.modify_if("/test/key1", "43", "42").index(); int64_t index = etcd.modify_if("/test/key1", "43", "42").index();
CHECK(etcd::ERROR_COMPARE_FAILED == etcd.modify_if("/test/key1", "44", "42").error_code()); CHECK(etcd::ERROR_COMPARE_FAILED ==
etcd.modify_if("/test/key1", "44", "42").error_code());
REQUIRE(etcd.modify_if("/test/key1", "44", index).is_ok()); REQUIRE(etcd.modify_if("/test/key1", "44", index).is_ok());
CHECK(etcd::ERROR_COMPARE_FAILED == etcd.modify_if("/test/key1", "45", index).error_code()); CHECK(etcd::ERROR_COMPARE_FAILED ==
etcd.modify_if("/test/key1", "45", index).error_code());
// atomic compare-and-delete based on prevValue // atomic compare-and-delete based on prevValue
etcd.set("/test/key1", "42"); etcd.set("/test/key1", "42");
CHECK(etcd::ERROR_COMPARE_FAILED == etcd.rm_if("/test/key1", "43").error_code()); CHECK(etcd::ERROR_COMPARE_FAILED ==
etcd.rm_if("/test/key1", "43").error_code());
CHECK(0 == etcd.rm_if("/test/key1", "42").error_code()); CHECK(0 == etcd.rm_if("/test/key1", "42").error_code());
// atomic compare-and-delete based on prevIndex // atomic compare-and-delete based on prevIndex
index = etcd.set("/test/key1", "42").index(); index = etcd.set("/test/key1", "42").index();
CHECK(etcd::ERROR_COMPARE_FAILED == etcd.rm_if("/test/key1", index - 1).error_code()); CHECK(etcd::ERROR_COMPARE_FAILED ==
etcd.rm_if("/test/key1", index - 1).error_code());
CHECK(0 == etcd.rm_if("/test/key1", index).error_code()); CHECK(0 == etcd.rm_if("/test/key1", index).error_code());
// leasegrant // leasegrant
@ -114,8 +122,7 @@ TEST_CASE("sync operations")
REQUIRE(0 == etcd.rmdir("/test", true).error_code()); REQUIRE(0 == etcd.rmdir("/test", true).error_code());
} }
TEST_CASE("wait for a value change") TEST_CASE("wait for a value change") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.set("/test/key1", "42"); etcd.set("/test/key1", "42");
@ -132,8 +139,7 @@ TEST_CASE("wait for a value change")
REQUIRE(0 == etcd.rmdir("/test", true).error_code()); REQUIRE(0 == etcd.rmdir("/test", true).error_code());
} }
TEST_CASE("wait for a directory change") TEST_CASE("wait for a directory change") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
std::thread watch_thrd1([&]() { std::thread watch_thrd1([&]() {
@ -159,8 +165,7 @@ TEST_CASE("wait for a directory change")
REQUIRE(0 == etcd.rmdir("/test", true).error_code()); REQUIRE(0 == etcd.rmdir("/test", true).error_code());
} }
TEST_CASE("watch changes in the past") TEST_CASE("watch changes in the past") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
int64_t index = etcd.set("/test/key1", "42").index(); int64_t index = etcd.set("/test/key1", "42").index();

View File

@ -7,16 +7,15 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("setup") TEST_CASE("setup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
} }
TEST_CASE("add a new key") TEST_CASE("add a new key") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
etcd::Response resp = etcd.add("/test/key1", "42").get(); etcd::Response resp = etcd.add("/test/key1", "42").get();
@ -30,32 +29,35 @@ TEST_CASE("add a new key")
CHECK(0 < val.modified_index()); CHECK(0 < val.modified_index());
CHECK(1 == val.version()); CHECK(1 == val.version());
CHECK(0 < resp.index()); CHECK(0 < resp.index());
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd.add("/test/key1", "43").get().error_code()); // Key already exists CHECK(etcd::ERROR_KEY_ALREADY_EXISTS ==
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd.add("/test/key1", "42").get().error_code()); // Key already exists etcd.add("/test/key1", "43").get().error_code()); // Key already exists
CHECK("etcd-cpp-apiv3: key already exists" == etcd.add("/test/key1", "42").get().error_message()); CHECK(etcd::ERROR_KEY_ALREADY_EXISTS ==
etcd.add("/test/key1", "42").get().error_code()); // Key already exists
CHECK("etcd-cpp-apiv3: key already exists" ==
etcd.add("/test/key1", "42").get().error_message());
} }
TEST_CASE("read a value from etcd") TEST_CASE("read a value from etcd") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd::Response resp = etcd.get("/test/key1").get(); etcd::Response resp = etcd.get("/test/key1").get();
CHECK("get" == resp.action()); CHECK("get" == resp.action());
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
REQUIRE(0 == resp.error_code()); REQUIRE(0 == resp.error_code());
CHECK("42" == resp.value().as_string()); CHECK("42" == resp.value().as_string());
CHECK("" == etcd.get("/test").get().value().as_string()); // key points to a directory CHECK("" == etcd.get("/test").get().value().as_string()); // key points to a
// directory
} }
TEST_CASE("simplified read") TEST_CASE("simplified read") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
CHECK("42" == etcd.get("/test/key1").get().value().as_string()); CHECK("42" == etcd.get("/test/key1").get().value().as_string());
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.get("/test/key2").get().error_code()); // Key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
CHECK("" == etcd.get("/test/key2").get().value().as_string()); // Key not found etcd.get("/test/key2").get().error_code()); // Key not found
CHECK("" ==
etcd.get("/test/key2").get().value().as_string()); // Key not found
} }
TEST_CASE("modify a key") TEST_CASE("modify a key") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
// get // get
@ -68,7 +70,8 @@ TEST_CASE("modify a key")
resp = etcd.modify("/test/key1", "43").get(); resp = etcd.modify("/test/key1", "43").get();
REQUIRE(0 == resp.error_code()); // overwrite REQUIRE(0 == resp.error_code()); // overwrite
CHECK("update" == resp.action()); CHECK("update" == resp.action());
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.modify("/test/key2", "43").get().error_code()); // Key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.modify("/test/key2", "43").get().error_code()); // Key not found
CHECK("43" == etcd.modify("/test/key1", "42").get().prev_value().as_string()); CHECK("43" == etcd.modify("/test/key1", "42").get().prev_value().as_string());
// check previous // check previous
@ -77,8 +80,7 @@ TEST_CASE("modify a key")
CHECK("42" == resp.value().as_string()); CHECK("42" == resp.value().as_string());
} }
TEST_CASE("set a key") TEST_CASE("set a key") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd::Response resp = etcd.set("/test/key1", "43").get(); etcd::Response resp = etcd.set("/test/key1", "43").get();
REQUIRE(0 == resp.error_code()); // overwrite REQUIRE(0 == resp.error_code()); // overwrite
@ -97,8 +99,7 @@ TEST_CASE("set a key")
CHECK(0 < resp.value().lease()); CHECK(0 < resp.value().lease());
} }
TEST_CASE("atomic compare-and-swap") TEST_CASE("atomic compare-and-swap") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.set("/test/key1", "42").wait(); etcd.set("/test/key1", "42").wait();
@ -121,8 +122,7 @@ TEST_CASE("atomic compare-and-swap")
CHECK("etcd-cpp-apiv3: key not found" == res.error_message()); CHECK("etcd-cpp-apiv3: key not found" == res.error_message());
} }
TEST_CASE("delete a value") TEST_CASE("delete a value") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd::Response resp = etcd.rm("/test/key11111").get(); etcd::Response resp = etcd.rm("/test/key11111").get();
CHECK(!resp.is_ok()); CHECK(!resp.is_ok());
@ -151,8 +151,7 @@ TEST_CASE("delete a value")
CHECK("/test/key1" == resp.value().key()); CHECK("/test/key1" == resp.value().key());
} }
TEST_CASE("atomic compare-and-delete based on prevValue") TEST_CASE("atomic compare-and-delete based on prevValue") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.set("/test/key1", "42").wait(); etcd.set("/test/key1", "42").wait();
@ -167,8 +166,7 @@ TEST_CASE("atomic compare-and-delete based on prevValue")
CHECK("42" == res.prev_value().as_string()); CHECK("42" == res.prev_value().as_string());
} }
TEST_CASE("atomic compare-and-delete based on prevIndex") TEST_CASE("atomic compare-and-delete based on prevIndex") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
int64_t index = etcd.set("/test/key1", "42").get().index(); int64_t index = etcd.set("/test/key1", "42").get().index();
@ -183,8 +181,7 @@ TEST_CASE("atomic compare-and-delete based on prevIndex")
CHECK("42" == res.prev_value().as_string()); CHECK("42" == res.prev_value().as_string());
} }
TEST_CASE("deep atomic compare-and-swap") TEST_CASE("deep atomic compare-and-swap") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.set("/test/key1", "42").wait(); etcd.set("/test/key1", "42").wait();
@ -214,8 +211,7 @@ TEST_CASE("deep atomic compare-and-swap")
CHECK("etcd-cpp-apiv3: compare failed" == res.error_message()); CHECK("etcd-cpp-apiv3: compare failed" == res.error_message());
} }
TEST_CASE("using binary keys and values, raw char pointer doesn't work") TEST_CASE("using binary keys and values, raw char pointer doesn't work") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
{ {
@ -244,12 +240,13 @@ TEST_CASE("using binary keys and values, raw char pointer doesn't work")
} }
} }
TEST_CASE("using binary keys and values, std::string is ok for \\0") TEST_CASE("using binary keys and values, std::string is ok for \\0") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
{ {
etcd::Response resp = etcd.put(std::string("/test/key1\0xyz", 14), std::string("42\0foo", 6)).get(); etcd::Response resp =
etcd.put(std::string("/test/key1\0xyz", 14), std::string("42\0foo", 6))
.get();
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
} }
{ {
@ -267,8 +264,7 @@ TEST_CASE("using binary keys and values, std::string is ok for \\0")
} }
} }
TEST_CASE("list a directory") TEST_CASE("list a directory") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
CHECK(0 == etcd.ls("/test/new_dir").get().keys().size()); CHECK(0 == etcd.ls("/test/new_dir").get().keys().size());
@ -304,8 +300,7 @@ TEST_CASE("list a directory")
CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok()); CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok());
} }
TEST_CASE("list by range") TEST_CASE("list by range") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
CHECK(0 == etcd.ls("/test/new_dir").get().keys().size()); CHECK(0 == etcd.ls("/test/new_dir").get().keys().size());
@ -315,13 +310,15 @@ TEST_CASE("list by range")
etcd.set("/test/new_dir/key3", "value3").wait(); etcd.set("/test/new_dir/key3", "value3").wait();
etcd.set("/test/new_dir/key4", "value4").wait(); etcd.set("/test/new_dir/key4", "value4").wait();
etcd::Response resp1 = etcd.ls("/test/new_dir/key1", "/test/new_dir/key3").get(); etcd::Response resp1 =
etcd.ls("/test/new_dir/key1", "/test/new_dir/key3").get();
REQUIRE(resp1.is_ok()); REQUIRE(resp1.is_ok());
CHECK("get" == resp1.action()); CHECK("get" == resp1.action());
REQUIRE(2 == resp1.keys().size()); REQUIRE(2 == resp1.keys().size());
REQUIRE(2 == resp1.values().size()); REQUIRE(2 == resp1.values().size());
etcd::Response resp2 = etcd.ls("/test/new_dir/key1", "/test/new_dir/key4").get(); etcd::Response resp2 =
etcd.ls("/test/new_dir/key1", "/test/new_dir/key4").get();
REQUIRE(resp2.is_ok()); REQUIRE(resp2.is_ok());
CHECK("get" == resp2.action()); CHECK("get" == resp2.action());
REQUIRE(3 == resp2.keys().size()); REQUIRE(3 == resp2.keys().size());
@ -333,7 +330,10 @@ TEST_CASE("list by range")
REQUIRE(4 == resp3.keys().size()); REQUIRE(4 == resp3.keys().size());
REQUIRE(4 == resp3.values().size()); REQUIRE(4 == resp3.values().size());
etcd::Response resp4 = etcd.ls("/test/new_dir/key1", etcdv3::detail::string_plus_one("/test/new_dir/key")).get(); etcd::Response resp4 =
etcd.ls("/test/new_dir/key1",
etcdv3::detail::string_plus_one("/test/new_dir/key"))
.get();
REQUIRE(resp4.is_ok()); REQUIRE(resp4.is_ok());
CHECK("get" == resp4.action()); CHECK("get" == resp4.action());
REQUIRE(4 == resp4.keys().size()); REQUIRE(4 == resp4.keys().size());
@ -344,8 +344,7 @@ TEST_CASE("list by range")
CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok()); CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok());
} }
TEST_CASE("list by range, w/o values") TEST_CASE("list by range, w/o values") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
CHECK(0 == etcd.ls("/test/new_dir").get().keys().size()); CHECK(0 == etcd.ls("/test/new_dir").get().keys().size());
@ -355,14 +354,16 @@ TEST_CASE("list by range, w/o values")
etcd.set("/test/new_dir/key3", "value3").wait(); etcd.set("/test/new_dir/key3", "value3").wait();
etcd.set("/test/new_dir/key4", "value4").wait(); etcd.set("/test/new_dir/key4", "value4").wait();
etcd::Response resp1 = etcd.ls("/test/new_dir/key1", "/test/new_dir/key2").get(); etcd::Response resp1 =
etcd.ls("/test/new_dir/key1", "/test/new_dir/key2").get();
REQUIRE(resp1.is_ok()); REQUIRE(resp1.is_ok());
CHECK("get" == resp1.action()); CHECK("get" == resp1.action());
REQUIRE(1 == resp1.keys().size()); REQUIRE(1 == resp1.keys().size());
REQUIRE(1 == resp1.values().size()); REQUIRE(1 == resp1.values().size());
REQUIRE(resp1.values()[0].as_string() == "value1"); REQUIRE(resp1.values()[0].as_string() == "value1");
etcd::Response resp2 = etcd.keys("/test/new_dir/key1", "/test/new_dir/key2").get(); etcd::Response resp2 =
etcd.keys("/test/new_dir/key1", "/test/new_dir/key2").get();
REQUIRE(resp1.is_ok()); REQUIRE(resp1.is_ok());
CHECK("get" == resp2.action()); CHECK("get" == resp2.action());
REQUIRE(1 == resp2.keys().size()); REQUIRE(1 == resp2.keys().size());
@ -372,15 +373,15 @@ TEST_CASE("list by range, w/o values")
CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok()); CHECK(etcd.rmdir("/test/new_dir", true).get().is_ok());
} }
TEST_CASE("delete a directory") TEST_CASE("delete a directory") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.set("/test/new_dir/key1", "value1").wait(); etcd.set("/test/new_dir/key1", "value1").wait();
etcd.set("/test/new_dir/key2", "value2").wait(); etcd.set("/test/new_dir/key2", "value2").wait();
etcd.set("/test/new_dir/key3", "value3").wait(); etcd.set("/test/new_dir/key3", "value3").wait();
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.rmdir("/test/new_dir").get().error_code()); // key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.rmdir("/test/new_dir").get().error_code()); // key not found
etcd::Response resp = etcd.ls("/test/new_dir").get(); etcd::Response resp = etcd.ls("/test/new_dir").get();
resp = etcd.rmdir("/test/new_dir", true).get(); resp = etcd.rmdir("/test/new_dir", true).get();
@ -391,7 +392,6 @@ TEST_CASE("delete a directory")
CHECK("value1" == resp.value(0).as_string()); CHECK("value1" == resp.value(0).as_string());
CHECK("value2" == resp.value(1).as_string()); CHECK("value2" == resp.value(1).as_string());
resp = etcd.rmdir("/test/dirnotfound", true).get(); resp = etcd.rmdir("/test/dirnotfound", true).get();
CHECK(!resp.is_ok()); CHECK(!resp.is_ok());
CHECK(etcd::ERROR_KEY_NOT_FOUND == resp.error_code()); CHECK(etcd::ERROR_KEY_NOT_FOUND == resp.error_code());
@ -403,8 +403,7 @@ TEST_CASE("delete a directory")
CHECK("etcd-cpp-apiv3: key not found" == resp.error_message()); CHECK("etcd-cpp-apiv3: key not found" == resp.error_message());
} }
TEST_CASE("delete all keys with rmdir(\"\", true)") TEST_CASE("delete all keys with rmdir(\"\", true)") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("", true).wait(); etcd.rmdir("", true).wait();
@ -417,11 +416,11 @@ TEST_CASE("delete all keys with rmdir(\"\", true)")
CHECK(resp.values().size() == 3); CHECK(resp.values().size() == 3);
} }
TEST_CASE("delete by range") TEST_CASE("delete by range") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
CHECK(etcd::ERROR_KEY_NOT_FOUND == etcd.rmdir("/test/new_dir").get().error_code()); // key not found CHECK(etcd::ERROR_KEY_NOT_FOUND ==
etcd.rmdir("/test/new_dir").get().error_code()); // key not found
etcd::Response resp = etcd.ls("/test/new_dir").get(); etcd::Response resp = etcd.ls("/test/new_dir").get();
etcd.set("/test/new_dir/key1", "value1").wait(); etcd.set("/test/new_dir/key1", "value1").wait();
@ -438,8 +437,7 @@ TEST_CASE("delete by range")
CHECK("value2" == resp.value(1).as_string()); CHECK("value2" == resp.value(1).as_string());
} }
TEST_CASE("wait for a value change") TEST_CASE("wait for a value change") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.set("/test/key1", "42").wait(); etcd.set("/test/key1", "42").wait();
@ -456,8 +454,7 @@ TEST_CASE("wait for a value change")
CHECK("42" == res.get().prev_value().as_string()); CHECK("42" == res.get().prev_value().as_string());
} }
TEST_CASE("wait for a directory change") TEST_CASE("wait for a directory change") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
pplx::task<etcd::Response> res = etcd.watch("/test", true); pplx::task<etcd::Response> res = etcd.watch("/test", true);
@ -483,8 +480,7 @@ TEST_CASE("wait for a directory change")
CHECK("45" == res2.get().value().as_string()); CHECK("45" == res2.get().value().as_string());
} }
TEST_CASE("watch changes in the past") TEST_CASE("watch changes in the past") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
REQUIRE(0 == etcd.rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd.rmdir("/test", true).get().error_code());
int64_t index = etcd.set("/test/key1", "42").get().index(); int64_t index = etcd.set("/test/key1", "42").get().index();
@ -510,8 +506,7 @@ TEST_CASE("watch changes in the past")
CHECK("45" == res.value().as_string()); CHECK("45" == res.value().as_string());
} }
TEST_CASE("watch range changes in the past") TEST_CASE("watch range changes in the past") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
REQUIRE(0 == etcd.rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd.rmdir("/test", true).get().error_code());
int64_t index = etcd.set("/test/key1", "42").get().index(); int64_t index = etcd.set("/test/key1", "42").get().index();
@ -542,7 +537,8 @@ TEST_CASE("watch multiple keys and use promise") {
int64_t start_index = etcd.set("/test/key1", "value1").get().index(); int64_t start_index = etcd.set("/test/key1", "value1").get().index();
etcd.set("/test/key2", "value2").get(); etcd.set("/test/key2", "value2").get();
pplx::task<size_t> res = etcd.watch("/test", start_index, true) pplx::task<size_t> res =
etcd.watch("/test", start_index, true)
.then([](pplx::task<etcd::Response> const& resp_task) -> size_t { .then([](pplx::task<etcd::Response> const& resp_task) -> size_t {
auto const& resp = resp_task.get(); auto const& resp = resp_task.get();
return resp.events().size(); return resp.events().size();
@ -551,8 +547,7 @@ TEST_CASE("watch multiple keys and use promise") {
CHECK(2 == event_size); CHECK(2 == event_size);
} }
TEST_CASE("lease grant") TEST_CASE("lease grant") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd::Response res = etcd.leasegrant(60).get(); etcd::Response res = etcd.leasegrant(60).get();
REQUIRE(res.is_ok()); REQUIRE(res.is_ok());
@ -627,8 +622,7 @@ TEST_CASE("lease grant")
CHECK("etcdserver: requested lease not found" == res.error_message()); CHECK("etcdserver: requested lease not found" == res.error_message());
} }
TEST_CASE("lease list") TEST_CASE("lease list") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd::Response res = etcd.leasegrant(60).get(); etcd::Response res = etcd.leasegrant(60).get();
REQUIRE(res.is_ok()); REQUIRE(res.is_ok());
@ -647,8 +641,7 @@ TEST_CASE("lease list")
} }
} }
TEST_CASE("cleanup") TEST_CASE("cleanup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
REQUIRE(0 == etcd.rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd.rmdir("/test", true).get().error_code());
} }

View File

@ -12,10 +12,10 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("fork: set in child and get from self") TEST_CASE("fork: set in child and get from self") {
{
pid_t pid = fork(); pid_t pid = fork();
REQUIRE(pid >= 0); REQUIRE(pid >= 0);

View File

@ -10,8 +10,8 @@
#include "etcd/SyncClient.hpp" #include "etcd/SyncClient.hpp"
#include "etcd/Value.hpp" #include "etcd/Value.hpp"
static std::string etcd_uri = etcdv3::detail::resolve_etcd_endpoints( static std::string etcd_uri =
"http://127.0.0.1:2379,http://127.0.0.1:2479,http://127.0.0.1:2579"); etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("keepalive revoke and check if alive") { TEST_CASE("keepalive revoke and check if alive") {
etcd::Client etcd(etcd_uri); etcd::Client etcd(etcd_uri);
@ -33,3 +33,30 @@ TEST_CASE("keepalive revoke and check if alive") {
// expect keep_alive->Check() to throw exception // expect keep_alive->Check() to throw exception
REQUIRE_THROWS(keepalive->Check()); REQUIRE_THROWS(keepalive->Check());
} }
TEST_CASE("keepalive won't expire") {
etcd::Client etcd(etcd_uri);
const int64_t ttl = 3;
const std::string key = "key";
const std::string meta_str = "meta ....";
etcd::Response resp = etcd.leasegrant(ttl).get();
auto lease_id = resp.value().lease();
etcd.add(key, meta_str, lease_id);
std::function<void(std::exception_ptr)> handler =
[](std::exception_ptr eptr) {
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch (const std::runtime_error& e) {
std::cerr << "Connection failure \"" << e.what() << "\"\n";
} catch (const std::out_of_range& e) {
std::cerr << "Lease expiry \"" << e.what() << "\"\n";
}
};
etcd::KeepAlive keepalive(etcd, handler, ttl, lease_id);
std::this_thread::sleep_for(std::chrono::seconds(5));
}

View File

@ -10,10 +10,10 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("lock and unlock") TEST_CASE("lock and unlock") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
// lock // lock
@ -29,8 +29,7 @@ TEST_CASE("lock and unlock")
REQUIRE(0 == resp2.error_code()); REQUIRE(0 == resp2.error_code());
} }
TEST_CASE("double lock will fail") TEST_CASE("double lock will fail") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
// lock // lock
@ -62,7 +61,8 @@ TEST_CASE("double lock will fail")
REQUIRE(0 == resp3.error_code()); REQUIRE(0 == resp3.error_code());
// create a duration // create a duration
// using a duration longer than default lease TTL for lock (see: DEFAULT_LEASE_TTL_FOR_LOCK) // using a duration longer than default lease TTL for lock (see:
// DEFAULT_LEASE_TTL_FOR_LOCK)
std::this_thread::sleep_for(std::chrono::seconds(15)); std::this_thread::sleep_for(std::chrono::seconds(15));
// unlock the first lock // unlock the first lock
@ -84,8 +84,7 @@ TEST_CASE("double lock will fail")
REQUIRE(0 == resp5.error_code()); REQUIRE(0 == resp5.error_code());
} }
TEST_CASE("lock could be timeout") TEST_CASE("lock could be timeout") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
// setup the timeout // setup the timeout
@ -113,13 +112,13 @@ TEST_CASE("lock could be timeout")
REQUIRE(0 == resp5.error_code()); REQUIRE(0 == resp5.error_code());
} }
TEST_CASE("lock using lease") TEST_CASE("lock using lease") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
bool failed = false; bool failed = false;
std::function<void (std::exception_ptr)> handler = [&failed](std::exception_ptr eptr) { std::function<void(std::exception_ptr)> handler =
[&failed](std::exception_ptr eptr) {
try { try {
if (eptr) { if (eptr) {
std::rethrow_exception(eptr); std::rethrow_exception(eptr);
@ -197,24 +196,30 @@ TEST_CASE("lock using lease")
} }
} }
TEST_CASE("concurrent lock & unlock") TEST_CASE("concurrent lock & unlock") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
std::string const lock_key = "/test/test_key"; std::string const lock_key = "/test/test_key";
constexpr size_t trials = 192; constexpr size_t trials = 192;
std::function<void(std::string const &, const size_t)> locker = [&etcd](std::string const &key, const size_t index) { std::function<void(std::string const&, const size_t)> locker =
std::cout << "start lock for " << key << ", index is " << index << std::endl; [&etcd](std::string const& key, const size_t index) {
std::cout << "start lock for " << key << ", index is " << index
<< std::endl;
auto resp = etcd.lock(key).get(); auto resp = etcd.lock(key).get();
std::cout << "lock for " << index << " is ok, starts sleeping: ..." << resp.error_message() << std::endl << std::flush; std::cout << "lock for " << index << " is ok, starts sleeping: ..."
<< resp.error_message() << std::endl
<< std::flush;
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
std::srand(index); std::srand(index);
size_t time_to_sleep = 1; size_t time_to_sleep = 1;
std::this_thread::sleep_for(std::chrono::seconds(time_to_sleep)); std::this_thread::sleep_for(std::chrono::seconds(time_to_sleep));
std::cout << "lock for " << index << " resumes from sleep: ..." << resp.error_message() << std::endl << std::flush; std::cout << "lock for " << index << " resumes from sleep: ..."
<< resp.error_message() << std::endl
<< std::flush;
REQUIRE(etcd.unlock(resp.lock_key()).get().is_ok()); REQUIRE(etcd.unlock(resp.lock_key()).get().is_ok());
std::cout << "thread " << index << " been unlocked" << std::endl << std::flush; std::cout << "thread " << index << " been unlocked" << std::endl
<< std::flush;
}; };
std::vector<std::thread> locks(trials); std::vector<std::thread> locks(trials);
@ -233,12 +238,15 @@ TEST_CASE("concurrent lock & unlock with a put in between") {
constexpr size_t trials = 128; constexpr size_t trials = 128;
std::function<void(std::string const &, const size_t)> locker = [&etcd](std::string const &key, const size_t index) { std::function<void(std::string const&, const size_t)> locker =
[&etcd](std::string const& key, const size_t index) {
std::cout << "start lock for " << index << std::endl; std::cout << "start lock for " << index << std::endl;
auto resp = etcd.lock(key, true).get(); auto resp = etcd.lock(key, true).get();
std::cout << "lock for " << index << " is ok, start put and unlock: ..." << resp.error_message() << std::endl; std::cout << "lock for " << index << " is ok, start put and unlock: ..."
<< resp.error_message() << std::endl;
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
auto put_resp = etcd.put("/test/test_put", "hello" + std::to_string(index)).get(); auto put_resp =
etcd.put("/test/test_put", "hello" + std::to_string(index)).get();
REQUIRE(put_resp.is_ok()); REQUIRE(put_resp.is_ok());
REQUIRE(etcd.unlock(resp.lock_key()).get().is_ok()); REQUIRE(etcd.unlock(resp.lock_key()).get().is_ok());
std::cout << "thread " << index << " been unlocked" << std::endl; std::cout << "thread " << index << " been unlocked" << std::endl;

View File

@ -6,16 +6,14 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
class DistributedLock { class DistributedLock {
public: public:
DistributedLock(const std::string &lock_name, DistributedLock(const std::string& lock_name, uint timeout = 0);
uint timeout = 0);
~DistributedLock() noexcept; ~DistributedLock() noexcept;
inline bool lock_acquired() { inline bool lock_acquired() { return _acquired; }
return _acquired;
}
private: private:
bool _acquired = false; bool _acquired = false;
@ -23,8 +21,7 @@ private:
std::unique_ptr<::etcd::Client> _etcd_client; std::unique_ptr<::etcd::Client> _etcd_client;
}; };
DistributedLock::DistributedLock(const std::string &lock_name, DistributedLock::DistributedLock(const std::string& lock_name, uint timeout) {
uint timeout) {
_etcd_client = std::unique_ptr<etcd::Client>(new etcd::Client(etcd_url)); _etcd_client = std::unique_ptr<etcd::Client>(new etcd::Client(etcd_url));
try { try {
@ -35,12 +32,14 @@ DistributedLock::DistributedLock(const std::string &lock_name,
_acquired = true; _acquired = true;
} }
} else { } else {
std::future<etcd::Response> future = std::async(std::launch::async, [&]() { std::future<etcd::Response> future =
std::async(std::launch::async, [&]() {
etcd::Response resp = _etcd_client->lock(lock_name).get(); etcd::Response resp = _etcd_client->lock(lock_name).get();
return resp; return resp;
}); });
std::future_status status = future.wait_for(std::chrono::seconds(timeout)); std::future_status status =
future.wait_for(std::chrono::seconds(timeout));
if (status == std::future_status::ready) { if (status == std::future_status::ready) {
auto resp = future.get(); auto resp = future.get();
if (resp.is_ok()) { if (resp.is_ok()) {
@ -48,7 +47,8 @@ DistributedLock::DistributedLock(const std::string &lock_name,
_acquired = true; _acquired = true;
} }
} else if (status == std::future_status::timeout) { } else if (status == std::future_status::timeout) {
std::cerr << "failed to acquire distributed because of lock timeout" << std::endl; std::cerr << "failed to acquire distributed because of lock timeout"
<< std::endl;
} else { } else {
std::cerr << "failed to acquire distributed lock" << std::endl; std::cerr << "failed to acquire distributed lock" << std::endl;
} }

View File

@ -8,14 +8,12 @@
#include "etcd/KeepAlive.hpp" #include "etcd/KeepAlive.hpp"
#include "etcd/Watcher.hpp" #include "etcd/Watcher.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
static std::atomic_int watcher_called; static std::atomic_int watcher_called;
void print_response(etcd::Response const & resp) void print_response(etcd::Response const& resp) { watcher_called.fetch_add(1); }
{
watcher_called.fetch_add(1);
}
/** /**
* @brief emulate the behavior of creating watcher many times: * @brief emulate the behavior of creating watcher many times:
@ -24,7 +22,8 @@ void print_response(etcd::Response const & resp)
* 2. change a value * 2. change a value
* 3. cancel the watcher * 3. cancel the watcher
*/ */
void watch_once(etcd::Client & client, std::unique_ptr<etcd::Watcher> &watcher, const size_t round) { void watch_once(etcd::Client& client, std::unique_ptr<etcd::Watcher>& watcher,
const size_t round) {
const std::string my_prefix = "/test"; const std::string my_prefix = "/test";
const std::string my_key = my_prefix + "/foo"; const std::string my_key = my_prefix + "/foo";
watcher.reset(new etcd::Watcher(client, my_prefix, print_response, true)); watcher.reset(new etcd::Watcher(client, my_prefix, print_response, true));
@ -42,19 +41,20 @@ void watch_once(etcd::Client & client, std::unique_ptr<etcd::Watcher> &watcher,
watcher->Cancel(); watcher->Cancel();
} }
TEST_CASE("watch shouldn't leak memory") TEST_CASE("watch shouldn't leak memory") {
{
watcher_called.store(0); watcher_called.store(0);
// issue some changes to see if the watcher works // issue some changes to see if the watcher works
etcd::Client client(etcd_url); etcd::Client client(etcd_url);
std::unique_ptr<etcd::Watcher> watcher; std::unique_ptr<etcd::Watcher> watcher;
for (int round = 0; round < 10 /* update this value to make it run for longer */; ++round) { for (int round = 0;
round < 10 /* update this value to make it run for longer */; ++round) {
if (round % 50 == 0) { if (round % 50 == 0) {
std::cout << "starting round " << round << std::endl; std::cout << "starting round " << round << std::endl;
} }
watch_once(client, watcher, round); watch_once(client, watcher, round);
} }
std::cout << "watcher been called for " << watcher_called.load() << " times" << std::endl; std::cout << "watcher been called for " << watcher_called.load() << " times"
<< std::endl;
} }

View File

@ -8,27 +8,28 @@
#include "etcd/SyncClient.hpp" #include "etcd/SyncClient.hpp"
#include "etcd/Watcher.hpp" #include "etcd/Watcher.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
static int watcher_called = 0; static int watcher_called = 0;
void print_response(etcd::Response const & resp) void print_response(etcd::Response const& resp) {
{
++watcher_called; ++watcher_called;
std::cout << "print response called" << std::endl; std::cout << "print response called" << std::endl;
if (resp.error_code()) { if (resp.error_code()) {
std::cout << resp.error_code() << ": " << resp.error_message() << std::endl; std::cout << resp.error_code() << ": " << resp.error_message() << std::endl;
} } else {
else {
std::cout << resp.action() << " " << resp.value().as_string() << std::endl; std::cout << resp.action() << " " << resp.value().as_string() << std::endl;
std::cout << "Previous value: " << resp.prev_value().as_string() << std::endl; std::cout << "Previous value: " << resp.prev_value().as_string()
<< std::endl;
std::cout << "Events size: " << resp.events().size() << std::endl; std::cout << "Events size: " << resp.events().size() << std::endl;
for (auto const& ev : resp.events()) { for (auto const& ev : resp.events()) {
std::cout << "Value change in events: " << static_cast<int>(ev.event_type()) std::cout << "Value change in events: "
<< ", prev kv = " << ev.prev_kv().key() << " -> " << ev.prev_kv().as_string() << static_cast<int>(ev.event_type())
<< ", kv = " << ev.kv().key() << " -> " << ev.kv().as_string() << ", prev kv = " << ev.prev_kv().key() << " -> "
<< std::endl; << ev.prev_kv().as_string() << ", kv = " << ev.kv().key()
<< " -> " << ev.kv().as_string() << std::endl;
} }
} }
} }
@ -48,8 +49,7 @@ void wait_for_connection(std::string endpoints) {
} }
} }
void initialize_watcher(const std::string& endpoints, void initialize_watcher(const std::string& endpoints, const std::string& prefix,
const std::string& prefix,
std::function<void(etcd::Response)> callback, std::function<void(etcd::Response)> callback,
std::shared_ptr<etcd::Watcher>& watcher) { std::shared_ptr<etcd::Watcher>& watcher) {
// wait until the endpoints turn to be available // wait until the endpoints turn to be available
@ -64,18 +64,19 @@ void initialize_watcher(const std::string& endpoints,
watcher.reset(new etcd::Watcher(client, prefix, callback, true)); watcher.reset(new etcd::Watcher(client, prefix, callback, true));
// Note that lambda requires `mutable`qualifier. // Note that lambda requires `mutable`qualifier.
watcher->Wait([endpoints, prefix, callback, watcher->Wait(
[endpoints, prefix, callback,
/* By reference for renewing */ &watcher](bool cancelled) mutable { /* By reference for renewing */ &watcher](bool cancelled) mutable {
if (cancelled) { if (cancelled) {
std::cout << "watcher's reconnect loop stopped as been cancelled" << std::endl; std::cout << "watcher's reconnect loop stopped as been cancelled"
<< std::endl;
return; return;
} }
initialize_watcher(endpoints, prefix, callback, watcher); initialize_watcher(endpoints, prefix, callback, watcher);
}); });
} }
TEST_CASE("watch should can be re-established") TEST_CASE("watch should can be re-established") {
{
const std::string my_prefix = "/test"; const std::string my_prefix = "/test";
// the watcher initialized in this way will auto re-connect to etcd // the watcher initialized in this way will auto re-connect to etcd
@ -86,8 +87,8 @@ TEST_CASE("watch should can be re-established")
for (int round = 0; round < 100000; ++round) { for (int round = 0; round < 100000; ++round) {
try { try {
etcd::Client client(etcd_url); etcd::Client client(etcd_url);
auto response = client.set( auto response =
my_prefix + "/foo", "bar-" + std::to_string(round)).get(); client.set(my_prefix + "/foo", "bar-" + std::to_string(round)).get();
} catch (...) { } catch (...) {
// pass // pass
} }
@ -102,8 +103,8 @@ TEST_CASE("watch should can be re-established")
for (int round = 10; round < 20; ++round) { for (int round = 10; round < 20; ++round) {
try { try {
etcd::Client client(etcd_url); etcd::Client client(etcd_url);
auto response = client.set( auto response =
my_prefix + "/foo", "bar-" + std::to_string(round)).get(); client.set(my_prefix + "/foo", "bar-" + std::to_string(round)).get();
} catch (...) { } catch (...) {
// pass // pass
} }

View File

@ -9,16 +9,15 @@ static std::string ca = "security-config/certs/ca.crt";
static std::string cert = "security-config/certs/etcd0.example.com.crt"; static std::string cert = "security-config/certs/etcd0.example.com.crt";
static std::string key = "security-config/private/etcd0.example.com.key"; static std::string key = "security-config/private/etcd0.example.com.key";
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("https://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("https://127.0.0.1:2379");
TEST_CASE("setup with auth") TEST_CASE("setup with auth") {
{
etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key); etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key);
etcd->rmdir("/test", true).wait(); etcd->rmdir("/test", true).wait();
} }
TEST_CASE("add a new key after authenticate") TEST_CASE("add a new key after authenticate") {
{
etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key); etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key);
etcd->rmdir("/test", true).wait(); etcd->rmdir("/test", true).wait();
etcd::Response resp = etcd->add("/test/key1", "42").get(); etcd::Response resp = etcd->add("/test/key1", "42").get();
@ -32,24 +31,28 @@ TEST_CASE("add a new key after authenticate")
CHECK(0 < val.modified_index()); CHECK(0 < val.modified_index());
CHECK(1 == val.version()); CHECK(1 == val.version());
CHECK(0 < resp.index()); CHECK(0 < resp.index());
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd->add("/test/key1", "43").get().error_code()); // Key already exists CHECK(
CHECK(etcd::ERROR_KEY_ALREADY_EXISTS == etcd->add("/test/key1", "42").get().error_code()); // Key already exists etcd::ERROR_KEY_ALREADY_EXISTS ==
CHECK("etcd-cpp-apiv3: key already exists" == etcd->add("/test/key1", "42").get().error_message()); etcd->add("/test/key1", "43").get().error_code()); // Key already exists
CHECK(
etcd::ERROR_KEY_ALREADY_EXISTS ==
etcd->add("/test/key1", "42").get().error_code()); // Key already exists
CHECK("etcd-cpp-apiv3: key already exists" ==
etcd->add("/test/key1", "42").get().error_message());
} }
TEST_CASE("read a value from etcd") TEST_CASE("read a value from etcd") {
{
etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key); etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key);
etcd::Response resp = etcd->get("/test/key1").get(); etcd::Response resp = etcd->get("/test/key1").get();
CHECK("get" == resp.action()); CHECK("get" == resp.action());
REQUIRE(resp.is_ok()); REQUIRE(resp.is_ok());
REQUIRE(0 == resp.error_code()); REQUIRE(0 == resp.error_code());
CHECK("42" == resp.value().as_string()); CHECK("42" == resp.value().as_string());
CHECK("" == etcd->get("/test").get().value().as_string()); // key points to a directory CHECK("" == etcd->get("/test").get().value().as_string()); // key points to a
// directory
} }
TEST_CASE("cleanup") TEST_CASE("cleanup") {
{
etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key); etcd::Client* etcd = etcd::Client::WithSSL(etcd_url, ca, cert, key);
REQUIRE(0 == etcd->rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd->rmdir("/test", true).get().error_code());
} }

View File

@ -8,16 +8,15 @@
#include "etcd/Client.hpp" #include "etcd/Client.hpp"
#include "etcd/v3/Transaction.hpp" #include "etcd/v3/Transaction.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
TEST_CASE("setup") TEST_CASE("setup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
} }
TEST_CASE("add a new key") TEST_CASE("add a new key") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
etcd.rmdir("/test", true).wait(); etcd.rmdir("/test", true).wait();
@ -52,10 +51,12 @@ TEST_CASE("add a new key")
// setup the conditions // setup the conditions
txn.reset_key("/test/x1"); txn.reset_key("/test/x1");
txn.init_compare("1", etcdv3::CompareResult::EQUAL, etcdv3::CompareTarget::VALUE); txn.init_compare("1", etcdv3::CompareResult::EQUAL,
etcdv3::CompareTarget::VALUE);
txn.reset_key("/test/x2"); txn.reset_key("/test/x2");
txn.init_compare("2", etcdv3::CompareResult::EQUAL, etcdv3::CompareTarget::VALUE); txn.init_compare("2", etcdv3::CompareResult::EQUAL,
etcdv3::CompareTarget::VALUE);
txn.setup_put("/test/x1", "111"); txn.setup_put("/test/x1", "111");
txn.setup_delete("/test/x2"); txn.setup_delete("/test/x2");
@ -83,8 +84,7 @@ TEST_CASE("add a new key")
} }
} }
TEST_CASE("cleanup") TEST_CASE("cleanup") {
{
etcd::Client etcd(etcd_url); etcd::Client etcd(etcd_url);
REQUIRE(0 == etcd.rmdir("/test", true).get().error_code()); REQUIRE(0 == etcd.rmdir("/test", true).get().error_code());
} }

View File

@ -4,41 +4,42 @@
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include "etcd/Watcher.hpp"
#include "etcd/SyncClient.hpp" #include "etcd/SyncClient.hpp"
#include "etcd/Watcher.hpp"
static const std::string etcd_url = etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379"); static const std::string etcd_url =
etcdv3::detail::resolve_etcd_endpoints("http://127.0.0.1:2379");
static int watcher_called = 0; static int watcher_called = 0;
void printResponse(etcd::Response const & resp) void printResponse(etcd::Response const& resp) {
{
if (resp.error_code()) { if (resp.error_code()) {
std::cout << "Watcher "<< resp.watch_id() std::cout << "Watcher " << resp.watch_id() << " fails with "
<< " fails with " << resp.error_code() << ": " << resp.error_message() << std::endl; << resp.error_code() << ": " << resp.error_message() << std::endl;
} } else {
else { std::cout << "Watcher " << resp.watch_id() << " responses with "
std::cout << "Watcher " << resp.watch_id() << resp.action() << " " << resp.value().as_string() << std::endl;
<< " responses with " << resp.action() << " " << resp.value().as_string() << std::endl; std::cout << "Previous value: " << resp.prev_value().as_string()
std::cout << "Previous value: " << resp.prev_value().as_string() << std::endl; << std::endl;
std::cout << "Events size: " << resp.events().size() << std::endl; std::cout << "Events size: " << resp.events().size() << std::endl;
for (auto const& ev : resp.events()) { for (auto const& ev : resp.events()) {
if (ev.prev_kv().key().find("/leader") == 0 || ev.kv().key().find("/leader") == 0) { if (ev.prev_kv().key().find("/leader") == 0 ||
ev.kv().key().find("/leader") == 0) {
return; return;
} }
std::cout << "Value change in events: " << static_cast<int>(ev.event_type()) std::cout << "Value change in events: "
<< ", prev kv = " << ev.prev_kv().key() << " -> " << ev.prev_kv().as_string() << static_cast<int>(ev.event_type())
<< ", kv = " << ev.kv().key() << " -> " << ev.kv().as_string() << ", prev kv = " << ev.prev_kv().key() << " -> "
<< std::endl; << ev.prev_kv().as_string() << ", kv = " << ev.kv().key()
<< " -> " << ev.kv().as_string() << std::endl;
} }
} }
std::cout << "print response called" << std::endl; std::cout << "print response called" << std::endl;
++watcher_called; ++watcher_called;
} }
TEST_CASE("create watcher") TEST_CASE("create watcher") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
@ -55,8 +56,7 @@ TEST_CASE("create watcher")
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
} }
TEST_CASE("watch with correct prefix") TEST_CASE("watch with correct prefix") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
@ -92,8 +92,7 @@ TEST_CASE("watch with correct prefix")
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
} }
TEST_CASE("create watcher with cancel") TEST_CASE("create watcher with cancel") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
@ -115,8 +114,7 @@ TEST_CASE("create watcher with cancel")
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
} }
TEST_CASE("create watcher on ranges with cancel") TEST_CASE("create watcher on ranges with cancel") {
{
etcd::SyncClient etcd(etcd_url); etcd::SyncClient etcd(etcd_url);
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
@ -138,29 +136,24 @@ TEST_CASE("create watcher on ranges with cancel")
etcd.rmdir("/test", true); etcd.rmdir("/test", true);
} }
TEST_CASE("watch should exit normally") TEST_CASE("watch should exit normally") {
{
// cancel immediately after start watch. // cancel immediately after start watch.
etcd::Watcher watcher(etcd_url, "/test", printResponse, true); etcd::Watcher watcher(etcd_url, "/test", printResponse, true);
watcher.Cancel(); watcher.Cancel();
} }
TEST_CASE("watch should can be cancelled repeatedly") TEST_CASE("watch should can be cancelled repeatedly") {
{
etcd::Watcher watcher(etcd_url, "/test", printResponse, true); etcd::Watcher watcher(etcd_url, "/test", printResponse, true);
std::vector<std::thread> threads(10); std::vector<std::thread> threads(10);
for (size_t i = 0; i < 10; ++i) { for (size_t i = 0; i < 10; ++i) {
threads[i] = std::thread([&]() { threads[i] = std::thread([&]() { watcher.Cancel(); });
watcher.Cancel();
});
} }
for (size_t i = 0; i < 10; ++i) { for (size_t i = 0; i < 10; ++i) {
threads[i].join(); threads[i].join();
} }
} }
TEST_CASE("watch changes on the same key (#212)") TEST_CASE("watch changes on the same key (#212)") {
{
std::string key_watch = "key watch"; std::string key_watch = "key watch";
etcd::SyncClient client(etcd_url); etcd::SyncClient client(etcd_url);
client.put(key_watch, "inittt"); client.put(key_watch, "inittt");
@ -180,21 +173,18 @@ TEST_CASE("watch changes on the same key (#212)")
} }
}; };
auto wait_cb = [&](bool) {}; auto wait_cb = [&](bool) {};
etcd::Watcher w(client, key_watch, current_index, etcd::Watcher w(client, key_watch, current_index, std::move(internal_cb),
std::move(internal_cb), std::move(wait_cb), false);
std::move(wait_cb),
false);
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
for (int i = 0; i < 10; ) { for (int i = 0; i < 10; ++i) {
std::string value = "watch_" + std::to_string(i++); std::string value = "watch_" + std::to_string(i);
client.put(key_watch, value); client.put(key_watch, value);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
} }
} }
TEST_CASE("create two watcher") TEST_CASE("create two watcher") {
{
etcd::Watcher w1(etcd_url, "/test", printResponse, true); etcd::Watcher w1(etcd_url, "/test", printResponse, true);
etcd::Watcher w2(etcd_url, "/test", printResponse, true); etcd::Watcher w2(etcd_url, "/test", printResponse, true);