diff --git a/.build.osx.sh b/.build.osx.sh index b60be7ac1..196aa8260 100644 --- a/.build.osx.sh +++ b/.build.osx.sh @@ -22,7 +22,7 @@ configure_environment() { install_libuv() { if brew ls --versions libuv > /dev/null; then if ! brew outdated libuv; then - brew upgrade --cleanup libuv + brew upgrade libuv fi else brew install libuv @@ -32,7 +32,7 @@ install_libuv() { install_openssl() { if brew ls --versions openssl > /dev/null; then if ! brew outdated openssl; then - brew upgrade --cleanup openssl + brew upgrade openssl fi else brew install openssl diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf57863b..997617b72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,20 @@ +2.12.0 +=========== + +Features +-------- +[CPP-751] Call host listener callback for the initial set of hosts + +Bug Fixes +-------- +[CPP-755] UDT metadata not being properly populated/updated + +Other +-------- +[CPP-705] Deprecate DC-aware multi-DC settings (`used_hosts_per_remote_dc` + and `allowRemoteDCsForLocalConsistencyLevel `) +[CPP-720] Streamline custom allocator + 2.11.0 =========== diff --git a/appveyor.ps1 b/appveyor.ps1 index 19fa79937..72c6022ba 100644 --- a/appveyor.ps1 +++ b/appveyor.ps1 @@ -342,7 +342,7 @@ add_dependencies(`${PROJECT_NAME} `${LIBUV_LIBRARY_NAME}) $cmakelists_contents | Out-File -FilePath "CMakeLists.txt" -Encoding Utf8 -Force Write-Host "Configuring libuv" - cmake -G "$($cmake_generator)" -DBUILD_SHARED_LIBS=On "-DLIBUV_VERSION=$($Env:LIBUV_VERSION)" "-DLIBUV_INSTALL_PREFIX=$($Env:LIBUV_ROOT_DIR)" + cmake -G "$($cmake_generator)" -DBUILD_SHARED_LIBS=On "-DLIBUV_VERSION=$($Env:LIBUV_VERSION)" "-DLIBUV_INSTALL_PREFIX=$($Env:LIBUV_ROOT_DIR)" . If ($LastExitCode -ne 0) { If (Test-Path -Path "build/CMakeFiles/CMakeOutput.log") { Push-AppveyorArtifact "build/CMakeFiles/CMakeOutput.log" -DeploymentName "libuv Output Log" @@ -395,7 +395,7 @@ add_dependencies(`${PROJECT_NAME} `${OPENSSL_LIBRARY_NAME}) if ("$_" -Like "shared") { $shared_libs = "On" } - cmake -G "$($cmake_generator)" "-DBUILD_SHARED_LIBS=$($shared_libs)" "-DOPENSSL_VERSION=$($Env:OPENSSL_VERSION)" "-DOPENSSL_INSTALL_PREFIX=$($Env:OPENSSL_BASE_DIR)/$_" + cmake -G "$($cmake_generator)" "-DBUILD_SHARED_LIBS=$($shared_libs)" "-DOPENSSL_VERSION=$($Env:OPENSSL_VERSION)" "-DOPENSSL_INSTALL_PREFIX=$($Env:OPENSSL_BASE_DIR)/$_" . If ($LastExitCode -ne 0) { If (Test-Path -Path "build/CMakeFiles/CMakeOutput.log") { Push-AppveyorArtifact "build/CMakeFiles/CMakeOutput.log" -DeploymentName "OpenSSL Output Log" @@ -476,7 +476,7 @@ add_dependencies(`${PROJECT_NAME} `${BOOST_LIBRARY_NAME}) $cmakelists_contents | Out-File -FilePath "CMakeLists.txt" -Encoding Utf8 -Force Write-Host "Configuring Boost" - cmake -G "$($cmake_generator)" "-DBOOST_VERSION=$($Env:BOOST_VERSION)" "-DBOOST_INSTALL_PREFIX=$($Env:BOOST_ROOT)" + cmake -G "$($cmake_generator)" "-DBOOST_VERSION=$($Env:BOOST_VERSION)" "-DBOOST_INSTALL_PREFIX=$($Env:BOOST_ROOT)" . If ($LastExitCode -ne 0) { If (Test-Path -Path "build/CMakeFiles/CMakeOutput.log") { Push-AppveyorArtifact "build/CMakeFiles/CMakeOutput.log" -DeploymentName "Boost Output Log" @@ -524,7 +524,7 @@ add_dependencies(`${PROJECT_NAME} `${LIBSSH2_LIBRARY_NAME}) $cmakelists_contents | Out-File -FilePath "CMakeLists.txt" -Encoding Utf8 -Force Write-Host "Configuring libssh2" - cmake -G "$($cmake_generator)" "-DLIBSSH2_VERSION=$($Env:LIBSSH2_VERSION)" "-DLIBSSH2_INSTALL_PREFIX=$($Env:LIBSSH2_ROOT_DIR)" + cmake -G "$($cmake_generator)" "-DLIBSSH2_VERSION=$($Env:LIBSSH2_VERSION)" "-DLIBSSH2_INSTALL_PREFIX=$($Env:LIBSSH2_ROOT_DIR)" . If ($LastExitCode -ne 0) { If (Test-Path -Path "build/CMakeFiles/CMakeOutput.log") { Push-AppveyorArtifact "build/CMakeFiles/CMakeOutput.log" -DeploymentName "libssh2 Output Log" diff --git a/appveyor.yml b/appveyor.yml index 7ed4b1f23..68e888c4a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -39,11 +39,11 @@ environment: APPVEYOR_BUILD_WORKER_CLOUD: gce APPVEYOR_IGNORE_COMMIT_FILTERING_ON_TAG: true DRIVER_TYPE: CASS - BOOST_VERSION: 1.68.0 - LIBSSH2_VERSION: 1.8.0 - LIBUV_VERSION: 1.24.0 - OPENSSL_1_0_VERSION: 1.0.2q - OPENSSL_1_1_VERSION: 1.1.1a + BOOST_VERSION: 1.69.0 + LIBSSH2_VERSION: 1.8.2 + LIBUV_VERSION: 1.28.0 + OPENSSL_1_0_VERSION: 1.0.2r + OPENSSL_1_1_VERSION: 1.1.1b matrix: - CMAKE_GENERATOR: Visual Studio 10 2010 OPENSSL_MAJOR_MINOR: 1.0 diff --git a/build.yaml b/build.yaml index 42d1e6a38..1af93b6d9 100644 --- a/build.yaml +++ b/build.yaml @@ -14,12 +14,12 @@ architecture: os: - ubuntu/bionic64/cpp - ubuntu/trusty64/cpp - - ubuntu/xenial64 - - centos/6-64 - - centos/7-64 + - ubuntu/xenial64/cpp + - centos/6-64/cpp + - centos/7-64/cpp - osx/high-sierra env: - LIBUV_VERSION: 1.24.0 + LIBUV_VERSION: 1.28.0 build: - script: | . .build.sh diff --git a/cmake/modules/ExternalProject-Boost.cmake b/cmake/modules/ExternalProject-Boost.cmake index b3d2ba3fa..b9b53d8fd 100644 --- a/cmake/modules/ExternalProject-Boost.cmake +++ b/cmake/modules/ExternalProject-Boost.cmake @@ -23,7 +23,7 @@ if(NOT BOOST_INSTALL_PREFIX) endif() option(BOOST_VERSION "Boost version to build and install") if(NOT BOOST_VERSION) - set(BOOST_VERSION "1.68.0") + set(BOOST_VERSION "1.69.0") endif() set(BOOST_VERSION ${BOOST_VERSION} CACHE STRING "Boost version to build and install" FORCE) diff --git a/cmake/modules/ExternalProject-OpenSSL.cmake b/cmake/modules/ExternalProject-OpenSSL.cmake index 7b357e57a..d86a7de1d 100644 --- a/cmake/modules/ExternalProject-OpenSSL.cmake +++ b/cmake/modules/ExternalProject-OpenSSL.cmake @@ -21,8 +21,8 @@ endif() # OpenSSL related CMake options option(OPENSSL_VERSION "OpenSSL version to build and install") if(NOT OPENSSL_VERSION) - # TODO: Should we default to OpenSSL 1.1 (e.g. 1.1.1a)? - set(OPENSSL_VERSION "1.0.2q") + # TODO: Should we default to OpenSSL 1.1 (e.g. 1.1.1b)? + set(OPENSSL_VERSION "1.0.2r") endif() option(OPENSSL_INSTALL_PREFIX "OpenSSL installation prefix location") if(CASS_USE_ZLIB) diff --git a/cmake/modules/ExternalProject-libssh2.cmake b/cmake/modules/ExternalProject-libssh2.cmake index 3b9b1e531..4bc3493c8 100644 --- a/cmake/modules/ExternalProject-libssh2.cmake +++ b/cmake/modules/ExternalProject-libssh2.cmake @@ -22,7 +22,7 @@ if(NOT LIBSSH2_INSTALL_PREFIX) endif() option(LIBSSH2_VERSION "libssh2 version to build and install") if(NOT LIBSSH2_VERSION) - set(LIBSSH2_VERSION "1.8.0") + set(LIBSSH2_VERSION "1.8.2") endif() set(LIBSSH2_VERSION ${LIBSSH2_VERSION} CACHE STRING "libssh2 version to build and install" FORCE) diff --git a/cmake/modules/ExternalProject-libuv.cmake b/cmake/modules/ExternalProject-libuv.cmake index 8d8e55308..71dbc13cf 100644 --- a/cmake/modules/ExternalProject-libuv.cmake +++ b/cmake/modules/ExternalProject-libuv.cmake @@ -22,7 +22,7 @@ if(NOT LIBUV_INSTALL_PREFIX) endif() option(LIBUV_VERSION "libuv version to build and install") if(NOT LIBUV_VERSION) - set(LIBUV_VERSION "1.24.0") + set(LIBUV_VERSION "1.28.0") endif() set(LIBUV_VERSION ${LIBUV_VERSION} CACHE STRING "libuv version to build and install" FORCE) diff --git a/docs.yaml b/docs.yaml index 6ef6bc09c..47c3f2ab1 100644 --- a/docs.yaml +++ b/docs.yaml @@ -56,6 +56,8 @@ rules: use_path_nav_files_only: true versions: + - name: "2.12" + ref: 2.12.0 - name: "2.11" ref: 2.11.0 - name: "2.10" diff --git a/examples/host_listener/host_listener.c b/examples/host_listener/host_listener.c index 3c8b3e617..6186a001c 100644 --- a/examples/host_listener/host_listener.c +++ b/examples/host_listener/host_listener.c @@ -72,13 +72,13 @@ void on_host_listener(CassHostListenerEvent event, CassInet inet, void* data) { cass_inet_string(inet, address); if (event == CASS_HOST_LISTENER_EVENT_ADD) { printf("Host %s has been ADDED\n", address); - } else if (event == CASS_HOST_LISTENER_EVENT_REMOVE) { + } else if (event == CASS_HOST_LISTENER_EVENT_REMOVE) { printf("Host %s has been REMOVED\n", address); - } else if (event == CASS_HOST_LISTENER_EVENT_UP) { + } else if (event == CASS_HOST_LISTENER_EVENT_UP) { printf("Host %s is UP\n", address); - } else if (event == CASS_HOST_LISTENER_EVENT_DOWN) { + } else if (event == CASS_HOST_LISTENER_EVENT_DOWN) { printf("Host %s is DOWN\n", address); - } + } } int main(int argc, char* argv[]) { diff --git a/gtests/src/integration/integration.cpp b/gtests/src/integration/integration.cpp index ae2d3fd97..827d28f69 100644 --- a/gtests/src/integration/integration.cpp +++ b/gtests/src/integration/integration.cpp @@ -17,6 +17,7 @@ #include "integration.hpp" #include "options.hpp" +#include #include #include #include @@ -60,7 +61,12 @@ Integration::Integration() , create_keyspace_query_("") , start_time_(0ull) { // Determine if the schema keyspaces table should be updated - if (server_version_ >= "3.0.0") { + // TODO: Make cass_version (and dse_version) available for all tests + CCM::CassVersion cass_version = server_version_; + if (Options::is_dse()) { + cass_version = static_cast(cass_version).get_cass_version(); + } + if (cass_version >= "3.0.0") { system_schema_keyspaces_ = "system_schema.keyspaces"; } @@ -391,13 +397,31 @@ bool Integration::force_decommission_node(unsigned int node) { return decommission_node(node, true); } -bool Integration::stop_node(unsigned int node) { +bool Integration::start_node(unsigned int node) { // Stop the requested node - bool status = ccm_->stop_node(node); - if (status) { - stopped_nodes_.push_back(node); + if (ccm_->is_node_down(node, true)) { + bool status = ccm_->start_node(node); + std::vector::iterator it = std::find(stopped_nodes_.begin(), + stopped_nodes_.end(), + node); + if (it != stopped_nodes_.end()) { + stopped_nodes_.erase(it); + } + return status; } - return status; + return false; +} + +bool Integration::stop_node(unsigned int node, bool is_kill /*= false*/) { + // Stop the requested node + if (ccm_->is_node_up(node, true)) { + bool status = ccm_->stop_node(node, is_kill); + if (status) { + stopped_nodes_.push_back(node); + } + return status; + } + return false; } std::string Integration::generate_contact_points(const std::string& ip_prefix, diff --git a/gtests/src/integration/integration.hpp b/gtests/src/integration/integration.hpp index 5c472d9f9..c88fee7a3 100644 --- a/gtests/src/integration/integration.hpp +++ b/gtests/src/integration/integration.hpp @@ -99,8 +99,12 @@ } #define CHECK_VALUE_TYPE_VERSION(type) \ - if (this->server_version_ < type::supported_server_version()) { \ - SKIP_TEST_VERSION(this->server_version_.to_string(), \ + CCM::CassVersion cass_version = this->server_version_; \ + if (Options::is_dse()) { \ + cass_version = static_cast(cass_version).get_cass_version(); \ + } \ + if (cass_version < type::supported_server_version()) { \ + SKIP_TEST_VERSION(cass_version.to_string(), \ type::supported_server_version()) \ } @@ -423,14 +427,26 @@ class Integration : public testing::Test { */ virtual bool force_decommission_node(unsigned int node); + /** + * Start a node that was previously stopped to ensure that it is not restarted + * after test is completed + * + * @param node Node that should be started + * @return True if node was started; false otherwise (the node is invalid or + * was already started) + */ + virtual bool start_node(unsigned int node); + /** * Stop a node that should be restarted after test is completed * * @param node Node that should be stopped + * @param is_kill True if forced termination requested; false otherwise + * (default: false) * @return True if node was stopped; false otherwise (the node is invalid or * was already stopped) */ - virtual bool stop_node(unsigned int node); + virtual bool stop_node(unsigned int node, bool is_kill = false); /** * Generate the contact points for the cluster diff --git a/gtests/src/integration/objects/user_type.hpp b/gtests/src/integration/objects/user_type.hpp index f508d27da..daac83473 100644 --- a/gtests/src/integration/objects/user_type.hpp +++ b/gtests/src/integration/objects/user_type.hpp @@ -198,7 +198,8 @@ class UserType : public Object { } // Create the user type from the data type - Object::set(cass_user_type_new_from_data_type(data_type)); + Object::set( + cass_user_type_new_from_data_type(data_type)); } }; diff --git a/gtests/src/integration/policies/ignore_retry_policy.hpp b/gtests/src/integration/policies/ignore_retry_policy.hpp index 9065cb1df..6f928466a 100644 --- a/gtests/src/integration/policies/ignore_retry_policy.hpp +++ b/gtests/src/integration/policies/ignore_retry_policy.hpp @@ -38,7 +38,7 @@ class IgnoreRetryPolicy : public cass::DefaultRetryPolicy { * @return Driver ready retry policy */ static ::test::driver::RetryPolicy policy() { - cass::RetryPolicy* policy = cass::Memory::allocate(); + cass::RetryPolicy* policy = new IgnoreRetryPolicy(); policy->inc_ref(); return CassRetryPolicy::to(policy); } diff --git a/gtests/src/integration/policies/next_host_retry_policy.hpp b/gtests/src/integration/policies/next_host_retry_policy.hpp index 00d91cf2d..8974ecbf1 100644 --- a/gtests/src/integration/policies/next_host_retry_policy.hpp +++ b/gtests/src/integration/policies/next_host_retry_policy.hpp @@ -38,7 +38,7 @@ class NextHostRetryPolicy : public cass::DefaultRetryPolicy { * @return Driver ready retry policy */ static ::test::driver::RetryPolicy policy() { - cass::RetryPolicy* policy = cass::Memory::allocate(); + cass::RetryPolicy* policy = new NextHostRetryPolicy(); policy->inc_ref(); return CassRetryPolicy::to(policy); } diff --git a/gtests/src/integration/shared_ptr.hpp b/gtests/src/integration/shared_ptr.hpp index 39e9e444d..7174bf2f2 100644 --- a/gtests/src/integration/shared_ptr.hpp +++ b/gtests/src/integration/shared_ptr.hpp @@ -62,7 +62,7 @@ class SharedPtr { SharedPtr(T* ptr = NULL) : object_(NULL) { if (ptr) { - ObjectRef* object_ref = cass::Memory::allocate >(ptr); + ObjectRef* object_ref = new ObjectRef(ptr); object_ = cass::SharedRefPtr >(object_ref); } } diff --git a/gtests/src/integration/simulacron/priming_requests.hpp b/gtests/src/integration/simulacron/priming_requests.hpp index d7074a07f..9ab1716ee 100644 --- a/gtests/src/integration/simulacron/priming_requests.hpp +++ b/gtests/src/integration/simulacron/priming_requests.hpp @@ -39,7 +39,7 @@ class Request { }; Request() - : then_(cass::Memory::allocate()) { }; + : then_(new Success()) { }; /** * Generate the JSON for the priming request diff --git a/gtests/src/integration/simulacron/simulacron_integration.cpp b/gtests/src/integration/simulacron/simulacron_integration.cpp index 344b66376..3eec4ac56 100644 --- a/gtests/src/integration/simulacron/simulacron_integration.cpp +++ b/gtests/src/integration/simulacron/simulacron_integration.cpp @@ -33,7 +33,7 @@ SimulacronIntegration::~SimulacronIntegration() { void SimulacronIntegration::SetUpTestCase() { try { - sc_ = cass::Memory::allocate(); + sc_ = new test::SimulacronCluster(); } catch (SimulacronCluster::Exception scce) { TEST_LOG_ERROR(scce.what()); } diff --git a/gtests/src/integration/tests/simulacron/test_simulacron_idempotent.cpp b/gtests/src/integration/tests/simulacron/test_simulacron_idempotent.cpp index 8aa908d53..b7e0bd296 100644 --- a/gtests/src/integration/tests/simulacron/test_simulacron_idempotent.cpp +++ b/gtests/src/integration/tests/simulacron/test_simulacron_idempotent.cpp @@ -79,7 +79,7 @@ SIMULACRON_INTEGRATION_TEST_F(IdempotentTest, WriteTimeoutNonIdempotentNoRetry) SKIP_TEST_IF_SIMULACRON_UNAVAILABLE; // Simulate a write timeout on node 1 - prime_mock_query_with_result(cass::Memory::allocate(), 1); + prime_mock_query_with_result(new prime::WriteTimeout(), 1); // Loop through all the nodes in the cluster execute the mock query for (unsigned int n = 0; n < number_dc1_nodes_; ++n) { @@ -108,7 +108,7 @@ SIMULACRON_INTEGRATION_TEST_F(IdempotentTest, WriteTimeoutIdempotentRetry) { SKIP_TEST_IF_SIMULACRON_UNAVAILABLE; // Simulate a write timeout on node 1 - prime_mock_query_with_result(cass::Memory::allocate(), 1); + prime_mock_query_with_result(new prime::WriteTimeout(), 1); // Loop through all the nodes in the cluster execute the mock query bool was_node_one_attempted = false; @@ -141,7 +141,7 @@ SIMULACRON_INTEGRATION_TEST_F(IdempotentTest, ClosedConnectionNonIdempotentNoRet SKIP_TEST_IF_SIMULACRON_UNAVAILABLE; // Simulate a closed connection on node 1 - prime_mock_query_with_result(cass::Memory::allocate(), 1); + prime_mock_query_with_result(new prime::CloseConnection(), 1); // Loop through all the nodes in the cluster execute the mock query for (unsigned int n = 0; n < number_dc1_nodes_; ++n) { @@ -171,7 +171,7 @@ SIMULACRON_INTEGRATION_TEST_F(IdempotentTest, ClosedConnectionIdempotentRetry) { SKIP_TEST_IF_SIMULACRON_UNAVAILABLE; // Simulate a closed connection on node 1 - prime_mock_query_with_result(cass::Memory::allocate(), 1); + prime_mock_query_with_result(new prime::CloseConnection(), 1); // Loop through all the nodes in the cluster execute the mock query bool was_node_one_attempted = false; diff --git a/gtests/src/integration/tests/test_auth.cpp b/gtests/src/integration/tests/test_auth.cpp index e06053c40..8776914bf 100644 --- a/gtests/src/integration/tests/test_auth.cpp +++ b/gtests/src/integration/tests/test_auth.cpp @@ -203,7 +203,11 @@ CASSANDRA_INTEGRATION_TEST_F(AuthenticationTests, BadCredentials) { CHECK_FAILURE; // Add the proper logging criteria (based on server version) - if (server_version_ >= "3.10") { + CCM::CassVersion cass_version = this->server_version_; + if (Options::is_dse()) { + cass_version = static_cast(cass_version).get_cass_version(); + } + if (cass_version >= "3.10") { logger_.add_critera("Provided username invalid and/or password are incorrect"); } else { logger_.add_critera("Username and/or password are incorrect"); @@ -241,7 +245,11 @@ CASSANDRA_INTEGRATION_TEST_F(AuthenticationTests, AuthenticatorSetErrorNull) { CHECK_FAILURE; // Add the proper logging criteria (based on server version) - if (server_version_ >= "3.10") { + CCM::CassVersion cass_version = this->server_version_; + if (Options::is_dse()) { + cass_version = static_cast(cass_version).get_cass_version(); + } + if (cass_version >= "3.10") { logger_.add_critera("Provided username invalid and/or password are incorrect"); } else { logger_.add_critera("Username and/or password are incorrect"); diff --git a/gtests/src/integration/tests/test_consistency.cpp b/gtests/src/integration/tests/test_consistency.cpp index 1c09e4836..50477d9ee 100644 --- a/gtests/src/integration/tests/test_consistency.cpp +++ b/gtests/src/integration/tests/test_consistency.cpp @@ -196,6 +196,7 @@ CASSANDRA_INTEGRATION_TEST_F(ConsistencyTwoNodeClusterTests, SimpleLocalQuorum) */ CASSANDRA_INTEGRATION_TEST_F(ConsistencyTwoNodeClusterTests, SimpleEachQuorum) { CHECK_FAILURE; + CHECK_VERSION(3.0.0); // Assign the consistency level for the test insert_.set_consistency(CASS_CONSISTENCY_EACH_QUORUM); diff --git a/gtests/src/integration/tests/test_control_connection.cpp b/gtests/src/integration/tests/test_control_connection.cpp index 9ab748212..e451e0ff9 100644 --- a/gtests/src/integration/tests/test_control_connection.cpp +++ b/gtests/src/integration/tests/test_control_connection.cpp @@ -119,7 +119,7 @@ class ControlConnectionFourNodeClusterTests : public ControlConnectionTests { * each */ class ControlConnectionSingleNodeDataCentersClusterTests - : public ControlConnectionTests { + : public ControlConnectionTests { public: ControlConnectionSingleNodeDataCentersClusterTests() { number_dc1_nodes_ = 1; @@ -250,7 +250,7 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTests, logger_.add_critera("Unable to establish a control connection to host " \ "1.1.1.1 because of the following error:"); Cluster cluster = Cluster::build().with_contact_points("1.1.1.1") - .with_local_address("127.0.0.1"); + .with_local_address("127.0.0.1"); try { cluster.connect(); FAIL() << "Connection was established using invalid IP address"; @@ -289,8 +289,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTwoNodeClusterTests, * node discovery of the second node */ Cluster cluster = default_cluster() - .with_load_balance_round_robin() - .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); + .with_load_balance_round_robin() + .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); Session session = cluster.connect(); // Stop the first node and bootstrap a third node into the cluster @@ -331,12 +331,12 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTests, TopologyChange) { * to ensure all nodes can be accessed during request execution */ Cluster cluster = default_cluster() - .with_load_balance_round_robin(); + .with_load_balance_round_robin(); Session session = cluster.connect(); // Bootstrap a second node and ensure all hosts are actively used logger_.add_critera("New node " + (ccm_->get_ip_prefix() + "2") + " added"); - EXPECT_EQ(2, ccm_->bootstrap_node()); // Triggers a `NEW_NODE` event + EXPECT_EQ(2u, ccm_->bootstrap_node()); // Triggers a `NEW_NODE` event EXPECT_TRUE(wait_for_logger(1)); std::set expected_nodes; expected_nodes.insert(1); @@ -374,8 +374,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTwoNodeClusterTests, * to ensure all nodes can be accessed during request execution */ Cluster cluster = default_cluster() - .with_load_balance_round_robin() - .with_reconnect_wait_time(10); // Ensure reconnect timeout is quick + .with_load_balance_round_robin() + .with_reconnect_wait_time(10); // Ensure reconnect timeout is quick Session session = cluster.connect(); // Ensure all hosts are actively used @@ -395,7 +395,7 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTwoNodeClusterTests, // Restart the second node and ensure all hosts are actively used reset_logger_criteria("Node ", logger_nodes, " is up"); - ccm_->start_node(2); // Triggers a `UP` event + start_node(2); // Triggers a `UP` event ASSERT_TRUE(wait_for_logger(logger_nodes.size())); expected_nodes.insert(2); check_hosts(session, expected_nodes); @@ -422,8 +422,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionThreeNodeClusterTests, * node discovery */ Cluster cluster = default_cluster() - .with_load_balance_round_robin() - .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); + .with_load_balance_round_robin() + .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); Session session = cluster.connect(); // Ensure all hosts are actively used @@ -461,10 +461,10 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionThreeNodeClusterTests, logger_.add_critera("to host 192.0.2.2 closed"); logger_.add_critera("to host 192.0.2.3 closed"); Cluster cluster = default_cluster(false) // Do not add the default contact points - .with_load_balance_round_robin() - .with_contact_points(generate_contact_points("192.0.2.", 3)) // Invalid IPs - .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)) // Single valid contact point - .with_connect_timeout(1000u); // Handle initial invalid IPs + .with_load_balance_round_robin() + .with_contact_points(generate_contact_points("192.0.2.", 3)) // Invalid IPs + .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)) // Single valid contact point + .with_connect_timeout(1000u); // Handle initial invalid IPs Session session = cluster.connect(); // Ensure the invalid IPs were not reached @@ -501,8 +501,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionThreeNodeClusterTests, * node discovery */ Cluster cluster = default_cluster() - .with_load_balance_round_robin() - .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); + .with_load_balance_round_robin() + .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); Session session = cluster.connect(); // Delete the `local` row from the system table (control connection info) @@ -538,8 +538,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionThreeNodeClusterTests, connect(); // Create the default session std::stringstream update_system_table; update_system_table - << "UPDATE system.peers SET rpc_address = null WHERE peer = '" - << ccm_->get_ip_prefix() << "3'"; + << "UPDATE system.peers SET rpc_address = null WHERE peer = '" + << ccm_->get_ip_prefix() << "3'"; for (int i = 0; i < 3; ++i) { // Ensure all the nodes in the cluster are updated session_.execute(update_system_table.str()); } @@ -550,8 +550,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionThreeNodeClusterTests, * node discovery */ Cluster cluster = default_cluster(false) - .with_load_balance_round_robin() - .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); + .with_load_balance_round_robin() + .with_contact_points(generate_contact_points(ccm_->get_ip_prefix(), 1)); Session session = cluster.connect(); // Ensure nodes one and two are actively used @@ -665,8 +665,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionFourNodeClusterTests, // Create a cluster object using randomized contact points Cluster cluster = default_cluster() - .with_load_balance_round_robin() - .with_randomized_contact_points(true); + .with_load_balance_round_robin() + .with_randomized_contact_points(true); // Establish a connect and ensure the first established host is not node 1 Session session; @@ -691,7 +691,7 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionFourNodeClusterTests, // Ensure the next host is the expected host std::string current_host = - session.execute(SELECT_ALL_SYSTEM_LOCAL_CQL).host(); + session.execute(SELECT_ALL_SYSTEM_LOCAL_CQL).host(); ASSERT_STREQ(expected_host.str().c_str(), current_host.c_str()); } @@ -723,7 +723,7 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionSingleNodeDataCentersClusterTests, * policy */ Cluster cluster = default_cluster() - .with_load_balance_dc_aware("invalid_data_center", 0, false); + .with_load_balance_dc_aware("invalid_data_center", 0, false); try { Session session = cluster.connect(); FAIL() << "Connection was established using invalid data center"; @@ -766,8 +766,8 @@ CASSANDRA_INTEGRATION_TEST_F(ControlConnectionTests, std::stringstream expected_message; // Message to validate number of I/O worker threads expected_message << "Unable to connect to host " << ccm_->get_ip_prefix() - << "1 because of the following error: Received error response " - << "'Keyspace '" << inavlid_keyspace_name << "' does not exist'"; + << "1 because of the following error: Received error response " + << "'Keyspace '" << inavlid_keyspace_name << "' does not exist'"; logger_.add_critera(expected_message.str()); // Message to validate connection/host is ready/up expected_message.str(""); diff --git a/gtests/src/integration/tests/test_dc_aware_policy.cpp b/gtests/src/integration/tests/test_dc_aware_policy.cpp index 0566bb741..ec18da175 100644 --- a/gtests/src/integration/tests/test_dc_aware_policy.cpp +++ b/gtests/src/integration/tests/test_dc_aware_policy.cpp @@ -98,8 +98,8 @@ CASSANDRA_INTEGRATION_TEST_F(DcAwarePolicyTest, UsedHostsRemoteDc) { } // Stop the whole local DC - ccm_->stop_node(1, true); - ccm_->stop_node(2, true); + stop_node(1, true); + stop_node(2, true); { // Run queries using the remote DC std::vector attempted_hosts = validate(); diff --git a/gtests/src/integration/tests/test_session.cpp b/gtests/src/integration/tests/test_session.cpp index 7bca3bb3c..238775303 100644 --- a/gtests/src/integration/tests/test_session.cpp +++ b/gtests/src/integration/tests/test_session.cpp @@ -15,35 +15,83 @@ */ #include "integration.hpp" + #include "cassandra.h" +#include "scoped_lock.hpp" + +#include + +#define EVENT_MAXIMUM_WAIT_TIME_MS 5000 +#define EVENT_WAIT_FOR_NAP_MS 100 class SessionTest : public Integration { public: typedef std::pair Event; - typedef std::vector Events; + typedef std::queue Events; + + SessionTest() { + uv_mutex_init(&mutex_); + } + ~SessionTest() { + uv_mutex_destroy(&mutex_); + } void SetUp() { is_session_requested_ = false; Integration::SetUp(); } - size_t event_count() { return events_.size(); } - const Events& events() const { return events_; } + void check_event(CassHostListenerEvent expected_event, short expected_node) { + cass::ScopedMutex l(&mutex_); + std::stringstream expected_address; + expected_address << ccm_->get_ip_prefix() << expected_node; + Event event = events_.front(); + EXPECT_EQ(expected_event, event.first); + EXPECT_EQ(expected_address.str().c_str(), event.second); + events_.pop(); + } + bool wait_for_event(size_t expected_count) { + start_timer(); + while (elapsed_time() < EVENT_MAXIMUM_WAIT_TIME_MS + && event_count() < expected_count) { + msleep(EVENT_WAIT_FOR_NAP_MS); + } + return event_count() >= expected_count; + } protected: + size_t event_count() { + cass::ScopedMutex l(&mutex_); + return events_.size(); + } + void add_event(CassHostListenerEvent event, CassInet inet) { + cass::ScopedMutex l(&mutex_); + char address[CASS_INET_STRING_LENGTH]; + + cass_inet_string(inet, address); + if (event == CASS_HOST_LISTENER_EVENT_ADD) { + TEST_LOG("Host " << address << " has been ADDED"); + } else if (event == CASS_HOST_LISTENER_EVENT_REMOVE) { + TEST_LOG("Host " << address << " has been REMOVED"); + } else if (event == CASS_HOST_LISTENER_EVENT_UP) { + TEST_LOG("Host " << address << " is UP"); + } else if (event == CASS_HOST_LISTENER_EVENT_DOWN) { + TEST_LOG("Host " << address << " is DOWN"); + } else { + TEST_LOG_ERROR("Invalid event [" << event << "] for " << address); + } + + events_.push(Event(event, address)); + } static void on_host_listener(CassHostListenerEvent event, CassInet inet, void* data) { SessionTest* instance = static_cast(data); - - char address[CASS_INET_STRING_LENGTH]; - uv_inet_ntop(inet.address_length == CASS_INET_V4_LENGTH ? AF_INET : AF_INET6, - inet.address, - address, CASS_INET_STRING_LENGTH); - instance->events_.push_back(Event(event, address)); + instance->add_event(event, inet); } private: + uv_mutex_t mutex_; Events events_; }; @@ -78,26 +126,42 @@ CASSANDRA_INTEGRATION_TEST_F(SessionTest, ExternalHostListener) { .with_host_listener_callback(on_host_listener, this); Session session = cluster.connect(); - ASSERT_EQ(0u, event_count()); + // Initial node 1 events (add and up) + ASSERT_TRUE(wait_for_event(2u)); + check_event(CASS_HOST_LISTENER_EVENT_ADD, 1); + check_event(CASS_HOST_LISTENER_EVENT_UP, 1); + + // Bootstrap node 2 (add and up events) + EXPECT_EQ(2u, ccm_->bootstrap_node()); + ASSERT_TRUE(wait_for_event(2u)); + check_event(CASS_HOST_LISTENER_EVENT_ADD, 2); + check_event(CASS_HOST_LISTENER_EVENT_UP, 2); - EXPECT_EQ(2, ccm_->bootstrap_node()); + // Stop node 1 (down event) stop_node(1); + ASSERT_TRUE(wait_for_event(1u)); + check_event(CASS_HOST_LISTENER_EVENT_DOWN, 1); + + // Restart node 1 (up event) ccm_->start_node(1); + CCM::CassVersion cass_version = this->server_version_; + if (Options::is_dse()) { + cass_version = static_cast(cass_version).get_cass_version(); + } + if (cass_version >= "2.2") { + ASSERT_TRUE(wait_for_event(1u)); + } else { + ASSERT_TRUE(wait_for_event(3u)); // C* <= 2.1 fires remove and add event on restart + check_event(CASS_HOST_LISTENER_EVENT_REMOVE, 1); + check_event(CASS_HOST_LISTENER_EVENT_ADD, 1); + } + check_event(CASS_HOST_LISTENER_EVENT_UP, 1); + + // Decomission node 1 (down and remove events) force_decommission_node(1); + ASSERT_TRUE(wait_for_event(1u)); + check_event(CASS_HOST_LISTENER_EVENT_DOWN, 1); + check_event(CASS_HOST_LISTENER_EVENT_REMOVE, 1); session.close(); - - ASSERT_EQ(6u, event_count()); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_ADD, events()[0].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "2", events()[0].second); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_UP, events()[1].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "2", events()[1].second); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_DOWN, events()[2].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[2].second); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_UP, events()[3].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[3].second); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_DOWN, events()[4].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[4].second); - EXPECT_EQ(CASS_HOST_LISTENER_EVENT_REMOVE, events()[5].first); - EXPECT_EQ(ccm_->get_ip_prefix() + "1", events()[5].second); } diff --git a/gtests/src/integration/tests/test_tracing.cpp b/gtests/src/integration/tests/test_tracing.cpp index 78bc5b67e..035e43202 100644 --- a/gtests/src/integration/tests/test_tracing.cpp +++ b/gtests/src/integration/tests/test_tracing.cpp @@ -35,7 +35,7 @@ CASSANDRA_INTEGRATION_TEST_F(TracingTests, Simple) { Statement statement("SELECT * FROM system_traces.sessions WHERE session_id = ?", 1); statement.bind(0, tracing_id); Result result = session_.execute(statement); - ASSERT_GT(result.row_count(), 0); + ASSERT_GT(result.row_count(), 0u); Uuid session_id = result.first_row().column_by_name("session_id"); ASSERT_FALSE(session_id.is_null()); EXPECT_EQ(tracing_id, session_id); diff --git a/gtests/src/unit/event_loop_test.hpp b/gtests/src/unit/event_loop_test.hpp index ca869aa24..19986222b 100644 --- a/gtests/src/unit/event_loop_test.hpp +++ b/gtests/src/unit/event_loop_test.hpp @@ -55,8 +55,8 @@ class EventLoopTest : public Unit { * @return Generic future instance. */ cass::Future::Ptr execute_outage_plan(OutagePlan* outage_plan) { - cass::Future::Ptr future(cass::Memory::allocate(cass::Future::FUTURE_TYPE_GENERIC)); - add_task(cass::Memory::allocate(outage_plan, future)); + cass::Future::Ptr future(new cass::Future(cass::Future::FUTURE_TYPE_GENERIC)); + add_task(new ExecuteOutagePlan(outage_plan, future)); return future; } diff --git a/gtests/src/unit/loop_test.hpp b/gtests/src/unit/loop_test.hpp index 05b2880ac..6357e526c 100644 --- a/gtests/src/unit/loop_test.hpp +++ b/gtests/src/unit/loop_test.hpp @@ -19,7 +19,6 @@ #include "unit.hpp" #include "test_utils.hpp" -#include "memory.hpp" #include @@ -61,7 +60,7 @@ class LoopTest : public Unit { */ void starve_thread_pool(unsigned int sleep_ms) { for (int i = 0; i < NUM_WORKERS; ++i) { - workers[i].data = cass::Memory::allocate(sleep_ms); + workers[i].data = new unsigned int(sleep_ms); uv_queue_work(loop(), &workers[i], on_work, NULL); } } @@ -70,7 +69,7 @@ class LoopTest : public Unit { static void on_work(uv_work_t* req) { unsigned int* sleep_ms = static_cast(req->data); test::Utils::msleep(*sleep_ms); - cass::Memory::deallocate(sleep_ms); + delete sleep_ms; } private: diff --git a/gtests/src/unit/main.cpp b/gtests/src/unit/main.cpp index bcd6276c5..679fa129b 100644 --- a/gtests/src/unit/main.cpp +++ b/gtests/src/unit/main.cpp @@ -156,8 +156,7 @@ int main(int argc, char* argv[]) { // Initialize the Google testing framework testing::InitGoogleTest(&argc, argv); - - // Add a bootstrap mechanism for program start and finish + // Add listeners for program start and finish events testing::TestEventListeners& listeners = testing::UnitTest::GetInstance()->listeners(); #if defined(_WIN32) && defined(_DEBUG) diff --git a/gtests/src/unit/mockssandra.cpp b/gtests/src/unit/mockssandra.cpp index 44493ed33..e48375ec4 100644 --- a/gtests/src/unit/mockssandra.cpp +++ b/gtests/src/unit/mockssandra.cpp @@ -20,6 +20,7 @@ #include #include "control_connection.hpp" // For host queries +#include "memory.hpp" #include "scoped_lock.hpp" #include "tracing_data_handler.hpp" // For tracing query #include "uuids.hpp" @@ -28,11 +29,14 @@ # include "winsock.h" #endif +using cass::Memory; using cass::ScopedMutex; using cass::OStringStream; #define SSL_BUF_SIZE 8192 -#define SERVER_VERSION "3.11.2" +#define CASSANDRA_VERSION "3.11.4" +#define DSE_VERSION "6.7.1" +#define DSE_CASSANDRA_VERSION "4.0.0.671" namespace mockssandra { @@ -197,7 +201,7 @@ void ClientConnection::on_close(uv_handle_t* handle) { void ClientConnection::handle_close() { on_close(); server_->remove(this); - Memory::deallocate(this); + delete this; } void ClientConnection::on_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { @@ -229,7 +233,7 @@ void ClientConnection::handle_read(ssize_t nread, const uv_buf_t* buf) { void ClientConnection::on_write(uv_write_t* req, int status) { WriteReq* write = static_cast(req->data); write->connection->handle_write(status); - Memory::deallocate(write); + delete write; } void ClientConnection::handle_write(int status) { @@ -257,12 +261,12 @@ void ClientConnection::handle_write(int status) { int ClientConnection::internal_write(const char* data, size_t len) { uv_buf_t buf; - WriteReq* write = Memory::allocate(data, len, this); + WriteReq* write = new WriteReq(data, len, this); buf.base = const_cast(write->data.data()); buf.len = write->data.length(); int rc = uv_write(&write->req, tcp_.as_stream(), &buf, 1, on_write); if (rc != 0) { - Memory::deallocate(write); + delete write; } return rc; } @@ -483,7 +487,7 @@ void ServerConnection::listen(EventLoopGroup* event_loop_group) { if (state_ != STATE_CLOSED) return; rc_ = 0; state_ = STATE_PENDING; - event_loop_ = event_loop_group->add(Memory::allocate(this)); + event_loop_ = event_loop_group->add(new RunListen(this)); } int ServerConnection::wait_listen() { @@ -498,7 +502,7 @@ void ServerConnection::close() { ScopedMutex l(&mutex_); if (state_ != STATE_LISTENING && state_ != STATE_PENDING) return; state_ = STATE_CLOSING; - event_loop_->add(Memory::allocate(this)); + event_loop_->add(new RunClose(this)); } void ServerConnection::wait_close() { @@ -511,7 +515,7 @@ void ServerConnection::wait_close() { void ServerConnection::run(const ServerConnectionTask::Ptr& task) { ScopedMutex l(&mutex_); if (state_ != STATE_LISTENING) return; - event_loop_->add(Memory::allocate(task, Ptr(this))); + event_loop_->add(new RunTask(task, Ptr(this))); } void ServerConnection::internal_listen() { @@ -604,7 +608,7 @@ void ServerConnection::handle_connection(int status) { ClientConnection* connection = factory_.create(this); if (connection && connection->on_accept() != 0) { - Memory::deallocate(connection); + delete connection; return; } clients_.push_back(connection); @@ -1065,6 +1069,34 @@ void Collection::encode(int protocol_version, String* output) const { } } +Value::Value() + : type_(NUL) { } + +Value::Value(const cass::String& value) + : type_(VALUE) + , value_(new String(value)) { } + +Value::Value(const Collection& collection) + : type_(COLLECTION) + , collection_(new Collection(collection)){ } + +Value::Value(const Value& other) + : type_(other.type_) { + if (type_ == VALUE) { + value_ = new String(*other.value_); + } else if (type_ == COLLECTION) { + collection_ = new Collection(*other.collection_); + } +} + +Value::~Value() { + if (type_ == VALUE) { + delete value_; + } else if (type_ == COLLECTION) { + delete collection_; + } +} + void Value::encode(int protocol_version, String* output) const { if (type_ == NUL) { encode_int32(-1, output); @@ -1164,19 +1196,19 @@ Action::Builder& Action::Builder::execute_if(Action* action) { } Action::Builder& Action::Builder::nop() { - return execute(Memory::allocate()); + return execute(new Nop()); } Action::Builder& Action::Builder::wait(uint64_t timeout) { - return execute(Memory::allocate(timeout)); + return execute(new Wait(timeout)); } Action::Builder& Action::Builder::close() { - return execute(Memory::allocate()); + return execute(new Close()); } Action::Builder& Action::Builder::error(int32_t code, const String& message) { - return execute(Memory::allocate(code, message)); + return execute(new SendError(code, message)); } Action::Builder&Action::Builder::invalid_protocol() { @@ -1188,96 +1220,104 @@ Action::Builder&Action::Builder::invalid_opcode() { } Action::Builder& Action::Builder::ready() { - return execute(Memory::allocate()); + return execute(new SendReady()); } Action::Builder& Action::Builder::authenticate(const String& class_name) { - return execute(Memory::allocate(class_name)); + return execute(new SendAuthenticate(class_name)); } Action::Builder& Action::Builder::auth_challenge(const String& token) { - return execute(Memory::allocate(token)); + return execute(new SendAuthChallenge(token)); } Action::Builder& Action::Builder::auth_success(const String& token) { - return execute(Memory::allocate(token)); + return execute(new SendAuthSuccess(token)); } Action::Builder& Action::Builder::supported() { - return execute(Memory::allocate()); + return execute(new SendSupported()); } Action::Builder& Action::Builder::up_event(const Address& address) { - return execute(Memory::allocate(address)); + return execute(new SendUpEvent(address)); } Action::Builder& Action::Builder::void_result() { - return execute(Memory::allocate()); + return execute(new VoidResult()); } Action::Builder& Action::Builder::empty_rows_result(int32_t row_count) { - return execute(Memory::allocate(row_count)); + return execute(new EmptyRowsResult(row_count)); } Action::Builder& Action::Builder::no_result() { - return execute(Memory::allocate()); + return execute(new NoResult()); } Action::Builder& Action::Builder::match_query(const Matches& matches) { - return execute(Memory::allocate(matches)); + return execute(new MatchQuery(matches)); } Action::Builder& Action::Builder::client_options() { - return execute(Memory::allocate()); + return execute(new ClientOptions()); } Action::Builder& Action::Builder::system_local() { - return execute(Memory::allocate()); + return execute(new SystemLocal()); +} + +Action::Builder& Action::Builder::system_local_dse() { + return execute(new SystemLocalDse()); } Action::Builder& Action::Builder::system_peers() { - return execute(Memory::allocate()); + return execute(new SystemPeers()); +} + +Action::Builder& Action::Builder::system_peers_dse() { + return execute(new SystemPeersDse()); } Action::Builder& Action::Builder::system_traces() { - return execute(Memory::allocate()); + return execute(new SystemTraces()); } Action::Builder& Action::Builder::use_keyspace(const cass::String& keyspace) { - return execute((Memory::allocate(keyspace))); + return execute((new UseKeyspace(keyspace))); } Action::Builder& Action::Builder::plaintext_auth(const cass::String& username, const cass::String& password) { - return execute((Memory::allocate(username, password))); + return execute((new PlaintextAuth(username, password))); } Action::Builder& Action::Builder::validate_startup() { - return execute(Memory::allocate()); + return execute(new ValidateStartup()); } Action::Builder& Action::Builder::validate_credentials() { - return execute(Memory::allocate()); + return execute(new ValidateCredentials()); } Action::Builder& Action::Builder::validate_auth_response() { - return execute(Memory::allocate()); + return execute(new ValidateAuthResponse()); } Action::Builder& Action::Builder::validate_register() { - return execute(Memory::allocate()); + return execute(new ValidateRegister()); } Action::Builder& Action::Builder::validate_query() { - return execute(Memory::allocate()); + return execute(new ValidateQuery()); } Action::Builder& Action::Builder::set_registered_for_events() { - return execute(Memory::allocate()); + return execute(new SetRegisteredForEvents()); } Action::Builder& Action::Builder::set_protocol_version() { - return execute(Memory::allocate()); + return execute(new SetProtocolVersion()); } Action* Action::Builder::build() { @@ -1285,15 +1325,15 @@ Action* Action::Builder::build() { } Action::PredicateBuilder Action::Builder::is_address(const cass::Address& address) { - return PredicateBuilder(execute(Memory::allocate(address))); + return PredicateBuilder(execute(new IsAddress(address))); } Action::PredicateBuilder Action::Builder::is_address(const cass::String& address, int port) { - return PredicateBuilder(execute(Memory::allocate(Address(address, port)))); + return PredicateBuilder(execute(new IsAddress(Address(address, port)))); } Action::PredicateBuilder Action::Builder::is_query(const cass::String& query) { - return PredicateBuilder(execute(Memory::allocate(query))); + return PredicateBuilder(execute(new IsQuery(query))); } void Action::run(Request* request) const { @@ -1315,14 +1355,9 @@ Request::Request(int8_t version, int8_t flags, int16_t stream, int8_t opcode, , body_(body) , client_(client) , timer_action_(NULL) { - client->add(this); (void)flags_; // TODO: Implement custom payload etc. } -Request::~Request() { - client_->remove(this); -} - void Request::write(int8_t opcode, const String& body) { write(stream_, opcode, body); } @@ -1339,6 +1374,7 @@ void Request::error(int32_t code, const String& message) { } void Request::wait(uint64_t timeout, const Action* action) { + inc_ref(); timer_action_ = action; timer_.start(client_->server()->loop(), timeout, cass::bind_callback(&Request::on_timeout, this)); @@ -1390,6 +1426,7 @@ Hosts Request::hosts() const { void Request::on_timeout(Timer* timer) { timer_action_->run_next(this); + dec_ref(); } void SendError::on_run(Request* request) const { @@ -1475,21 +1512,20 @@ void ClientOptions::on_run(Request* request) const { QueryParameters params; if (!request->decode_query(&query, ¶ms)) { request->error(ERROR_PROTOCOL_ERROR, "Invalid query message"); - } else { - if (query == CLIENT_OPTIONS_QUERY) { - ResultSet::Builder builder("client", "options"); - Row::Builder row_builder; - for (Options::const_iterator it = request->client()->options().begin(), - end = request->client()->options().end(); it != end; ++it) { - builder.column((*it).first, Type::text()); - row_builder.text((*it).second); - } - ResultSet client_options = builder.row(row_builder.build()).build(); - - request->write(OPCODE_RESULT, client_options.encode(request->version())); + } else if (query == CLIENT_OPTIONS_QUERY) { + ResultSet::Builder builder("client", "options"); + Row::Builder row_builder; + for (Options::const_iterator it = request->client()->options().begin(), + end = request->client()->options().end(); it != end; ++it) { + builder.column((*it).first, Type::text()); + row_builder.text((*it).second); } + ResultSet client_options = builder.row(row_builder.build()).build(); + + request->write(OPCODE_RESULT, client_options.encode(request->version())); + } else { + run_next(request); } - run_next(request); } void SystemLocal::on_run(Request* request) const { @@ -1513,7 +1549,43 @@ void SystemLocal::on_run(Request* request) const { .text(request->client()->server()->address().to_string()) .text(host.dc) .text(host.rack) - .text(SERVER_VERSION) + .text(CASSANDRA_VERSION) + .inet(request->client()->server()->address()) + .text(host.partitioner) + .collection(Collection::text(host.tokens)) + .build()) + .build(); + + request->write(OPCODE_RESULT, local_rs.encode(request->version())); + } else { + run_next(request); + } +} + +void SystemLocalDse::on_run(Request* request) const { + String query; + QueryParameters params; + if (!request->decode_query(&query, ¶ms)) { + request->error(ERROR_PROTOCOL_ERROR, "Invalid query message"); + } else if (query.find(SELECT_LOCAL) != String::npos) { + const Host& host(request->host(request->address())); + + ResultSet local_rs + = ResultSet::Builder("system", "local") + .column("key", Type::text()) + .column("data_center", Type::text()) + .column("rack", Type::text()) + .column("dse_version", Type::text()) + .column("release_version", Type::text()) + .column("rpc_address", Type::inet()) + .column("partitioner", Type::text()) + .column("tokens", Type::list(Type::text())) + .row(Row::Builder() + .text(request->client()->server()->address().to_string()) + .text(host.dc) + .text(host.rack) + .text(DSE_VERSION) + .text(DSE_CASSANDRA_VERSION) .inet(request->client()->server()->address()) .text(host.partitioner) .collection(Collection::text(host.tokens)) @@ -1556,7 +1628,7 @@ void SystemPeers::on_run(Request* request) const { .inet(host.address) .text(host.dc) .text(host.rack) - .text(SERVER_VERSION) + .text(CASSANDRA_VERSION) .inet(host.address) .collection(Collection::text(host.tokens)) .build()); @@ -1585,7 +1657,80 @@ void SystemPeers::on_run(Request* request) const { .inet(host.address) .text(host.dc) .text(host.rack) - .text(SERVER_VERSION) + .text(CASSANDRA_VERSION) + .inet(host.address) + .collection(Collection::text(host.tokens)) + .build()) + .build(); + request->write(OPCODE_RESULT, peers_rs.encode(request->version())); + } + } else { + run_next(request); + } +} + +void SystemPeersDse::on_run(Request* request) const { + String query; + QueryParameters params; + if (!request->decode_query(&query, ¶ms)) { + request->error(ERROR_PROTOCOL_ERROR, "Invalid query message"); + } else if (query.find(SELECT_PEERS) != String::npos) { + const String where_clause(" WHERE peer = '"); + ResultSet::Builder peers_builder + = ResultSet::Builder("system", "peers") + .column("peer", Type::inet()) + .column("data_center", Type::text()) + .column("rack", Type::text()) + .column("dse_version", Type::text()) + .column("release_version", Type::text()) + .column("rpc_address", Type::inet()) + .column("tokens", Type::list(Type::text())); + + size_t pos = query.find(where_clause); + if (pos == String::npos) { + Hosts hosts(request->hosts()); + for (Hosts::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { + const Host& host(*it); + if (host.address == request->address()) { + continue; + } + peers_builder + .row(Row::Builder() + .inet(host.address) + .text(host.dc) + .text(host.rack) + .text(DSE_VERSION) + .text(DSE_CASSANDRA_VERSION) + .inet(host.address) + .collection(Collection::text(host.tokens)) + .build()); + } + ResultSet peers_rs = peers_builder.build(); + request->write(OPCODE_RESULT, peers_rs.encode(request->version())); + } else { + pos += where_clause.size(); + size_t end_pos = query.find("'", pos); + if (end_pos == String::npos) { + request->error(ERROR_INVALID_QUERY, "Invalid WHERE clause"); + return; + } + + String ip = query.substr(pos, end_pos - pos); + Address address; + if (!Address::from_string(ip, request->address().port(), &address)) { + request->error(ERROR_INVALID_QUERY, "Invalid inet address in WHERE clause"); + return; + } + + const Host& host(request->host(address)); + ResultSet peers_rs + = peers_builder + .row(Row::Builder() + .inet(host.address) + .text(host.dc) + .text(host.rack) + .text(CASSANDRA_VERSION) .inet(host.address) .collection(Collection::text(host.tokens)) .build()) @@ -1754,9 +1899,9 @@ RequestHandler::RequestHandler(RequestHandler::Builder* builder, , highest_supported_protocol_version_(highest_supported_protocol_version) { } const RequestHandler* RequestHandler::Builder::build() { - RequestHandler* handler(Memory::allocate(this, - lowest_supported_protocol_version_, - highest_supported_protocol_version_)); + RequestHandler* handler(new RequestHandler(this, + lowest_supported_protocol_version_, + highest_supported_protocol_version_)); handler->actions_[OPCODE_STARTUP].reset(actions_[OPCODE_STARTUP].build()); handler->actions_[OPCODE_OPTIONS].reset(actions_[OPCODE_OPTIONS].build()); @@ -1800,8 +1945,9 @@ int32_t ProtocolHandler::decode_frame(ClientConnection* client, const char* fram version_ > request_handler_->highest_supported_protocol_version()) { // Respond using the highest supported protocol that the server // supports (don't use the request's version because it's not supported) - request_handler_->invalid_protocol(Memory::allocate(request_handler_->highest_supported_protocol_version(), - flags_, stream_, opcode_, String(), client)); + Request::Ptr request(new Request(request_handler_->highest_supported_protocol_version(), + flags_, stream_, opcode_, String(), client)); + request_handler_->invalid_protocol(request.get()); return len - remaining; } state_ = HEADER; @@ -1845,13 +1991,8 @@ int32_t ProtocolHandler::decode_frame(ClientConnection* client, const char* fram } void ProtocolHandler::decode_body(ClientConnection* client, const char* body, int32_t len) { - request_handler_->run(Memory::allocate(version_, flags_, stream_, opcode_, String(body, len), client)); -} - -ClientConnection::~ClientConnection() { - while(!requests_.is_empty()) { - Memory::deallocate(requests_.front()); // Removes itself from the list - } + Request::Ptr request(new Request(version_, flags_, stream_, opcode_, String(body, len), client)); + request_handler_->run(request.get()); } void ClientConnection::on_read(const char* data, size_t len) { @@ -1872,15 +2013,15 @@ void Event::run(internal::ServerConnection* server_connection) { } Event::Ptr TopologyChangeEvent::new_node(const Address& address) { - return Ptr(Memory::allocate(NEW_NODE, address)); + return Ptr(new TopologyChangeEvent(NEW_NODE, address)); } Event::Ptr TopologyChangeEvent::moved_node(const Address& address) { - return Ptr(Memory::allocate(MOVED_NODE, address)); + return Ptr(new TopologyChangeEvent(MOVED_NODE, address)); } Event::Ptr TopologyChangeEvent::removed_node(const Address& address) { - return Ptr(Memory::allocate(REMOVED_NODE, address)); + return Ptr(new TopologyChangeEvent(REMOVED_NODE, address)); } cass::String TopologyChangeEvent::encode(TopologyChangeEvent::Type type, const cass::Address& address) { @@ -1902,11 +2043,11 @@ cass::String TopologyChangeEvent::encode(TopologyChangeEvent::Type type, const c } Event::Ptr StatusChangeEvent::up(const Address& address) { - return Ptr(Memory::allocate(UP, address)); + return Ptr(new StatusChangeEvent(UP, address)); } Event::Ptr StatusChangeEvent::down(const cass::Address& address) { - return Ptr(Memory::allocate(DOWN, address)); + return Ptr(new StatusChangeEvent(DOWN, address)); } String StatusChangeEvent::encode(Type type, const Address& address) { @@ -1926,22 +2067,22 @@ String StatusChangeEvent::encode(Type type, const Address& address) { Event::Ptr SchemaChangeEvent::keyspace(SchemaChangeEvent::Type type, const String& keyspace_name) { - return Ptr(Memory::allocate(KEYSPACE, - type, - keyspace_name)); + return Ptr(new SchemaChangeEvent(KEYSPACE, + type, + keyspace_name)); } Event::Ptr SchemaChangeEvent::table(SchemaChangeEvent::Type type, const String& keyspace_name, const String& table_name) { - return Ptr(Memory::allocate(TABLE, type, - keyspace_name, table_name)); + return Ptr(new SchemaChangeEvent(TABLE, type, + keyspace_name, table_name)); } Event::Ptr SchemaChangeEvent::user_type(SchemaChangeEvent::Type type, const String& keyspace_name, const String& user_type_name) { - return Ptr(Memory::allocate(USER_TYPE, type, + return Ptr(new SchemaChangeEvent(USER_TYPE, type, keyspace_name, user_type_name)); } @@ -1949,7 +2090,7 @@ Event::Ptr SchemaChangeEvent::function(SchemaChangeEvent::Type type, const String& keyspace_name, const String& function_name, const Vector& args_types) { - return Ptr(Memory::allocate(FUNCTION, type, + return Ptr(new SchemaChangeEvent(FUNCTION, type, keyspace_name, function_name, args_types)); } @@ -1958,7 +2099,7 @@ Event::Ptr SchemaChangeEvent::aggregate(SchemaChangeEvent::Type type, const String& keyspace_name, const String& aggregate_name, const Vector& args_types) { - return Ptr(Memory::allocate(AGGREGATE, type, + return Ptr(new SchemaChangeEvent(AGGREGATE, type, keyspace_name, aggregate_name, args_types)); } @@ -2167,7 +2308,7 @@ int Cluster::create_and_add_server(AddressGenerator& generator, Address address(generator.next()); Server server(Host(address, dc, "rack1", token_rng_), internal::ServerConnection::Ptr( - Memory::allocate(address, factory))); + new internal::ServerConnection(address, factory))); servers_.push_back(server); return static_cast(servers_.size()); diff --git a/gtests/src/unit/mockssandra.hpp b/gtests/src/unit/mockssandra.hpp index e5f4db5e5..913f2b87e 100644 --- a/gtests/src/unit/mockssandra.hpp +++ b/gtests/src/unit/mockssandra.hpp @@ -27,7 +27,6 @@ #include "address.hpp" #include "event_loop.hpp" -#include "memory.hpp" #include "string.hpp" #include "vector.hpp" #include "timer.hpp" @@ -48,7 +47,6 @@ using cass::Address; using cass::EventLoop; using cass::EventLoopGroup; using cass::List; -using cass::Memory; using cass::String; using cass::Task; using cass::Timer; @@ -412,33 +410,11 @@ class Value { }; public: - Value() - : type_(NUL) { } - - Value(const String& value) - : type_(VALUE) - , value_(Memory::allocate(value)) { } - - Value(const Collection& collection) - : type_(COLLECTION) - , collection_(Memory::allocate(collection)){ } - - Value(const Value& other) - : type_(other.type_) { - if (type_ == VALUE) { - value_ = Memory::allocate(*other.value_); - } else if (type_ == COLLECTION) { - collection_ = Memory::allocate(*other.collection_); - } - } - - ~Value() { - if (type_ == VALUE) { - Memory::deallocate(value_); - } else if (type_ == COLLECTION) { - Memory::deallocate(collection_); - } - } + Value(); + Value(const String& value); + Value(const Collection& collection); + Value(const Value& other); + ~Value(); void encode(int protocol_version, String* output) const; @@ -642,7 +618,9 @@ struct Action { Builder& client_options(); Builder& system_local(); + Builder& system_local_dse(); Builder& system_peers(); + Builder& system_peers_dse(); Builder& system_traces(); Builder& use_keyspace(const String& keyspace); @@ -688,7 +666,7 @@ struct Action { }; Action() : next(NULL) { } - virtual ~Action() { Memory::deallocate(next); } + virtual ~Action() { delete next; } void run(Request* request) const; void run_next(Request* request) const; @@ -701,7 +679,7 @@ struct Action { struct Predicate : public Action { Predicate() : then(NULL) { } - virtual ~Predicate() { Memory::deallocate(then); } + virtual ~Predicate() { delete then; } virtual bool is_predicate() const { return true; } virtual bool is_true(Request* request) const = 0; @@ -720,11 +698,13 @@ struct Predicate : public Action { }; -class Request : public List::Node { +class Request : public List::Node + , public RefCounted { public: + typedef SharedRefPtr Ptr; + Request(int8_t version, int8_t flags, int16_t stream, int8_t opcode, const String& body, ClientConnection* client); - ~Request(); int8_t version() const { return version_; } int16_t stream() const { return stream_; } @@ -865,10 +845,18 @@ struct SystemLocal : public Action { virtual void on_run(Request* request) const; }; +struct SystemLocalDse : public Action { + virtual void on_run(Request* request) const; +}; + struct SystemPeers : public Action { virtual void on_run(Request* request) const; }; +struct SystemPeersDse : public Action { + virtual void on_run(Request* request) const; +}; + struct SystemTraces : public Action { virtual void on_run(Request* request) const; }; @@ -993,7 +981,6 @@ class RequestHandler { } else { invalid_opcode_->run(request); } - Memory::deallocate(request); } private: @@ -1048,13 +1035,8 @@ class ClientConnection : public internal::ClientConnection { , protocol_version_(-1) , is_registered_for_events_(false) { } - ~ClientConnection(); - virtual void on_read(const char* data, size_t len); - void add(Request* request) { requests_.add_to_back(request); } - void remove(Request* request) { requests_.remove(request); } - const Cluster* cluster() const { return cluster_; } int protocol_version() const { return protocol_version_; } @@ -1068,7 +1050,6 @@ class ClientConnection : public internal::ClientConnection { private: ProtocolHandler handler_; const Cluster* cluster_; - List requests_; int protocol_version_; bool is_registered_for_events_; Options options_; @@ -1102,9 +1083,9 @@ class ClientConnectionFactory : public internal::ClientConnectionFactory { virtual internal::ClientConnection* create(internal::ServerConnection* server) const { if (close_immediately_) { - return Memory::allocate(server, request_handler_.get(), cluster_); + return new CloseConnection(server, request_handler_.get(), cluster_); } else { - return Memory::allocate(server, request_handler_.get(), cluster_); + return new ClientConnection(server, request_handler_.get(), cluster_); } } @@ -1341,7 +1322,7 @@ class SimpleEchoServer { public: SimpleEchoServer(const Address& address = Address("127.0.0.1", 8888)) : event_loop_group_(1) - , server_(Memory::allocate(address, factory_)) { } + , server_(new internal::ServerConnection(address, factory_)) { } ~SimpleEchoServer() { close(); @@ -1371,7 +1352,7 @@ class SimpleEchoServer { } void reset(const Address& address) { - server_.reset(Memory::allocate(address, factory_)); + server_.reset(new internal::ServerConnection(address, factory_)); } private: @@ -1411,9 +1392,9 @@ class SimpleEchoServer { virtual internal::ClientConnection* create(internal::ServerConnection* server) const { if (close_immediately_) { - return Memory::allocate(server); + return new CloseConnection(server); } else { - return Memory::allocate(server); + return new EchoConnection(server); } } diff --git a/gtests/src/unit/test_token_map_utils.hpp b/gtests/src/unit/test_token_map_utils.hpp index 384b2b160..9b46ee83e 100644 --- a/gtests/src/unit/test_token_map_utils.hpp +++ b/gtests/src/unit/test_token_map_utils.hpp @@ -276,7 +276,7 @@ inline void add_keyspace_simple(const cass::String& keyspace_name, size_t replication_factor, cass::TokenMap* token_map) { - cass::DataType::ConstPtr varchar_data_type(cass::Memory::allocate(CASS_VALUE_TYPE_VARCHAR)); + cass::DataType::ConstPtr varchar_data_type(new cass::DataType(CASS_VALUE_TYPE_VARCHAR)); ColumnMetadataVec column_metadata; column_metadata.push_back(ColumnMetadata("keyspace_name", varchar_data_type)); @@ -298,7 +298,7 @@ inline void add_keyspace_network_topology(const cass::String& keyspace_name, ReplicationMap& replication, cass::TokenMap* token_map) { - cass::DataType::ConstPtr varchar_data_type(cass::Memory::allocate(CASS_VALUE_TYPE_VARCHAR)); + cass::DataType::ConstPtr varchar_data_type(new cass::DataType(CASS_VALUE_TYPE_VARCHAR)); ColumnMetadataVec column_metadata; column_metadata.push_back(ColumnMetadata("keyspace_name", varchar_data_type)); @@ -318,9 +318,9 @@ inline cass::Host::Ptr create_host(const cass::Address& address, const cass::String& dc = "dc", const cass::String& rack = "rack", const cass::String& release_version = "3.11") { - cass::Host::Ptr host(cass::Memory::allocate(address)); + cass::Host::Ptr host(new cass::Host(address)); - cass::DataType::ConstPtr varchar_data_type(cass::Memory::allocate(CASS_VALUE_TYPE_VARCHAR)); + cass::DataType::ConstPtr varchar_data_type(new cass::DataType(CASS_VALUE_TYPE_VARCHAR)); ColumnMetadataVec column_metadata; column_metadata.push_back(ColumnMetadata("data_center", varchar_data_type)); diff --git a/gtests/src/unit/tests/test_cluster.cpp b/gtests/src/unit/tests/test_cluster.cpp index b3a6b7cca..8338d6876 100644 --- a/gtests/src/unit/tests/test_cluster.cpp +++ b/gtests/src/unit/tests/test_cluster.cpp @@ -229,7 +229,7 @@ class ClusterUnitTest : public EventLoopTest { DisableEventsListener(const Future::Ptr& close_future, mockssandra::Cluster& simple_cluster) : Listener(close_future) - , event_future_(Memory::allocate()) + , event_future_(new Future()) , simple_cluster_(simple_cluster) { } Future::Ptr& event_future() { return event_future_; } @@ -303,10 +303,10 @@ TEST_F(ClusterUnitTest, Simple) { contact_points.push_back("127.0.0.2"); contact_points.push_back("127.0.0.3"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); @@ -320,13 +320,13 @@ TEST_F(ClusterUnitTest, SimpleWithCriticalFailures) { mockssandra::SimpleRequestHandlerBuilder builder; builder.on(mockssandra::OPCODE_STARTUP) .validate_startup() - .is_address("127.0.0.2").then(mockssandra::Action::Builder().authenticate("com.dataxtax.SomeAuthenticator")) - .is_address("127.0.0.3").then(mockssandra::Action::Builder().invalid_protocol()) + .is_address("127.0.0.2").then(mockssandra::Action::Builder().authenticate("com.dataxtax.SomeAuthenticator")) + .is_address("127.0.0.3").then(mockssandra::Action::Builder().invalid_protocol()) .ready(); builder.on(mockssandra::OPCODE_AUTH_RESPONSE) .validate_auth_response() - .is_address("127.0.0.2").then(mockssandra::Action::Builder().plaintext_auth()) + .is_address("127.0.0.2").then(mockssandra::Action::Builder().plaintext_auth()) .auth_success(); ContactPointList contact_points; @@ -343,14 +343,14 @@ TEST_F(ClusterUnitTest, SimpleWithCriticalFailures) { mockssandra::SimpleCluster cluster(builder.build(), 3); ASSERT_EQ(cluster.start_all(), 0); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); ClusterSettings settings; settings.control_connection_settings.connection_settings.auth_provider.reset( - Memory::allocate("invalid", "invalid")); + new PlainTextAuthProvider("invalid", "invalid")); connector ->with_settings(settings) @@ -368,10 +368,10 @@ TEST_F(ClusterUnitTest, Resolve) { ContactPointList contact_points; contact_points.push_back("localhost"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); ASSERT_TRUE(connect_future->wait_for(WAIT_FOR_TIME)); @@ -385,14 +385,14 @@ TEST_F(ClusterUnitTest, Auth) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); ClusterSettings settings; settings.control_connection_settings.connection_settings.auth_provider.reset( - Memory::allocate("cassandra", "cassandra")); + new PlainTextAuthProvider("cassandra", "cassandra")); connector ->with_settings(settings) @@ -411,10 +411,10 @@ TEST_F(ClusterUnitTest, Ssl) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector ->with_settings(settings) @@ -437,10 +437,10 @@ TEST_F(ClusterUnitTest, Cancel) { contact_points.push_back("doesnotexist.dne"); for (size_t i = 0; i < 10; ++i) { - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); connectors.push_back(connector); connect_futures.push_back(connect_future); @@ -480,13 +480,13 @@ TEST_F(ClusterUnitTest, ReconnectToDiscoveredHosts) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); ReconnectClusterListener::Ptr listener( - Memory::allocate(close_future, &outage_plan)); + new ReconnectClusterListener(close_future, &outage_plan)); ClusterSettings settings; settings.reconnect_timeout_ms = 1; // Reconnect immediately @@ -526,13 +526,13 @@ TEST_F(ClusterUnitTest, ReconnectUpdateHosts) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); ReconnectClusterListener::Ptr listener( - Memory::allocate(close_future, &outage_plan)); + new ReconnectClusterListener(close_future, &outage_plan)); ClusterSettings settings; settings.reconnect_timeout_ms = 1; // Reconnect immediately @@ -569,13 +569,13 @@ TEST_F(ClusterUnitTest, CloseDuringReconnect) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); - Listener::Ptr listener(Memory::allocate(close_future)); + Listener::Ptr listener(new Listener(close_future)); ClusterSettings settings; settings.reconnect_timeout_ms = 100000; // Make sure we're reconnecting when we close. @@ -604,15 +604,15 @@ TEST_F(ClusterUnitTest, NotifyDownUp) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - Future::Ptr up_future(Memory::allocate()); - Future::Ptr down_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + Future::Ptr up_future(new Future()); + Future::Ptr down_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); - UpDownListener::Ptr listener(Memory::allocate(close_future, up_future, down_future)); + UpDownListener::Ptr listener(new UpDownListener(close_future, up_future, down_future)); connector ->with_listener(listener.get()) @@ -648,10 +648,10 @@ TEST_F(ClusterUnitTest, ProtocolNegotiation) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); @@ -670,10 +670,10 @@ TEST_F(ClusterUnitTest, NoSupportedProtocols) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); @@ -691,10 +691,10 @@ TEST_F(ClusterUnitTest, FindValidHost) { contact_points.push_back("127.99.99.2"); // Invalid contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); ClusterSettings settings; settings.control_connection_settings.connection_settings.connect_timeout_ms = 100; @@ -716,10 +716,10 @@ TEST_F(ClusterUnitTest, NoHostsAvailable) { contact_points.push_back("127.0.0.2"); contact_points.push_back("127.0.0.3"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); connector->connect(event_loop()); @@ -735,14 +735,14 @@ TEST_F(ClusterUnitTest, InvalidAuth) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); ClusterSettings settings; settings.control_connection_settings.connection_settings.auth_provider.reset( - Memory::allocate("invalid", "invalid")); + new PlainTextAuthProvider("invalid", "invalid")); connector ->with_settings(settings) @@ -761,10 +761,10 @@ TEST_F(ClusterUnitTest, InvalidSsl) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); SslContext::Ptr ssl_context(SslContextFactory::create()); // No trusted cert @@ -790,19 +790,19 @@ TEST_F(ClusterUnitTest, DCAwareRecoverOnRemoteHost) { ContactPointList contact_points; contact_points.push_back(local_address.to_string()); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); - Future::Ptr up_future(Memory::allocate()); - Future::Ptr recover_future(Memory::allocate()); + Future::Ptr up_future(new Future()); + Future::Ptr recover_future(new Future()); RecoverClusterListener::Ptr listener( - Memory::allocate(close_future, up_future, recover_future)); + new RecoverClusterListener(close_future, up_future, recover_future)); ClusterSettings settings; - settings.load_balancing_policy.reset(Memory::allocate("dc1", 1, false)); // Allow connection to a single remote host + settings.load_balancing_policy.reset(new DCAwarePolicy("dc1", 1, false)); // Allow connection to a single remote host settings.load_balancing_policies.clear(); settings.load_balancing_policies.push_back(settings.load_balancing_policy); settings.reconnect_timeout_ms = 1; // Reconnect immediately @@ -845,13 +845,13 @@ TEST_F(ClusterUnitTest, InvalidDC) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_connected, connect_future.get()))); ClusterSettings settings; - settings.load_balancing_policy.reset(Memory::allocate("invalid_dc", 0, false)); // Invalid DC and not using remote hosts + settings.load_balancing_policy.reset(new DCAwarePolicy("invalid_dc", 0, false)); // Invalid DC and not using remote hosts settings.load_balancing_policies.clear(); settings.load_balancing_policies.push_back(settings.load_balancing_policy); @@ -873,17 +873,17 @@ TEST_F(ClusterUnitTest, DisableEventsOnStartup) { ContactPointList contact_points; contact_points.push_back("127.0.0.1"); - Future::Ptr connect_future(Memory::allocate()); - ClusterConnector::Ptr connector(Memory::allocate(contact_points, - PROTOCOL_VERSION, - bind_callback(on_connection_reconnect, connect_future.get()))); + Future::Ptr connect_future(new Future()); + ClusterConnector::Ptr connector(new ClusterConnector(contact_points, + PROTOCOL_VERSION, + bind_callback(on_connection_reconnect, connect_future.get()))); ClusterSettings settings; settings.disable_events_on_startup = true; // Disable events to start - Future::Ptr close_future(Memory::allocate()); + Future::Ptr close_future(new Future()); DisableEventsListener::Ptr listener( - cass::Memory::allocate(close_future, cluster)); + new DisableEventsListener(close_future, cluster)); connector ->with_listener(listener.get()) diff --git a/gtests/src/unit/tests/test_connection.cpp b/gtests/src/unit/tests/test_connection.cpp index 1f4ecc511..22e5db413 100644 --- a/gtests/src/unit/tests/test_connection.cpp +++ b/gtests/src/unit/tests/test_connection.cpp @@ -18,8 +18,8 @@ #include "auth.hpp" #include "connector.hpp" -#include "delayed_connector.hpp" #include "constants.hpp" +#include "delayed_connector.hpp" #include "request_callback.hpp" #include "ssl.hpp" @@ -84,7 +84,7 @@ class ConnectionUnitTest : public LoopTest { state->status = STATUS_CONNECTED; state->connection = connector->release_connection(); state->connection->start_heartbeats(); - state->connection->write_and_flush(RequestCallback::Ptr(Memory::allocate(state->connection.get(), state))); + state->connection->write_and_flush(RequestCallback::Ptr(new RequestCallback(state->connection.get(), state))); } static void on_connection_error_code(Connector* connector, Connector::ConnectionError* error_code) { @@ -104,7 +104,7 @@ class ConnectionUnitTest : public LoopTest { state->status = STATUS_CONNECTED; state->connection = connector->release_connection(); state->connection->start_heartbeats(); - state->connection->write_and_flush(RequestCallback::Ptr(Memory::allocate(state->connection.get(), state))); + state->connection->write_and_flush(RequestCallback::Ptr(new RequestCallback(state->connection.get(), state))); } static void on_delayed_error_code(DelayedConnector* connector, Connector::ConnectionError* error_code) { @@ -120,9 +120,9 @@ TEST_F(ConnectionUnitTest, Simple) { ASSERT_EQ(cluster.start_all(), 0); State state; - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &state))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &state))); connector->connect(loop()); @@ -141,9 +141,9 @@ TEST_F(ConnectionUnitTest, Keyspace) { ASSERT_EQ(cluster.start_all(), 0); State state; - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &state))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &state))); connector ->with_keyspace("foo") @@ -161,12 +161,12 @@ TEST_F(ConnectionUnitTest, Auth) { ASSERT_EQ(cluster.start_all(), 0); State state; - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &state))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &state))); ConnectionSettings settings; - settings.auth_provider.reset(Memory::allocate("cassandra", "cassandra")); + settings.auth_provider.reset(new PlainTextAuthProvider("cassandra", "cassandra")); connector ->with_settings(settings) @@ -183,9 +183,9 @@ TEST_F(ConnectionUnitTest, Ssl) { ASSERT_EQ(cluster.start_all(), 0); State state; - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &state))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &state))); connector ->with_settings(settings) ->connect(loop()); @@ -199,9 +199,9 @@ TEST_F(ConnectionUnitTest, Refused) { // Don't start cluster Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -218,9 +218,9 @@ TEST_F(ConnectionUnitTest, Close) { bool is_closed(false); for (size_t i = 0; i < 10; ++i) { - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_close, &is_closed))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_close, &is_closed))); connector->connect(loop()); connectors.push_back(connector); } @@ -240,9 +240,9 @@ TEST_F(ConnectionUnitTest, SslClose) { bool is_closed(false); for (size_t i = 0; i < 10; ++i) { - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_close, &is_closed))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_close, &is_closed))); connector ->with_settings(settings) ->connect(loop()); @@ -262,9 +262,9 @@ TEST_F(ConnectionUnitTest, Cancel) { Connector::ConnectionError error_code(Connector::CONNECTION_OK); for (size_t i = 0; i < 10; ++i) { - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector->connect(loop()); connectors.push_back(connector); } @@ -290,9 +290,9 @@ TEST_F(ConnectionUnitTest, SslCancel) { Connector::ConnectionError error_code(Connector::CONNECTION_OK); for (size_t i = 0; i < 10; ++i) { - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector ->with_settings(settings) ->connect(loop()); @@ -318,9 +318,9 @@ TEST_F(ConnectionUnitTest, Timeout) { ASSERT_EQ(cluster.start_all(), 0); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); ConnectionSettings settings; settings.connect_timeout_ms = 200; @@ -344,9 +344,9 @@ TEST_F(ConnectionUnitTest, InvalidKeyspace) { ASSERT_EQ(cluster.start_all(), 0); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector ->with_keyspace("invalid") ->connect(loop()); @@ -361,9 +361,9 @@ TEST_F(ConnectionUnitTest, InvalidProtocol) { ASSERT_EQ(cluster.start_all(), 0); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - 0x7F, // Invalid protocol version - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + 0x7F, // Invalid protocol version + bind_callback(on_connection_error_code, &error_code))); connector ->connect(loop()); @@ -379,9 +379,9 @@ TEST_F(ConnectionUnitTest, DeprecatedProtocol) { cluster.start_all(); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector ->connect(loop()); @@ -395,12 +395,12 @@ TEST_F(ConnectionUnitTest, InvalidAuth) { ASSERT_EQ(cluster.start_all(), 0); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); ConnectionSettings settings; - settings.auth_provider.reset(Memory::allocate("invalid", "invalid")); + settings.auth_provider.reset(new PlainTextAuthProvider("invalid", "invalid")); connector ->with_settings(settings) @@ -416,9 +416,9 @@ TEST_F(ConnectionUnitTest, InvalidNoSsl) { ASSERT_EQ(cluster.start_all(), 0); // Start without ssl Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); SslContext::Ptr ssl_context(SslContextFactory::create()); @@ -441,9 +441,9 @@ TEST_F(ConnectionUnitTest, InvalidSsl) { ASSERT_EQ(cluster.start_all(), 0); Connector::ConnectionError error_code(Connector::CONNECTION_OK); - Connector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + Connector::Ptr connector(new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); SslContext::Ptr ssl_context(SslContextFactory::create()); // No trusted cert @@ -465,9 +465,9 @@ TEST_F(ConnectionUnitTest, Delayed) { ASSERT_EQ(cluster.start_all(), 0); State state; - DelayedConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_delayed_connected, &state))); + DelayedConnector::Ptr connector(new DelayedConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_delayed_connected, &state))); connector->delayed_connect(loop(), 500); @@ -481,9 +481,9 @@ TEST_F(ConnectionUnitTest, DelayedCancel) { ASSERT_EQ(cluster.start_all(), 0); State state; - DelayedConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_delayed_connected, &state))); + DelayedConnector::Ptr connector(new DelayedConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_delayed_connected, &state))); connector->delayed_connect(loop(), 500); @@ -497,9 +497,9 @@ TEST_F(ConnectionUnitTest, DelayedCancel) { Connector::ConnectionError error_code(Connector::CONNECTION_OK); for (size_t i = 0; i < 10; ++i) { - DelayedConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_delayed_error_code, &error_code))); + DelayedConnector::Ptr connector(new DelayedConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_delayed_error_code, &error_code))); connector->delayed_connect(loop(), 500); connectors.push_back(connector); } diff --git a/gtests/src/unit/tests/test_control_connection.cpp b/gtests/src/unit/tests/test_control_connection.cpp index bd1c73d2e..50c214e3d 100644 --- a/gtests/src/unit/tests/test_control_connection.cpp +++ b/gtests/src/unit/tests/test_control_connection.cpp @@ -125,13 +125,13 @@ class RecordingControlConnectionListener virtual void on_up(const Address& address) { RecordedEvent event(RecordedEvent::NODE_UP); - event.host.reset(Memory::allocate(address)); + event.host.reset(new Host(address)); events_.push_back(event); } virtual void on_down(const Address& address) { RecordedEvent event(RecordedEvent::NODE_DOWN); - event.host.reset(Memory::allocate(address)); + event.host.reset(new Host(address)); events_.push_back(event); } @@ -143,7 +143,7 @@ class RecordingControlConnectionListener virtual void on_remove(const Address& address) { RecordedEvent event(RecordedEvent::NODE_REMOVED); - event.host.reset(Memory::allocate(address)); + event.host.reset(new Host(address)); events_.push_back(event); } @@ -194,9 +194,9 @@ class ControlConnectionUnitTest : public LoopTest { } virtual void on_update_schema(SchemaType type, - const ResultResponse::Ptr& result, - const String& keyspace_name, - const String& target_name) { + const ResultResponse::Ptr& result, + const String& keyspace_name, + const String& target_name) { RecordingControlConnectionListener::on_update_schema(type, result, keyspace_name, target_name); if (type == COLUMN || type == INDEX) return; @@ -247,9 +247,9 @@ TEST_F(ControlConnectionUnitTest, Simple) { ASSERT_EQ(cluster.start_all(), 0); bool is_connected = false; - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &is_connected))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &is_connected))); connector->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -262,11 +262,11 @@ TEST_F(ControlConnectionUnitTest, Auth) { ASSERT_EQ(cluster.start_all(), 0); bool is_connected = false; - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &is_connected))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &is_connected))); ControlConnectionSettings settings; - settings.connection_settings.auth_provider.reset(Memory::allocate("cassandra", "cassandra")); + settings.connection_settings.auth_provider.reset(new PlainTextAuthProvider("cassandra", "cassandra")); connector ->with_settings(settings) @@ -284,9 +284,9 @@ TEST_F(ControlConnectionUnitTest, Ssl) { ASSERT_EQ(cluster.start_all(), 0); bool is_connected = false; - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &is_connected))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &is_connected))); connector ->with_settings(settings) ->connect(loop()); @@ -305,9 +305,9 @@ TEST_F(ControlConnectionUnitTest, Close) { bool is_closed(false); for (size_t i = 0; i < 10; ++i) { - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_close, &is_closed))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_close, &is_closed))); connector->connect(loop()); connectors.push_back(connector); } @@ -325,9 +325,9 @@ TEST_F(ControlConnectionUnitTest, Cancel) { ControlConnector::ControlConnectionError error_code(ControlConnector::CONTROL_CONNECTION_OK); for (size_t i = 0; i < 10; ++i) { - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); connector->connect(loop()); connectors.push_back(connector); } @@ -355,9 +355,9 @@ TEST_F(ControlConnectionUnitTest, StatusChangeEvents) { listener.add_event(StatusChangeEvent::up(address)); listener.add_event(StatusChangeEvent::down(address)); - ControlConnector::Ptr connector(Memory::allocate(address, - PROTOCOL_VERSION, - bind_callback(on_connection_event, &listener))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(address)), + PROTOCOL_VERSION, + bind_callback(on_connection_event, &listener))); connector ->with_listener(&listener) ->connect(loop()); @@ -387,9 +387,9 @@ TEST_F(ControlConnectionUnitTest, TopologyChangeEvents) { listener.add_event(TopologyChangeEvent::new_node(address2)); listener.add_event(TopologyChangeEvent::removed_node(address2)); - ControlConnector::Ptr connector(Memory::allocate(address1, - PROTOCOL_VERSION, - bind_callback(on_connection_event, &listener))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(address1)), + PROTOCOL_VERSION, + bind_callback(on_connection_event, &listener))); connector ->with_listener(&listener) ->connect(loop()); @@ -437,9 +437,9 @@ TEST_F(ControlConnectionUnitTest, SchemaChangeEvents) { listener.add_event(SchemaChangeEvent::aggregate(SchemaChangeEvent::DROPPED, "keyspace1", "aggregate1", Vector(1, "varchar"))); - ControlConnector::Ptr connector(Memory::allocate(address, - PROTOCOL_VERSION, - bind_callback(on_connection_event, &listener))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(address)), + PROTOCOL_VERSION, + bind_callback(on_connection_event, &listener))); connector ->with_listener(&listener) ->connect(loop()); @@ -532,9 +532,9 @@ TEST_F(ControlConnectionUnitTest, EventDuringStartup) { RecordingControlConnectionListener listener; bool is_connected; - ControlConnector::Ptr connector(Memory::allocate(address, - PROTOCOL_VERSION, - bind_callback(on_connection_connected, &is_connected))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(address)), + PROTOCOL_VERSION, + bind_callback(on_connection_connected, &is_connected))); connector ->with_listener(&listener) ->connect(loop()); @@ -554,9 +554,9 @@ TEST_F(ControlConnectionUnitTest, InvalidProtocol) { ASSERT_EQ(cluster.start_all(), 0); ControlConnector::ControlConnectionError error_code(ControlConnector::CONTROL_CONNECTION_OK); - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - 0x7F, // Invalid protocol version - bind_callback(on_connection_error_code, &error_code))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + 0x7F, // Invalid protocol version + bind_callback(on_connection_error_code, &error_code))); connector->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -570,12 +570,12 @@ TEST_F(ControlConnectionUnitTest, InvalidAuth) { ASSERT_EQ(cluster.start_all(), 0); ControlConnector::ControlConnectionError error_code(ControlConnector::CONTROL_CONNECTION_OK); - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); ControlConnectionSettings settings; - settings.connection_settings.auth_provider.reset(Memory::allocate("invalid", "invalid")); + settings.connection_settings.auth_provider.reset(new PlainTextAuthProvider("invalid", "invalid")); connector ->with_settings(settings) @@ -593,9 +593,9 @@ TEST_F(ControlConnectionUnitTest, InvalidSsl) { ASSERT_EQ(cluster.start_all(), 0); ControlConnector::ControlConnectionError error_code(ControlConnector::CONTROL_CONNECTION_OK); - ControlConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(on_connection_error_code, &error_code))); + ControlConnector::Ptr connector(new ControlConnector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(on_connection_error_code, &error_code))); SslContext::Ptr ssl_context(SslContextFactory::create()); // No trusted cert diff --git a/gtests/src/unit/tests/test_copy_on_write.cpp b/gtests/src/unit/tests/test_copy_on_write.cpp index 67f7b4397..1b183dde9 100644 --- a/gtests/src/unit/tests/test_copy_on_write.cpp +++ b/gtests/src/unit/tests/test_copy_on_write.cpp @@ -23,7 +23,7 @@ #include "vector.hpp" TEST(CopyOnWriteUnitTest, Simple) { - cass::Vector* ptr = cass::Memory::allocate >(); + cass::Vector* ptr = new cass::Vector(); cass::CopyOnWritePtr > vec(ptr); // Only a single reference so no copy should be made diff --git a/gtests/src/unit/tests/test_event_loop.cpp b/gtests/src/unit/tests/test_event_loop.cpp index 250243df0..94b0d70bf 100644 --- a/gtests/src/unit/tests/test_event_loop.cpp +++ b/gtests/src/unit/tests/test_event_loop.cpp @@ -111,7 +111,7 @@ TEST_F(EventLoopUnitTest, ExecuteTask) { ASSERT_EQ(0, event_loop.run()); ASSERT_FALSE(is_task_completed()); - event_loop.add(cass::Memory::allocate(this)); + event_loop.add(new MarkTaskCompleted(this)); event_loop.close_handles(); event_loop.join(); @@ -125,7 +125,7 @@ TEST_F(EventLoopUnitTest, ThreadRunningOn) { ASSERT_EQ(0, event_loop.run()); ASSERT_FALSE(is_running_on()); - event_loop.add(cass::Memory::allocate(this, &event_loop)); + event_loop.add(new MarkIsRunningOn(this, &event_loop)); event_loop.close_handles(); event_loop.join(); @@ -144,7 +144,7 @@ TEST_F(EventLoopUnitTest, ThreadNotRunningOn) { ASSERT_EQ(0, event_loop_2.init("EventLoopUnitTest::ThreadNotRunningOn (EventLoop 2)")); ASSERT_STREQ("EventLoopUnitTest::ThreadNotRunningOn (EventLoop 2)", event_loop_2.name().c_str()); ASSERT_EQ(0, event_loop_2.run()); - event_loop_2.add(cass::Memory::allocate(this, &event_loop)); + event_loop_2.add(new MarkIsRunningOn(this, &event_loop)); event_loop_2.close_handles(); event_loop_2.join(); diff --git a/gtests/src/unit/tests/test_exec_profile.cpp b/gtests/src/unit/tests/test_exec_profile.cpp index e7a973ee8..9d7bcc447 100644 --- a/gtests/src/unit/tests/test_exec_profile.cpp +++ b/gtests/src/unit/tests/test_exec_profile.cpp @@ -16,7 +16,6 @@ #include #include "config.hpp" -#include "memory.hpp" bool execution_profile(const cass::Config& config, const cass::String& name, @@ -104,10 +103,10 @@ TEST(ExecutionProfileUnitTest, DISABLED_ClusterLoadBalancingPolicy) { // the test is invalid making the whole test invalid. TEST(ExecutionProfileUnitTest, DISABLED_ClusterLoadBalancingPolicies) { cass::ExecutionProfile profile_1; - profile_1.set_load_balancing_policy(cass::Memory::allocate()); + profile_1.set_load_balancing_policy(new cass::DCAwarePolicy()); cass::ExecutionProfile profile_2; cass::ExecutionProfile profile_3; - profile_3.set_load_balancing_policy(cass::Memory::allocate()); + profile_3.set_load_balancing_policy(new cass::RoundRobinPolicy()); cass::Config config; config.set_execution_profile("profile_1", &profile_1); @@ -278,10 +277,10 @@ TEST(ExecutionProfileUnitTest, ClusterRetryPolicy) { TEST(ExecutionProfileUnitTest, ClusterRetryPolicies) { cass::ExecutionProfile profile_1; - profile_1.set_retry_policy(cass::Memory::allocate()); + profile_1.set_retry_policy(new cass::FallthroughRetryPolicy()); cass::ExecutionProfile profile_2; cass::ExecutionProfile profile_3; - profile_3.set_retry_policy(cass::Memory::allocate()); + profile_3.set_retry_policy(new cass::DefaultRetryPolicy()); cass::Config config; config.set_execution_profile("profile_1", &profile_1); @@ -317,7 +316,7 @@ TEST(ExecutionProfileUnitTest, ClusterSpeculativeExecutionPolicy) { cass::ExecutionProfile profile; cass::Config config; - config.set_speculative_execution_policy(cass::Memory::allocate()); + config.set_speculative_execution_policy(new cass::NoSpeculativeExecutionPolicy()); config.set_execution_profile("profile", &profile); cass::Config copy_config = config.new_instance(); @@ -331,13 +330,13 @@ TEST(ExecutionProfileUnitTest, ClusterSpeculativeExecutionPolicy) { TEST(ExecutionProfileUnitTest, ClusterSpeculativeExecutionPolicies) { cass::ExecutionProfile profile_1; - profile_1.set_speculative_execution_policy(cass::Memory::allocate(1, 2)); + profile_1.set_speculative_execution_policy(new cass::ConstantSpeculativeExecutionPolicy(1, 2)); cass::ExecutionProfile profile_2; cass::ExecutionProfile profile_3; - profile_3.set_speculative_execution_policy(cass::Memory::allocate()); + profile_3.set_speculative_execution_policy(new cass::NoSpeculativeExecutionPolicy()); cass::Config config; - config.set_speculative_execution_policy(cass::Memory::allocate(3, 4)); + config.set_speculative_execution_policy(new cass::ConstantSpeculativeExecutionPolicy(3, 4)); config.set_execution_profile("profile_1", &profile_1); config.set_execution_profile("profile_2", &profile_2); config.set_execution_profile("profile_3", &profile_3); diff --git a/gtests/src/unit/tests/test_load_balancing.cpp b/gtests/src/unit/tests/test_load_balancing.cpp index 5c6260a2e..aed8fbece 100644 --- a/gtests/src/unit/tests/test_load_balancing.cpp +++ b/gtests/src/unit/tests/test_load_balancing.cpp @@ -57,7 +57,7 @@ cass::Address addr_for_sequence(size_t i) { cass::SharedRefPtr host_for_addr(const cass::Address addr, const cass::String& rack = "rack", const cass::String& dc = "dc") { - cass::SharedRefPtrhost(cass::Memory::allocate(addr)); + cass::SharedRefPtrhost(new cass::Host(addr)); host->set_rack_and_dc(rack, dc); return host; } @@ -75,8 +75,8 @@ void populate_hosts(size_t count, const cass::String& rack, void verify_sequence(cass::QueryPlan* qp, const cass::Vector& sequence) { cass::Address received; for (cass::Vector::const_iterator it = sequence.begin(); - it!= sequence.end(); - ++it) { + it!= sequence.end(); + ++it) { ASSERT_TRUE(qp->compute_next(&received)); EXPECT_EQ(addr_for_sequence(*it), received); } @@ -481,10 +481,10 @@ TEST(DatacenterAwareLoadBalancingUnitTest, AllowRemoteDatacentersForLocalConsist policy.init(cass::SharedRefPtr(), hosts, NULL); // Set local CL - cass::QueryRequest::Ptr request(cass::Memory::allocate("", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("", 0)); request->set_consistency(CASS_CONSISTENCY_LOCAL_ONE); cass::SharedRefPtr request_handler( - cass::Memory::allocate(request, cass::ResponseFuture::Ptr())); + new cass::RequestHandler(request, cass::ResponseFuture::Ptr())); // Check for only local hosts are used cass::ScopedPtr qp(policy.new_query_plan("ks", request_handler.get(), NULL)); @@ -499,10 +499,10 @@ TEST(DatacenterAwareLoadBalancingUnitTest, AllowRemoteDatacentersForLocalConsist policy.init(cass::SharedRefPtr(), hosts, NULL); // Set local CL - cass::QueryRequest::Ptr request(cass::Memory::allocate("", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("", 0)); request->set_consistency(CASS_CONSISTENCY_LOCAL_QUORUM); cass::SharedRefPtr request_handler( - cass::Memory::allocate(request, cass::ResponseFuture::Ptr())); + new cass::RequestHandler(request, cass::ResponseFuture::Ptr())); // Check for only local hosts are used cass::ScopedPtr qp(policy.new_query_plan("ks", request_handler.get(), NULL)); @@ -530,7 +530,7 @@ TEST(DatacenterAwareLoadBalancingUnitTest, StartWithEmptyLocalDatacenter) { { cass::DCAwarePolicy policy("", 0, false); policy.init(cass::SharedRefPtr( - cass::Memory::allocate(cass::Address("0.0.0.0", 9042))), hosts, NULL); + new cass::Host(cass::Address("0.0.0.0", 9042))), hosts, NULL); cass::ScopedPtr qp(policy.new_query_plan("ks", NULL, NULL)); const size_t seq[] = {1}; @@ -669,15 +669,15 @@ TEST(TokenAwareLoadBalancingUnitTest, Simple) { add_keyspace_simple("test", 3, token_map.get()); token_map->build(); - cass::TokenAwarePolicy policy(cass::Memory::allocate(), false); + cass::TokenAwarePolicy policy(new cass::RoundRobinPolicy(), false); policy.init(cass::SharedRefPtr(), hosts, NULL); - cass::QueryRequest::Ptr request(cass::Memory::allocate("", 1)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("", 1)); const char* value = "kjdfjkldsdjkl"; // hash: 9024137376112061887 request->set(0, cass::CassString(value, strlen(value))); request->add_key_index(0); cass::SharedRefPtr request_handler( - cass::Memory::allocate(request, cass::ResponseFuture::Ptr())); + new cass::RequestHandler(request, cass::ResponseFuture::Ptr())); { cass::ScopedPtr qp(policy.new_query_plan("test", request_handler.get(), token_map.get())); @@ -725,7 +725,7 @@ TEST(TokenAwareLoadBalancingUnitTest, NetworkTopology) { // 7.0.0.0 local 9223372036854775806 const uint64_t partition_size = CASS_UINT64_MAX / num_hosts; - cass::Murmur3Partitioner::Token token = CASS_INT64_MIN + partition_size; + cass::Murmur3Partitioner::Token token = CASS_INT64_MIN + partition_size; for (size_t i = 1; i <= num_hosts; ++i) { cass::Host::Ptr host(create_host(addr_for_sequence(i), @@ -745,15 +745,15 @@ TEST(TokenAwareLoadBalancingUnitTest, NetworkTopology) { add_keyspace_network_topology("test", replication, token_map.get()); token_map->build(); - cass::TokenAwarePolicy policy(cass::Memory::allocate(LOCAL_DC, num_hosts / 2, false), false); + cass::TokenAwarePolicy policy(new cass::DCAwarePolicy(LOCAL_DC, num_hosts / 2, false), false); policy.init(cass::SharedRefPtr(), hosts, NULL); - cass::QueryRequest::Ptr request(cass::Memory::allocate("", 1)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("", 1)); const char* value = "abc"; // hash: -5434086359492102041 request->set(0, cass::CassString(value, strlen(value))); request->add_key_index(0); cass::SharedRefPtr request_handler( - cass::Memory::allocate(request, cass::ResponseFuture::Ptr())); + new cass::RequestHandler(request, cass::ResponseFuture::Ptr())); { cass::ScopedPtr qp(policy.new_query_plan("test", request_handler.get(), token_map.get())); @@ -815,17 +815,17 @@ TEST(TokenAwareLoadBalancingUnitTest, ShuffleReplicas) { add_keyspace_simple("test", 3, token_map.get()); token_map->build(); - cass::QueryRequest::Ptr request(cass::Memory::allocate("", 1)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("", 1)); const char* value = "kjdfjkldsdjkl"; // hash: 9024137376112061887 request->set(0, cass::CassString(value, strlen(value))); request->add_key_index(0); cass::SharedRefPtr request_handler( - cass::Memory::allocate(request, cass::ResponseFuture::Ptr())); + new cass::RequestHandler(request, cass::ResponseFuture::Ptr())); cass::HostVec not_shuffled; { - cass::TokenAwarePolicy policy(cass::Memory::allocate(), false); // Not shuffled + cass::TokenAwarePolicy policy(new cass::RoundRobinPolicy(), false); // Not shuffled policy.init(cass::SharedRefPtr(), hosts, &random); cass::ScopedPtr qp1(policy.new_query_plan("test", request_handler.get(), token_map.get())); for (int i = 0; i < num_hosts; ++i) { @@ -843,7 +843,7 @@ TEST(TokenAwareLoadBalancingUnitTest, ShuffleReplicas) { // Verify that the shuffle setting does indeed shuffle the replicas { - cass::TokenAwarePolicy shuffle_policy(cass::Memory::allocate(), true); // Shuffled + cass::TokenAwarePolicy shuffle_policy(new cass::RoundRobinPolicy(), true); // Shuffled shuffle_policy.init(cass::SharedRefPtr(), hosts, &random); cass::HostVec shuffled_previous; @@ -940,7 +940,7 @@ TEST(LatencyAwareLoadBalancingUnitTest, Simple) { const int64_t num_hosts = 4; cass::HostMap hosts; populate_hosts(num_hosts, "rack1", LOCAL_DC, &hosts); - cass::LatencyAwarePolicy policy(cass::Memory::allocate(), settings); + cass::LatencyAwarePolicy policy(new cass::RoundRobinPolicy(), settings); policy.init(cass::SharedRefPtr(), hosts, NULL); // Record some latencies with 100 ns being the minimum @@ -1000,7 +1000,7 @@ TEST(LatencyAwareLoadBalancingUnitTest, MinAverageUnderMinMeasured) { const int64_t num_hosts = 4; cass::HostMap hosts; populate_hosts(num_hosts, "rack1", LOCAL_DC, &hosts); - cass::LatencyAwarePolicy policy(cass::Memory::allocate(), settings); + cass::LatencyAwarePolicy policy(new cass::RoundRobinPolicy(), settings); policy.init(cass::SharedRefPtr(), hosts, NULL); int count = 1; @@ -1034,7 +1034,7 @@ TEST(WhitelistLoadBalancingUnitTest, Hosts) { cass::ContactPointList whitelist_hosts; whitelist_hosts.push_back("37.0.0.0"); whitelist_hosts.push_back("83.0.0.0"); - cass::WhitelistPolicy policy(cass::Memory::allocate(), whitelist_hosts); + cass::WhitelistPolicy policy(new cass::RoundRobinPolicy(), whitelist_hosts); policy.init(cass::SharedRefPtr(), hosts, NULL); cass::ScopedPtr qp(policy.new_query_plan("ks", NULL, NULL)); @@ -1055,7 +1055,7 @@ TEST(WhitelistLoadBalancingUnitTest, Datacenters) { cass::DcList whitelist_dcs; whitelist_dcs.push_back(LOCAL_DC); whitelist_dcs.push_back(REMOTE_DC); - cass::WhitelistDCPolicy policy(cass::Memory::allocate(), whitelist_dcs); + cass::WhitelistDCPolicy policy(new cass::RoundRobinPolicy(), whitelist_dcs); policy.init(cass::SharedRefPtr(), hosts, NULL); cass::ScopedPtr qp(policy.new_query_plan("ks", NULL, NULL)); @@ -1075,7 +1075,7 @@ TEST(BlacklistLoadBalancingUnitTest, Hosts) { cass::ContactPointList blacklist_hosts; blacklist_hosts.push_back("2.0.0.0"); blacklist_hosts.push_back("3.0.0.0"); - cass::BlacklistPolicy policy(cass::Memory::allocate(), blacklist_hosts); + cass::BlacklistPolicy policy(new cass::RoundRobinPolicy(), blacklist_hosts); policy.init(cass::SharedRefPtr(), hosts, NULL); cass::ScopedPtr qp(policy.new_query_plan("ks", NULL, NULL)); @@ -1096,7 +1096,7 @@ TEST(BlacklistLoadBalancingUnitTest, Datacenters) { cass::DcList blacklist_dcs; blacklist_dcs.push_back(LOCAL_DC); blacklist_dcs.push_back(REMOTE_DC); - cass::BlacklistDCPolicy policy(cass::Memory::allocate(), blacklist_dcs); + cass::BlacklistDCPolicy policy(new cass::RoundRobinPolicy(), blacklist_dcs); policy.init(cass::SharedRefPtr(), hosts, NULL); cass::ScopedPtr qp(policy.new_query_plan("ks", NULL, NULL)); diff --git a/gtests/src/unit/tests/test_metadata.cpp b/gtests/src/unit/tests/test_metadata.cpp index 5fda3095b..ad7950a82 100644 --- a/gtests/src/unit/tests/test_metadata.cpp +++ b/gtests/src/unit/tests/test_metadata.cpp @@ -23,8 +23,8 @@ cass::SharedRefPtr create_metadata(const char* column_name while (column_names[count] != NULL) { count++; } cass::ResultMetadata::Ptr metadata( - cass::Memory::allocate(count, - cass::RefBuffer::Ptr())); + new cass::ResultMetadata(count, + cass::RefBuffer::Ptr())); for (size_t i = 0; column_names[i] != NULL; ++i) { cass::ColumnDefinition def; diff --git a/gtests/src/unit/tests/test_name_resolver.cpp b/gtests/src/unit/tests/test_name_resolver.cpp index a5815507b..7a28e1ad9 100644 --- a/gtests/src/unit/tests/test_name_resolver.cpp +++ b/gtests/src/unit/tests/test_name_resolver.cpp @@ -38,8 +38,8 @@ class NameResolverUnitTest : public LoopTest { NameResolver::Ptr create(const Address& address) { return NameResolver::Ptr( - Memory::allocate(address, - bind_callback(&NameResolverUnitTest::on_resolve, this))); + new NameResolver(address, + bind_callback(&NameResolverUnitTest::on_resolve, this))); } NameResolver::Status status() const { diff --git a/gtests/src/unit/tests/test_pool.cpp b/gtests/src/unit/tests/test_pool.cpp index e2546e8d5..57649f1c9 100644 --- a/gtests/src/unit/tests/test_pool.cpp +++ b/gtests/src/unit/tests/test_pool.cpp @@ -207,8 +207,8 @@ class PoolUnitTest : public LoopTest { } virtual void on_pool_critical_error(const Address& address, - Connector::ConnectionError code, - const String& message) { + Connector::ConnectionError code, + const String& message) { switch (code) { case Connector::CONNECTION_ERROR_INVALID_PROTOCOL: status_->critical_error_invalid_protocol(); @@ -268,20 +268,21 @@ class PoolUnitTest : public LoopTest { loop()->data = NULL; } - AddressVec addresses() const { + HostMap hosts() const { mockssandra::Ipv4AddressGenerator generator; - AddressVec addresses; + HostMap hosts; for (size_t i = 0; i < NUM_NODES; ++i) { - addresses.push_back(generator.next()); + Host::Ptr host(new Host(generator.next())); + hosts[host->address()] = host; } - return addresses; + return hosts; } void run_request(const ConnectionPoolManager::Ptr& manager, const Address& address) { PooledConnection::Ptr connection = manager->find_least_busy(address); if (connection) { RequestStatus status(manager->loop(), 1); - RequestCallback::Ptr callback(Memory::allocate(&status)); + RequestCallback::Ptr callback(new RequestCallback(&status)); EXPECT_TRUE(connection->write(callback.get())) << "Unable to write request to connection " << address.to_string(); connection->flush(); // Flush requests to avoid unnecessary timeouts uv_run(loop(), UV_RUN_DEFAULT); @@ -299,7 +300,7 @@ class PoolUnitTest : public LoopTest { for (size_t i = 0; i < NUM_NODES; ++i) { PooledConnection::Ptr connection = manager->find_least_busy(generator.next()); if (connection) { - RequestCallback::Ptr callback(Memory::allocate(status)); + RequestCallback::Ptr callback(new RequestCallback(status)); if(!connection->write(callback.get())) { status->error_failed_write(); } @@ -355,12 +356,12 @@ TEST_F(PoolUnitTest, Simple) { RequestStatusWithManager status(loop()); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_connected, &status))); initializer - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(status.count(RequestStatus::SUCCESS), NUM_NODES) << status.results(); @@ -379,15 +380,16 @@ TEST_F(PoolUnitTest, Keyspace) { RequestStatusWithManager status(loop()); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_connected, &status))); - AddressVec addresses = this->addresses(); + HostMap hosts = this->hosts(); + ASSERT_EQ(hosts.size(), NUM_NODES); initializer ->with_keyspace("foo") - ->initialize(loop(), addresses); + ->initialize(loop(), hosts); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(status.count(RequestStatus::SUCCESS), NUM_NODES) << status.results(); @@ -395,12 +397,14 @@ TEST_F(PoolUnitTest, Keyspace) { ConnectionPoolManager::Ptr manager = status.manager(); ASSERT_TRUE(manager); - for (size_t i = 0; i < NUM_NODES; ++i) { - PooledConnection::Ptr connection = manager->find_least_busy(addresses[i]); + for (HostMap::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { + const Address& address = it->first; + PooledConnection::Ptr connection = manager->find_least_busy(address); if (connection) { EXPECT_EQ(connection->keyspace(), "foo"); } else { - EXPECT_TRUE(false) << "Unable to get connection for " << addresses[i].to_string(); + EXPECT_TRUE(false) << "Unable to get connection for " << address.to_string(); } } } @@ -412,16 +416,16 @@ TEST_F(PoolUnitTest, Auth) { RequestStatusWithManager status(loop()); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_connected, &status))); ConnectionPoolSettings settings; - settings.connection_settings.auth_provider.reset(Memory::allocate("cassandra", "cassandra")); + settings.connection_settings.auth_provider.reset(new PlainTextAuthProvider("cassandra", "cassandra")); initializer ->with_settings(settings) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(status.count(RequestStatus::SUCCESS), NUM_NODES) << status.results(); @@ -436,13 +440,13 @@ TEST_F(PoolUnitTest, Ssl) { RequestStatusWithManager status(loop()); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_connected, &status))); initializer ->with_settings(settings) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(status.count(RequestStatus::SUCCESS), NUM_NODES) << status.results(); @@ -453,17 +457,17 @@ TEST_F(PoolUnitTest, Listener) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); initializer ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::UP), NUM_NODES) << listener_status.results(); @@ -475,17 +479,17 @@ TEST_F(PoolUnitTest, ListenerDown) { ASSERT_EQ(cluster.start(1), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); initializer ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::UP), 1u) << listener_status.results(); @@ -499,20 +503,21 @@ TEST_F(PoolUnitTest, AddRemove) { ListenerStatus listener_status(loop()); ListenerStatus add_remove_listener_status(loop(), 1); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); - AddressVec addresses = this->addresses(); + HostMap hosts = this->hosts(); + ASSERT_EQ(hosts.size(), NUM_NODES); initializer ->with_listener(listener.get()) - ->initialize(loop(), addresses); + ->initialize(loop(), hosts); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::UP), NUM_NODES) << listener_status.results(); @@ -521,16 +526,19 @@ TEST_F(PoolUnitTest, AddRemove) { ASSERT_TRUE(manager); listener->reset(&add_remove_listener_status); - for (size_t i = 0; i < NUM_NODES; ++i) { + for (HostMap::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { + const Address& address = it->first; + const Host::Ptr& host = it->second; add_remove_listener_status.reset(); - manager->remove(addresses[i]); // Remove node + manager->remove(address); // Remove node uv_run(loop(), UV_RUN_DEFAULT); - EXPECT_FALSE(manager->find_least_busy(addresses[i])); + EXPECT_FALSE(manager->find_least_busy(address)); add_remove_listener_status.reset(); - manager->add(addresses[i]); // Add node + manager->add(host); // Add node uv_run(loop(), UV_RUN_DEFAULT); - run_request(manager, addresses[i]); + run_request(manager, address); } EXPECT_EQ(add_remove_listener_status.count(ListenerStatus::DOWN), 3u) << add_remove_listener_status.results(); @@ -543,15 +551,16 @@ TEST_F(PoolUnitTest, Reconnect) { ListenerStatus listener_status(loop()); ListenerStatus reconnect_listener_status(loop(), 1); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); - AddressVec addresses = this->addresses(); + HostMap hosts = this->hosts(); + ASSERT_EQ(hosts.size(), NUM_NODES); ConnectionPoolSettings settings; settings.reconnect_wait_time_ms = 0; // Reconnect immediately @@ -559,7 +568,7 @@ TEST_F(PoolUnitTest, Reconnect) { initializer ->with_settings(settings) ->with_listener(listener.get()) - ->initialize(loop(), addresses); + ->initialize(loop(), hosts); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::UP), NUM_NODES) << listener_status.results(); @@ -568,18 +577,22 @@ TEST_F(PoolUnitTest, Reconnect) { ASSERT_TRUE(manager); listener->reset(&reconnect_listener_status); - for (size_t i = 0; i < NUM_NODES; ++i) { + size_t node = 1; + for (HostMap::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { + const Address& address = it->first; reconnect_listener_status.reset(); - cluster.stop(i + 1); // Stop node + cluster.stop(node); // Stop node uv_run(loop(), UV_RUN_DEFAULT); - EXPECT_FALSE(manager->find_least_busy(addresses[i])); + EXPECT_FALSE(manager->find_least_busy(address)); reconnect_listener_status.reset(); - ASSERT_EQ(cluster.start(i + 1), 0); // Start node + ASSERT_EQ(cluster.start(node), 0); // Start node uv_run(loop(), UV_RUN_DEFAULT); - run_request(manager, addresses[i]); + run_request(manager, address); + ++node; } EXPECT_EQ(reconnect_listener_status.count(ListenerStatus::DOWN), 3u) << reconnect_listener_status.results(); @@ -593,11 +606,11 @@ TEST_F(PoolUnitTest, Timeout) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); @@ -607,7 +620,7 @@ TEST_F(PoolUnitTest, Timeout) { initializer ->with_settings(settings) ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::DOWN), NUM_NODES) << listener_status.results(); @@ -619,17 +632,17 @@ TEST_F(PoolUnitTest, InvalidProtocol) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( 0x7F, // Invalid protocol version bind_callback(on_pool_nop, &request_status))); initializer ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_GT(listener_status.count(ListenerStatus::CRITICAL_ERROR_INVALID_PROTOCOL), 0u) << listener_status.results(); @@ -653,18 +666,18 @@ TEST_F(PoolUnitTest, InvalidKeyspace) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); initializer ->with_keyspace("invalid") ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(listener_status.count(ListenerStatus::CRITICAL_ERROR_KEYSPACE), NUM_NODES) << listener_status.results(); @@ -675,21 +688,21 @@ TEST_F(PoolUnitTest, InvalidAuth) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); ConnectionPoolSettings settings; - settings.connection_settings.auth_provider.reset(Memory::allocate("invalid", "invalid")); + settings.connection_settings.auth_provider.reset(new PlainTextAuthProvider("invalid", "invalid")); initializer ->with_settings(settings) ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_GT(listener_status.count(ListenerStatus::CRITICAL_ERROR_AUTH), 0u) << listener_status.results(); @@ -700,11 +713,11 @@ TEST_F(PoolUnitTest, InvalidNoSsl) { ASSERT_EQ(cluster.start_all(), 0); // Start without ssl ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); @@ -717,7 +730,7 @@ TEST_F(PoolUnitTest, InvalidNoSsl) { initializer ->with_settings(settings) ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_GT(listener_status.count(ListenerStatus::CRITICAL_ERROR_SSL_HANDSHAKE), 0u) << listener_status.results(); @@ -729,11 +742,11 @@ TEST_F(PoolUnitTest, InvalidSsl) { ASSERT_EQ(cluster.start_all(), 0); ListenerStatus listener_status(loop()); - ScopedPtr listener(Memory::allocate(&listener_status)); + ScopedPtr listener(new Listener(&listener_status)); RequestStatusWithManager request_status(loop(), 0); ConnectionPoolManagerInitializer::Ptr initializer( - Memory::allocate( + new ConnectionPoolManagerInitializer( PROTOCOL_VERSION, bind_callback(on_pool_nop, &request_status))); @@ -746,7 +759,7 @@ TEST_F(PoolUnitTest, InvalidSsl) { initializer ->with_settings(settings) ->with_listener(listener.get()) - ->initialize(loop(), addresses()); + ->initialize(loop(), hosts()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_GT(listener_status.count(ListenerStatus::CRITICAL_ERROR_SSL_VERIFY), 0u) << listener_status.results(); diff --git a/gtests/src/unit/tests/test_replication_strategy.cpp b/gtests/src/unit/tests/test_replication_strategy.cpp index 97c310946..06d176047 100644 --- a/gtests/src/unit/tests/test_replication_strategy.cpp +++ b/gtests/src/unit/tests/test_replication_strategy.cpp @@ -49,7 +49,7 @@ struct MockTokenMap { cass::DatacenterMap datacenters; void init_simple_strategy(size_t replication_factor) { - cass::DataType::ConstPtr varchar_data_type(cass::Memory::allocate(CASS_VALUE_TYPE_VARCHAR)); + cass::DataType::ConstPtr varchar_data_type(new cass::DataType(CASS_VALUE_TYPE_VARCHAR)); ColumnMetadataVec column_metadata; column_metadata.push_back(ColumnMetadata("keyspace_name", varchar_data_type)); @@ -72,7 +72,7 @@ struct MockTokenMap { } void init_network_topology_strategy(ReplicationMap& replication) { - cass::DataType::ConstPtr varchar_data_type(cass::Memory::allocate(CASS_VALUE_TYPE_VARCHAR)); + cass::DataType::ConstPtr varchar_data_type(new cass::DataType(CASS_VALUE_TYPE_VARCHAR)); ColumnMetadataVec column_metadata; column_metadata.push_back(ColumnMetadata("keyspace_name", varchar_data_type)); @@ -115,7 +115,7 @@ struct MockTokenMap { cass::Host* create_host(const cass::String& address, const cass::String& rack = "", const cass::String& dc = "") { - cass::Host::Ptr host(cass::Memory::allocate(cass::Address(address, 9042))); + cass::Host::Ptr host(new cass::Host(cass::Address(address, 9042))); host->set_rack_and_dc(rack, dc); host->set_rack_and_dc_ids(rack_ids.get(rack), dc_ids.get(dc)); cass::HostSet::iterator i = hosts.find(host); diff --git a/gtests/src/unit/tests/test_request_processor.cpp b/gtests/src/unit/tests/test_request_processor.cpp index f9ed101a0..716a223b3 100644 --- a/gtests/src/unit/tests/test_request_processor.cpp +++ b/gtests/src/unit/tests/test_request_processor.cpp @@ -33,9 +33,9 @@ class RequestProcessorUnitTest : public EventLoopTest { HostMap generate_hosts() { HostMap hosts; - Host::Ptr host1(Memory::allocate(Address("127.0.0.1", PORT))); - Host::Ptr host2(Memory::allocate(Address("127.0.0.2", PORT))); - Host::Ptr host3(Memory::allocate(Address("127.0.0.3", PORT))); + Host::Ptr host1(new Host(Address("127.0.0.1", PORT))); + Host::Ptr host2(new Host(Address("127.0.0.2", PORT))); + Host::Ptr host3(new Host(Address("127.0.0.3", PORT))); hosts[host1->address()] = host1; hosts[host2->address()] = host2; hosts[host3->address()] = host3; @@ -44,17 +44,17 @@ class RequestProcessorUnitTest : public EventLoopTest { void try_request(const RequestProcessor::Ptr& processor, uint64_t wait_for_time_us = WAIT_FOR_TIME) { - ResponseFuture::Ptr response_future(Memory::allocate()); - QueryRequest::Ptr query_request(Memory::allocate("SELECT * FROM table")); + ResponseFuture::Ptr response_future(new ResponseFuture()); + QueryRequest::Ptr query_request(new QueryRequest("SELECT * FROM table")); query_request->set_is_idempotent(true); Request::ConstPtr request(query_request); - RequestHandler::Ptr request_handler(Memory::allocate(request, response_future)); + RequestHandler::Ptr request_handler(new RequestHandler(request, response_future)); processor->process_request(request_handler); ASSERT_TRUE(response_future->wait_for(wait_for_time_us)) << "Timed out waiting for response"; ASSERT_FALSE(response_future->error()) - << cass_error_desc(response_future->error()->code) << ": " - << response_future->error()->message;; + << cass_error_desc(response_future->error()->code) << ": " + << response_future->error()->message;; } class Future : public cass::Future { @@ -105,7 +105,7 @@ class RequestProcessorUnitTest : public EventLoopTest { // that a host is ready. if (processor_) { processor_->notify_host_ready( - Host::Ptr(Memory::allocate(address))); + Host::Ptr(new Host(address))); } } virtual void on_pool_down(const Address& address) { } @@ -211,12 +211,12 @@ TEST_F(RequestProcessorUnitTest, Simple) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); initializer->initialize(event_loop()); @@ -232,12 +232,12 @@ TEST_F(RequestProcessorUnitTest, CloseWithRequestsPending) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); initializer->initialize(event_loop()); @@ -248,9 +248,9 @@ TEST_F(RequestProcessorUnitTest, CloseWithRequestsPending) { RequestProcessor::Ptr processor(connect_future->processor()); for (int i = 0; i < 4096; ++i) { - ResponseFuture::Ptr response_future(Memory::allocate()); - Request::ConstPtr request(Memory::allocate("SELECT * FROM table")); - RequestHandler::Ptr request_handler(Memory::allocate(request, response_future)); + ResponseFuture::Ptr response_future(new ResponseFuture()); + Request::ConstPtr request(new QueryRequest("SELECT * FROM table")); + RequestHandler::Ptr request_handler(new RequestHandler(request, response_future)); processor->process_request(request_handler); futures.push_back(response_future); @@ -272,16 +272,16 @@ TEST_F(RequestProcessorUnitTest, Auth) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.connection_settings.auth_provider.reset( - Memory::allocate("cassandra", "cassandra")); + new PlainTextAuthProvider("cassandra", "cassandra")); initializer ->with_settings(settings) @@ -301,12 +301,12 @@ TEST_F(RequestProcessorUnitTest, Ssl) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); initializer ->with_settings(settings) @@ -327,19 +327,19 @@ TEST_F(RequestProcessorUnitTest, NotifyAddRemoveHost) { Host::Ptr to_add_remove(hosts.begin()->second); hosts.erase(to_add_remove->address()); // Remove to add/remove it back later - Future::Ptr connect_future(Memory::allocate()); - Future::Ptr up_future(Memory::allocate()); - Future::Ptr down_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + Future::Ptr up_future(new Future()); + Future::Ptr down_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.reconnect_wait_time_ms = 1; // Reconnect immediately - UpDownListener::Ptr listener(Memory::allocate(up_future, down_future, to_add_remove)); + UpDownListener::Ptr listener(new UpDownListener(up_future, down_future, to_add_remove)); initializer ->with_settings(settings) @@ -364,18 +364,18 @@ TEST_F(RequestProcessorUnitTest, CloseDuringReconnect) { HostMap hosts(generate_hosts()); - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.reconnect_wait_time_ms = 100000; // Make sure we're reconnecting when we close. - CloseListener::Ptr listener(Memory::allocate(close_future)); + CloseListener::Ptr listener(new CloseListener(close_future)); initializer ->with_settings(settings) @@ -403,15 +403,15 @@ TEST_F(RequestProcessorUnitTest, CloseDuringAddNewHost) { Host::Ptr to_add(hosts.begin()->second); hosts.erase(to_add->address()); // Remove to add it back later - Future::Ptr close_future(Memory::allocate()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr close_future(new Future()); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); - CloseListener::Ptr listener(Memory::allocate(close_future)); + CloseListener::Ptr listener(new CloseListener(close_future)); initializer ->with_listener(listener.get()) @@ -436,16 +436,16 @@ TEST_F(RequestProcessorUnitTest, PoolDown) { Host::Ptr target_host(hosts.find(Address("127.0.0.1", PORT))->second); ASSERT_TRUE(target_host); - Future::Ptr connect_future(Memory::allocate()); - Future::Ptr up_future(Memory::allocate()); - Future::Ptr down_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + Future::Ptr up_future(new Future()); + Future::Ptr down_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); - UpDownListener::Ptr listener(Memory::allocate(up_future, down_future, target_host)); + UpDownListener::Ptr listener(new UpDownListener(up_future, down_future, target_host)); initializer ->with_listener(listener.get()) @@ -470,19 +470,19 @@ TEST_F(RequestProcessorUnitTest, PoolUp) { Host::Ptr target_host(hosts.find(Address("127.0.0.1", PORT))->second); ASSERT_TRUE(target_host); - Future::Ptr connect_future(Memory::allocate()); - Future::Ptr up_future(Memory::allocate()); - Future::Ptr down_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + Future::Ptr up_future(new Future()); + Future::Ptr down_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.reconnect_wait_time_ms = 1; // Reconnect immediately - UpDownListener::Ptr listener(Memory::allocate(up_future, down_future, target_host)); + UpDownListener::Ptr listener(new UpDownListener(up_future, down_future, target_host)); initializer ->with_settings(settings) @@ -504,16 +504,16 @@ TEST_F(RequestProcessorUnitTest, InvalidAuth) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.connection_settings.auth_provider.reset( - Memory::allocate("invalid", "invalid")); + new PlainTextAuthProvider("invalid", "invalid")); CriticalErrorListener listener; // Use stack allocation because it's never closed @@ -535,12 +535,12 @@ TEST_F(RequestProcessorUnitTest, InvalidSsl) { HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); SslContext::Ptr ssl_context(SslContextFactory::create()); // No trusted cert @@ -572,24 +572,24 @@ TEST_F(RequestProcessorUnitTest, RollingRestart) { outage_plan.start_node(node); } - Future::Ptr close_future(Memory::allocate()); - CloseListener::Ptr listener(Memory::allocate(close_future)); + Future::Ptr close_future(new Future()); + CloseListener::Ptr listener(new CloseListener(close_future)); HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); RequestProcessorSettings settings; settings.connection_pool_settings.reconnect_wait_time_ms = 10; // Reconnect immediately initializer - ->with_settings(settings) - ->with_listener(listener.get()) - ->initialize(event_loop()); + ->with_settings(settings) + ->with_listener(listener.get()) + ->initialize(event_loop()); ASSERT_TRUE(connect_future->wait_for(WAIT_FOR_TIME)); EXPECT_FALSE(connect_future->error()); @@ -608,28 +608,28 @@ TEST_F(RequestProcessorUnitTest, NoHostsAvailable) { mockssandra::SimpleCluster cluster(simple(), NUM_NODES); ASSERT_EQ(cluster.start_all(), 0); - Future::Ptr close_future(Memory::allocate()); - CloseListener::Ptr listener(Memory::allocate(close_future)); + Future::Ptr close_future(new Future()); + CloseListener::Ptr listener(new CloseListener(close_future)); HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); initializer - ->with_listener(listener.get()) - ->initialize(event_loop()); + ->with_listener(listener.get()) + ->initialize(event_loop()); ASSERT_TRUE(connect_future->wait_for(WAIT_FOR_TIME)); EXPECT_FALSE(connect_future->error()); RequestProcessor::Ptr processor(connect_future->processor()); - ResponseFuture::Ptr response_future(Memory::allocate()); - Request::ConstPtr request(Memory::allocate("SELECT * FROM table")); - RequestHandler::Ptr request_handler(Memory::allocate(request, response_future)); + ResponseFuture::Ptr response_future(new ResponseFuture()); + Request::ConstPtr request(new QueryRequest("SELECT * FROM table")); + RequestHandler::Ptr request_handler(new RequestHandler(request, response_future)); cluster.stop_all(); @@ -648,30 +648,30 @@ TEST_F(RequestProcessorUnitTest, RequestTimeout) { mockssandra::SimpleCluster cluster(builder.build(), NUM_NODES); ASSERT_EQ(cluster.start_all(), 0); - Future::Ptr close_future(Memory::allocate()); - CloseListener::Ptr listener(Memory::allocate(close_future)); + Future::Ptr close_future(new Future()); + CloseListener::Ptr listener(new CloseListener(close_future)); HostMap hosts(generate_hosts()); - Future::Ptr connect_future(Memory::allocate()); - RequestProcessorInitializer::Ptr initializer(Memory::allocate(hosts.begin()->second, - PROTOCOL_VERSION, - hosts, - TokenMap::Ptr(), - bind_callback(on_connected, connect_future.get()))); + Future::Ptr connect_future(new Future()); + RequestProcessorInitializer::Ptr initializer(new RequestProcessorInitializer(hosts.begin()->second, + PROTOCOL_VERSION, + hosts, + TokenMap::Ptr(), + bind_callback(on_connected, connect_future.get()))); initializer - ->with_listener(listener.get()) - ->initialize(event_loop()); + ->with_listener(listener.get()) + ->initialize(event_loop()); ASSERT_TRUE(connect_future->wait_for(WAIT_FOR_TIME)); EXPECT_FALSE(connect_future->error()); RequestProcessor::Ptr processor(connect_future->processor()); - ResponseFuture::Ptr response_future(Memory::allocate()); - QueryRequest::Ptr query_request(Memory::allocate("SELECT * FROM table")); + ResponseFuture::Ptr response_future(new ResponseFuture()); + QueryRequest::Ptr query_request(new QueryRequest("SELECT * FROM table")); query_request->set_request_timeout_ms(50); // Small request timeout window (smaller than delay) Request::ConstPtr request(query_request); - RequestHandler::Ptr request_handler(Memory::allocate(request, response_future)); + RequestHandler::Ptr request_handler(new RequestHandler(request, response_future)); processor->process_request(request_handler); ASSERT_TRUE(response_future->wait_for(WAIT_FOR_TIME)); diff --git a/gtests/src/unit/tests/test_resolver.cpp b/gtests/src/unit/tests/test_resolver.cpp index 1557c7f67..2969261fa 100644 --- a/gtests/src/unit/tests/test_resolver.cpp +++ b/gtests/src/unit/tests/test_resolver.cpp @@ -36,14 +36,14 @@ class ResolverUnitTest : public LoopTest { Resolver::Ptr create(const String& hostname, int port = 9042) { return Resolver::Ptr( - Memory::allocate(hostname, - port, - bind_callback(&ResolverUnitTest::on_resolve, this))); + new Resolver(hostname, + port, + bind_callback(&ResolverUnitTest::on_resolve, this))); } MultiResolver::Ptr create_multi() { return MultiResolver::Ptr( - Memory::allocate(bind_callback(&ResolverUnitTest::on_multi_resolve, this))); + new MultiResolver(bind_callback(&ResolverUnitTest::on_multi_resolve, this))); } Resolver::Status status() const { diff --git a/gtests/src/unit/tests/test_retry_policies.cpp b/gtests/src/unit/tests/test_retry_policies.cpp index b06c28507..bad5f58fc 100644 --- a/gtests/src/unit/tests/test_retry_policies.cpp +++ b/gtests/src/unit/tests/test_retry_policies.cpp @@ -213,7 +213,7 @@ TEST(RetryPoliciesUnitTest, Fallthrough) TEST(RetryPoliciesUnitTest, Logging) { cass::SharedRefPtr policy( - cass::Memory::allocate()); + new cass::DefaultRetryPolicy()); cass::LoggingRetryPolicy logging_policy(policy); cass_log_set_level(CASS_LOG_INFO); check_default(logging_policy); diff --git a/gtests/src/unit/tests/test_session.cpp b/gtests/src/unit/tests/test_session.cpp index 1e6f2f548..082686e93 100644 --- a/gtests/src/unit/tests/test_session.cpp +++ b/gtests/src/unit/tests/test_session.cpp @@ -60,8 +60,8 @@ class SessionUnitTest : public EventLoopTest { cass::Future::Ptr connect_future(session->connect(config)); ASSERT_TRUE(connect_future->wait_for(wait_for_time_us)) << "Timed out waiting for session to connect"; ASSERT_FALSE(connect_future->error()) - << cass_error_desc(connect_future->error()->code) << ": " - << connect_future->error()->message; + << cass_error_desc(connect_future->error()->code) << ": " + << connect_future->error()->message; } static void connect(cass::Session* session, @@ -86,19 +86,19 @@ class SessionUnitTest : public EventLoopTest { cass::Future::Ptr close_future(session->close()); ASSERT_TRUE(close_future->wait_for(wait_for_time_us)) << "Timed out waiting for session to close"; ASSERT_FALSE(close_future->error()) - << cass_error_desc(close_future->error()->code) << ": " - << close_future->error()->message; + << cass_error_desc(close_future->error()->code) << ": " + << close_future->error()->message; } static void query(cass::Session* session) { - cass::QueryRequest::Ptr request(cass::Memory::allocate("blah", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("blah", 0)); request->set_is_idempotent(true); cass::Future::Ptr future = session->execute(request, NULL); ASSERT_TRUE(future->wait_for(WAIT_FOR_TIME)) << "Timed out executing query"; ASSERT_FALSE(future->error()) - << cass_error_desc(future->error()->code) << ": " - << future->error()->message; + << cass_error_desc(future->error()->code) << ": " + << future->error()->message; } // uv_thread_create @@ -150,8 +150,8 @@ class SessionUnitTest : public EventLoopTest { TestHostListener() { events_.push_back( - HostEventFuture::Ptr( - Memory::allocate())); + HostEventFuture::Ptr( + new HostEventFuture())); uv_mutex_init(&mutex_); } @@ -177,7 +177,7 @@ class SessionUnitTest : public EventLoopTest { HostEventFuture::Event wait_for_event(uint64_t timeout_us) { HostEventFuture::Event event(front()->wait_for_event(timeout_us)); - pop_front(); + if (event.first != HostEventFuture::INVALID) pop_front(); return event; } @@ -204,8 +204,8 @@ class SessionUnitTest : public EventLoopTest { cass::ScopedMutex lock(&mutex_); events_.back()->set_event(type, host->address()); events_.push_back( - HostEventFuture::Ptr( - Memory::allocate())); + HostEventFuture::Ptr( + new HostEventFuture())); } private: @@ -215,7 +215,7 @@ class SessionUnitTest : public EventLoopTest { }; TEST_F(SessionUnitTest, ExecuteQueryNotConnected) { - cass::QueryRequest::Ptr request(cass::Memory::allocate("blah", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("blah", 0)); cass::Session session; cass::Future::Ptr future = session.execute(request, NULL); @@ -225,10 +225,10 @@ TEST_F(SessionUnitTest, ExecuteQueryNotConnected) { TEST_F(SessionUnitTest, InvalidKeyspace) { mockssandra::SimpleRequestHandlerBuilder builder; builder.on(mockssandra::OPCODE_QUERY) - .system_local() - .system_peers() - .use_keyspace("blah") - .empty_rows_result(1); + .system_local() + .system_peers() + .use_keyspace("blah") + .empty_rows_result(1); mockssandra::SimpleCluster cluster(builder.build()); ASSERT_EQ(cluster.start_all(), 0); @@ -249,7 +249,7 @@ TEST_F(SessionUnitTest, InvalidDataCenter) { cass::Config config; config.contact_points().push_back("127.0.0.1"); - config.set_load_balancing_policy(cass::Memory::allocate( + config.set_load_balancing_policy(new cass::DCAwarePolicy( "invalid_data_center", 0, false)); @@ -270,7 +270,7 @@ TEST_F(SessionUnitTest, InvalidLocalAddress) { cass::Config config; config.set_local_address(Address("1.1.1.1", PORT)); // Invalid config.contact_points().push_back("127.0.0.1"); - config.set_load_balancing_policy(cass::Memory::allocate( + config.set_load_balancing_policy(new cass::DCAwarePolicy( "invalid_data_center", 0, false)); @@ -350,7 +350,7 @@ TEST_F(SessionUnitTest, ExecuteQueryWithCompleteOutage) { // Full outage cluster.stop_all(); - cass::QueryRequest::Ptr request(cass::Memory::allocate("blah", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("blah", 0)); cass::Future::Ptr future = session.execute(request, NULL); ASSERT_TRUE(future->wait_for(WAIT_FOR_TIME)); ASSERT_TRUE(future->error()); @@ -381,7 +381,7 @@ TEST_F(SessionUnitTest, ExecuteQueryWithCompleteOutageSpinDown) { cluster.stop(2); // Full outage - cass::QueryRequest::Ptr request(cass::Memory::allocate("blah", 0)); + cass::QueryRequest::Ptr request(new cass::QueryRequest("blah", 0)); cass::Future::Ptr future = session.execute(request, NULL); ASSERT_TRUE(future->wait_for(WAIT_FOR_TIME)); ASSERT_EQ(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE, future->error()->code); @@ -456,7 +456,7 @@ TEST_F(SessionUnitTest, HostListener) { mockssandra::SimpleCluster cluster(simple(), 2); ASSERT_EQ(cluster.start_all(), 0); - TestHostListener::Ptr listener(cass::Memory::allocate()); + TestHostListener::Ptr listener(new TestHostListener()); cass::Config config; config.set_reconnect_wait_time(100); // Reconnect immediately @@ -466,7 +466,20 @@ TEST_F(SessionUnitTest, HostListener) { cass::Session session; connect(config, &session); - EXPECT_EQ(0u, listener->event_count()); + { // Initial nodes available from peers table + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } { cluster.remove(1); @@ -506,3 +519,150 @@ TEST_F(SessionUnitTest, HostListener) { ASSERT_EQ(0u, listener->event_count()); } + +TEST_F(SessionUnitTest, HostListenerDCAwareLocal) { + mockssandra::SimpleCluster cluster(simple(), 2, 1); + ASSERT_EQ(cluster.start_all(), 0); + + TestHostListener::Ptr listener(new TestHostListener()); + + cass::Config config; + config.set_reconnect_wait_time(100); // Reconnect immediately + config.contact_points().push_back("127.0.0.1"); + config.set_host_listener(listener); + + cass::Session session; + connect(config, &session); + + { // Initial nodes available from peers table + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + { // Node 3 is DC2 should be ignored + cluster.stop(3); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::INVALID, + Address()), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + close(&session); + + ASSERT_EQ(0u, listener->event_count()); +} + +// TODO: Remove HostListenerDCAwareRemote after remote DC settings are removed from API +TEST_F(SessionUnitTest, HostListenerDCAwareRemote) { + mockssandra::SimpleCluster cluster(simple(), 2, 1); + ASSERT_EQ(cluster.start_all(), 0); + + TestHostListener::Ptr listener(new TestHostListener()); + + cass::Config config; + config.set_reconnect_wait_time(100); // Reconnect immediately + config.contact_points().push_back("127.0.0.1"); + config.set_load_balancing_policy(new cass::DCAwarePolicy( + "dc1", + 1, + false)); + config.set_host_listener(listener); + + cass::Session session; + connect(config, &session); + + { // Initial nodes available from peers table + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.3", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.3", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + { + cluster.stop(3); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::STOP_NODE, + Address("127.0.0.3", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + close(&session); + + ASSERT_EQ(0u, listener->event_count()); +} + +TEST_F(SessionUnitTest, HostListenerNodeDown) { + mockssandra::SimpleCluster cluster(simple(), 3); + ASSERT_EQ(cluster.start(1), 0); + ASSERT_EQ(cluster.start(3), 0); + + TestHostListener::Ptr listener(new TestHostListener()); + + cass::Config config; + config.set_reconnect_wait_time(100); // Reconnect immediately + config.contact_points().push_back("127.0.0.1"); + config.set_host_listener(listener); + + cass::Session session; + connect(config, &session); + + { // Initial nodes available from peers table + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.1", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::ADD_NODE, + Address("127.0.0.3", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.3", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + { // Node 2 connection should not be established (node down event) + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::STOP_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + { + cluster.start(2); + EXPECT_EQ(HostEventFuture::Event(HostEventFuture::START_NODE, + Address("127.0.0.2", 9042)), + listener->wait_for_event(WAIT_FOR_TIME)); + } + + close(&session); + + ASSERT_EQ(0u, listener->event_count()); +} diff --git a/gtests/src/unit/tests/test_socket.cpp b/gtests/src/unit/tests/test_socket.cpp index eb7d73cda..c17182647 100644 --- a/gtests/src/unit/tests/test_socket.cpp +++ b/gtests/src/unit/tests/test_socket.cpp @@ -42,7 +42,7 @@ class TestSocketHandler : public SocketHandler { } virtual void on_write(Socket* socket, int status, SocketRequest* request) { - Memory::deallocate(request); + delete request; } virtual void on_close() { } @@ -65,7 +65,7 @@ class SslTestSocketHandler : public SslSocketHandler { } virtual void on_write(Socket* socket, int status, SocketRequest* request) { - Memory::deallocate(request); + delete request; } virtual void on_close() { } @@ -116,15 +116,15 @@ class SocketUnitTest : public LoopTest { if (connector->error_code() == SocketConnector::SOCKET_OK) { if (connector->ssl_session()) { socket->set_handler( - Memory::allocate( + new SslTestSocketHandler( connector->ssl_session().release(), result)); } else { socket->set_handler( - Memory::allocate(result)); + new TestSocketHandler(result)); } const char* data = "The socket is successfully connected and wrote data - "; - socket->write(Memory::allocate(Buffer(data, strlen(data)))); - socket->write(Memory::allocate(Buffer("Closed", sizeof("Closed") - 1))); + socket->write(new BufferSocketRequest(Buffer(data, strlen(data)))); + socket->write(new BufferSocketRequest(Buffer("Closed", sizeof("Closed") - 1))); socket->flush(); } else { ASSERT_TRUE(false) << "Failed to connect: " << connector->error_message(); @@ -155,13 +155,13 @@ class SocketUnitTest : public LoopTest { const char* service) { if(status) { FAIL() - << "Unable to Execute Test SocketUnitTest.SslVerifyIdentityDns: " - << "Add /etc/hosts entry " << SSL_VERIFY_PEER_DNS_IP_ADDRESS << "\t" - << SSL_VERIFY_PEER_DNS_ABSOLUTE_HOSTNAME; + << "Unable to Execute Test SocketUnitTest.SslVerifyIdentityDns: " + << "Add /etc/hosts entry " << SSL_VERIFY_PEER_DNS_IP_ADDRESS << "\t" + << SSL_VERIFY_PEER_DNS_ABSOLUTE_HOSTNAME; } else if (String(hostname) != String(SSL_VERIFY_PEER_DNS_ABSOLUTE_HOSTNAME)) { FAIL() - << "Invalid /etc/hosts entry for: '" << hostname << "' != '" - << SSL_VERIFY_PEER_DNS_ABSOLUTE_HOSTNAME << "'"; + << "Invalid /etc/hosts entry for: '" << hostname << "' != '" + << SSL_VERIFY_PEER_DNS_ABSOLUTE_HOSTNAME << "'"; } } @@ -173,8 +173,8 @@ TEST_F(SocketUnitTest, Simple) { listen(); String result; - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_connected, &result))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_connected, &result))); connector->connect(loop()); @@ -189,12 +189,12 @@ TEST_F(SocketUnitTest, Ssl) { SocketSettings settings(use_ssl()); String result; - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_connected, &result))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_connected, &result))); connector->with_settings(settings) - ->connect(loop()); + ->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -203,8 +203,8 @@ TEST_F(SocketUnitTest, Ssl) { TEST_F(SocketUnitTest, Refused) { bool is_refused = false; - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_refused, &is_refused))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_refused, &is_refused))); connector->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -222,8 +222,8 @@ TEST_F(SocketUnitTest, SslClose) { bool is_closed = false; for (size_t i = 0; i < 10; ++i) { - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_closed, &is_closed))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_closed, &is_closed))); connector ->with_settings(settings) @@ -243,8 +243,8 @@ TEST_F(SocketUnitTest, Cancel) { bool is_canceled = false; for (size_t i = 0; i < 10; ++i) { - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_canceled, &is_canceled))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_canceled, &is_canceled))); connector->connect(loop()); connectors.push_back(connector); } @@ -270,10 +270,10 @@ TEST_F(SocketUnitTest, SslCancel) { bool is_canceled = false; for (size_t i = 0; i < 10; ++i) { - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_canceled, &is_canceled))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_canceled, &is_canceled))); connector->with_settings(settings) - ->connect(loop()); + ->connect(loop()); connectors.push_back(connector); } @@ -296,11 +296,11 @@ TEST_F(SocketUnitTest, SslVerifyIdentity) { settings.ssl_context->set_verify_flags(CASS_SSL_VERIFY_PEER_IDENTITY); String result; - SocketConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888), - cass::bind_callback(on_socket_connected, &result))); + SocketConnector::Ptr connector(new SocketConnector(Address("127.0.0.1", 8888), + cass::bind_callback(on_socket_connected, &result))); connector->with_settings(settings) - ->connect(loop()); + ->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -329,13 +329,13 @@ TEST_F(SocketUnitTest, SslVerifyIdentityDns) { settings.ssl_context->set_verify_flags(CASS_SSL_VERIFY_PEER_IDENTITY_DNS); String result; - SocketConnector::Ptr connector(Memory::allocate(Address(SSL_VERIFY_PEER_DNS_IP_ADDRESS, 8888), - cass::bind_callback(on_socket_connected, &result))); + SocketConnector::Ptr connector(new SocketConnector(Address(SSL_VERIFY_PEER_DNS_IP_ADDRESS, 8888), + cass::bind_callback(on_socket_connected, &result))); connector->with_settings(settings) - ->connect(loop()); + ->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); EXPECT_EQ(result, "The socket is successfully connected and wrote data - Closed"); -} \ No newline at end of file +} diff --git a/gtests/src/unit/tests/test_startup_options.cpp b/gtests/src/unit/tests/test_startup_options.cpp index e4ad38a26..d7007cb74 100644 --- a/gtests/src/unit/tests/test_startup_options.cpp +++ b/gtests/src/unit/tests/test_startup_options.cpp @@ -19,11 +19,20 @@ #include "driver_info.hpp" #include "query_request.hpp" #include "session.hpp" - +#include "testing.hpp" #define APPLICATION_NAME "DataStax C/C++ Test Harness" #define APPLICATION_VERSION "1.0.0" +inline bool operator==(const CassUuid& rhs, const CassUuid& lhs) { + return rhs.clock_seq_and_node == lhs.clock_seq_and_node && + rhs.time_and_version == lhs.time_and_version; +} + +inline bool operator!=(const CassUuid& rhs, const CassUuid& lhs) { + return !(rhs == lhs); +} + class StartupRequestUnitTest : public Unit { public: void TearDown() { @@ -31,6 +40,7 @@ class StartupRequestUnitTest : public Unit { Unit::TearDown(); } + cass::Session& session() { return session_; } const cass::String& client_id() const { return client_id_; } cass::Config& config() { return config_; } const mockssandra::RequestHandler* simple_with_client_options() { @@ -57,7 +67,7 @@ class StartupRequestUnitTest : public Unit { } cass::Map client_options() { - cass::SharedRefPtr request(cass::Memory::allocate(CLIENT_OPTIONS_QUERY, 0)); + cass::SharedRefPtr request(new cass::QueryRequest(CLIENT_OPTIONS_QUERY, 0)); cass::ResponseFuture::Ptr future = static_cast(session_.execute(request, NULL)); EXPECT_TRUE(future->wait_for(WAIT_FOR_TIME)) << "Timed out executing query"; EXPECT_FALSE(future->error()) @@ -129,3 +139,27 @@ TEST_F(StartupRequestUnitTest, Application) { ASSERT_EQ(cass::driver_name(), options["DRIVER_NAME"]); ASSERT_EQ(cass::driver_version(), options["DRIVER_VERSION"]); } + +TEST_F(StartupRequestUnitTest, SetClientId) { + mockssandra::SimpleCluster cluster(simple_with_client_options()); + ASSERT_EQ(cluster.start_all(), 0); + + CassUuid generated_client_id = session().client_id(); + CassUuid assigned_client_id; + ASSERT_EQ(CASS_OK, + cass_uuid_from_string("03398c99-c635-4fad-b30a-3b2c49f785c2", + &assigned_client_id)); + config().set_client_id(assigned_client_id); + + connect(); + CassUuid current_client_id = session().client_id(); + ASSERT_EQ(assigned_client_id, current_client_id); + ASSERT_NE(generated_client_id, current_client_id); + cass::Map options = client_options(); + ASSERT_EQ(4u, options.size()); + + ASSERT_EQ("03398c99-c635-4fad-b30a-3b2c49f785c2", options["CLIENT_ID"]); + ASSERT_EQ(CASS_DEFAULT_CQL_VERSION, options["CQL_VERSION"]); + ASSERT_EQ(cass::driver_name(), options["DRIVER_NAME"]); + ASSERT_EQ(cass::driver_version(), options["DRIVER_VERSION"]); +} \ No newline at end of file diff --git a/gtests/src/unit/tests/test_statement.cpp b/gtests/src/unit/tests/test_statement.cpp index 9c99f5b7c..7149f197c 100644 --- a/gtests/src/unit/tests/test_statement.cpp +++ b/gtests/src/unit/tests/test_statement.cpp @@ -70,7 +70,7 @@ TEST_F(StatementUnitTest, SetHost) { for (int i = 0; i < 2; ++i) { cass::Address expected_host(gen.next()); - cass::Statement::Ptr request(cass::Memory::allocate(SELECT_LOCAL, 0)); + cass::Statement::Ptr request(new cass::QueryRequest(SELECT_LOCAL, 0)); request->set_host(expected_host); cass::ResponseFuture::Ptr future(session.execute(cass::Request::ConstPtr(request))); @@ -91,7 +91,7 @@ TEST_F(StatementUnitTest, SetHostWithInvalidPort) { cass::Address expected_host(cass::Address("127.0.0.1", 8888)); // Invalid port - cass::Statement::Ptr request(cass::Memory::allocate(SELECT_LOCAL, 0)); + cass::Statement::Ptr request(new cass::QueryRequest(SELECT_LOCAL, 0)); request->set_host(expected_host); cass::ResponseFuture::Ptr future(session.execute(cass::Request::ConstPtr(request))); @@ -111,7 +111,7 @@ TEST_F(StatementUnitTest, SetHostWhereHostIsDown) { cass::Address expected_host(cass::Address("127.0.0.1", 9042)); - cass::Statement::Ptr request(cass::Memory::allocate(SELECT_LOCAL, 0)); + cass::Statement::Ptr request(new cass::QueryRequest(SELECT_LOCAL, 0)); request->set_host(expected_host); cass::ResponseFuture::Ptr future(session.execute(cass::Request::ConstPtr(request))); diff --git a/gtests/src/unit/tests/test_tcp_connector.cpp b/gtests/src/unit/tests/test_tcp_connector.cpp index 76e7af864..726f7c1ca 100644 --- a/gtests/src/unit/tests/test_tcp_connector.cpp +++ b/gtests/src/unit/tests/test_tcp_connector.cpp @@ -65,28 +65,28 @@ class TcpConnectorUnitTest : public LoopTest { }; TEST_F(TcpConnectorUnitTest, Simple) { - TcpConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888))); + TcpConnector::Ptr connector(new TcpConnector(Address("127.0.0.1", 8888))); connect(connector); run_loop(); EXPECT_EQ(TcpConnector::SUCCESS, status()); } TEST_F(TcpConnectorUnitTest, Invalid) { - TcpConnector::Ptr connector(Memory::allocate(Address("127.99.0.99", 8888))); + TcpConnector::Ptr connector(new TcpConnector(Address("127.99.0.99", 8888))); connect(connector); run_loop(); EXPECT_EQ(TcpConnector::FAILED_TO_CONNECT, status()); } TEST_F(TcpConnectorUnitTest, InvalidPort) { - TcpConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 9999))); + TcpConnector::Ptr connector(new TcpConnector(Address("127.0.0.1", 9999))); connect(connector); run_loop(); EXPECT_EQ(TcpConnector::FAILED_TO_CONNECT, status()); } TEST_F(TcpConnectorUnitTest, Cancel) { - TcpConnector::Ptr connector(Memory::allocate(Address("127.0.0.1", 8888))); + TcpConnector::Ptr connector(new TcpConnector(Address("127.0.0.1", 8888))); connect(connector); connector->cancel(); run_loop(); diff --git a/gtests/src/unit/tests/test_tracing.cpp b/gtests/src/unit/tests/test_tracing.cpp index 1f3f55574..d1572398b 100644 --- a/gtests/src/unit/tests/test_tracing.cpp +++ b/gtests/src/unit/tests/test_tracing.cpp @@ -53,7 +53,7 @@ TEST_F(TracingUnitTest, Simple) { connect(); - cass::Statement::Ptr request(cass::Memory::allocate("blah", 0)); + cass::Statement::Ptr request(new cass::QueryRequest("blah", 0)); request->set_tracing(true); cass::ResponseFuture::Ptr future(session.execute(cass::Request::ConstPtr(request))); @@ -79,7 +79,7 @@ TEST_F(TracingUnitTest, DataNotAvailble) { connect(); - cass::Statement::Ptr request(cass::Memory::allocate("blah", 0)); + cass::Statement::Ptr request(new cass::QueryRequest("blah", 0)); request->set_tracing(true); add_logging_critera("Tracing data not available after 15 ms"); @@ -111,7 +111,7 @@ TEST_F(TracingUnitTest, RequestTimeout) { config.set_max_tracing_wait_time_ms(500); connect(config); - cass::Statement::Ptr request(cass::Memory::allocate("blah", 0)); + cass::Statement::Ptr request(new cass::QueryRequest("blah", 0)); request->set_request_timeout_ms(100); request->set_tracing(true); @@ -142,7 +142,7 @@ TEST_F(TracingUnitTest, QueryError) { connect(); - cass::Statement::Ptr request(cass::Memory::allocate("blah", 0)); + cass::Statement::Ptr request(new cass::QueryRequest("blah", 0)); request->set_tracing(true); add_logging_critera("Chained error response 'Invalid query' (0x02002200) for query " diff --git a/gtests/src/unit/tests/test_value.cpp b/gtests/src/unit/tests/test_value.cpp index 006f3fd5c..93cbded13 100644 --- a/gtests/src/unit/tests/test_value.cpp +++ b/gtests/src/unit/tests/test_value.cpp @@ -16,7 +16,6 @@ #include -#include "memory.hpp" #include "value.hpp" #include "cassandra.h" @@ -25,7 +24,7 @@ // The following CassValue's are used in tests as "bad data". // Create a CassValue representing a text type. -static cass::DataType::ConstPtr s_text_type(cass::Memory::allocate(CASS_VALUE_TYPE_TEXT)); +static cass::DataType::ConstPtr s_text_type(new cass::DataType(CASS_VALUE_TYPE_TEXT)); static cass::Value s_text_value_Value(s_text_type, cass::Decoder(NULL, 0)); static CassValue* s_text_value = CassValue::to(&s_text_value_Value); @@ -36,7 +35,7 @@ TEST(ValueUnitTest, Bad##ST) \ T output; \ EXPECT_EQ(cass_value_get_##ST(s_text_value, &output), \ CASS_ERROR_LIB_INVALID_VALUE_TYPE); \ - cass::DataType::ConstPtr data_type(cass::Memory::allocate(CASS_VALUE_TYPE_##SLT)); \ + cass::DataType::ConstPtr data_type(new cass::DataType(CASS_VALUE_TYPE_##SLT)); \ cass::Value null_value(data_type); \ EXPECT_EQ(cass_value_get_##ST(NULL, &output), \ CASS_ERROR_LIB_NULL_VALUE); \ @@ -78,7 +77,7 @@ TEST(ValueUnitTest, BadString) TEST(ValueUnitTest, BadInet) { CassInet inet; - cass::DataType::ConstPtr data_type(cass::Memory::allocate(CASS_VALUE_TYPE_INET)); + cass::DataType::ConstPtr data_type(new cass::DataType(CASS_VALUE_TYPE_INET)); EXPECT_EQ(cass_value_get_inet(NULL, &inet), CASS_ERROR_LIB_NULL_VALUE); @@ -99,7 +98,7 @@ TEST(ValueUnitTest, BadDuration) EXPECT_EQ(cass_value_get_duration(s_text_value, &months, &days, &nanos), CASS_ERROR_LIB_INVALID_VALUE_TYPE); - cass::DataType::ConstPtr data_type(cass::Memory::allocate(CASS_VALUE_TYPE_DURATION)); + cass::DataType::ConstPtr data_type(new cass::DataType(CASS_VALUE_TYPE_DURATION)); cass::Value invalid_value(data_type, cass::Decoder("", 0)); EXPECT_EQ(cass_value_get_duration(CassValue::to(&invalid_value), &months, &days, &nanos), CASS_ERROR_LIB_NOT_ENOUGH_DATA); @@ -113,7 +112,7 @@ TEST(ValueUnitTest, BadDecimal) EXPECT_EQ(cass_value_get_decimal(s_text_value, &varint, &varint_size, &scale), CASS_ERROR_LIB_INVALID_VALUE_TYPE); - cass::DataType::ConstPtr data_type(cass::Memory::allocate(CASS_VALUE_TYPE_DECIMAL)); + cass::DataType::ConstPtr data_type(new cass::DataType(CASS_VALUE_TYPE_DECIMAL)); cass::Value invalid_value(data_type, cass::Decoder("", 0)); EXPECT_EQ(cass_value_get_decimal(CassValue::to(&invalid_value), &varint, &varint_size, &scale), CASS_ERROR_LIB_NOT_ENOUGH_DATA); diff --git a/gtests/src/unit/tests/test_wait_for_handler.cpp b/gtests/src/unit/tests/test_wait_for_handler.cpp index 40d4f948b..105f4c65f 100644 --- a/gtests/src/unit/tests/test_wait_for_handler.cpp +++ b/gtests/src/unit/tests/test_wait_for_handler.cpp @@ -33,10 +33,10 @@ class WaitForHandlerUnitTest : public LoopTest { TestWaitForHandler(uint64_t max_wait_time = 2000, uint64_t retry_wait_time = 200) : WaitForHandler(RequestHandler::Ptr( - Memory::allocate( - QueryRequest::Ptr(Memory::allocate("")), - ResponseFuture::Ptr(Memory::allocate()))), - Host::Ptr(Memory::allocate(Address())), + new RequestHandler( + QueryRequest::Ptr(new QueryRequest("")), + ResponseFuture::Ptr(new ResponseFuture()))), + Host::Ptr(new Host(Address())), Response::Ptr(), max_wait_time, retry_wait_time) { } virtual RequestCallback::Ptr callback() = 0; @@ -67,8 +67,8 @@ class WaitForHandlerUnitTest : public LoopTest { public: virtual RequestCallback::Ptr callback() { WaitforRequestVec requests; - QueryRequest::Ptr local_request(Memory::allocate("SELECT * FROM system.local WHERE key='local'")); - QueryRequest::Ptr peers_request(Memory::allocate("SELECT * FROM system.peers")); + QueryRequest::Ptr local_request(new QueryRequest("SELECT * FROM system.local WHERE key='local'")); + QueryRequest::Ptr peers_request(new QueryRequest("SELECT * FROM system.peers")); local_request->set_is_idempotent(true); peers_request->set_is_idempotent(true); requests.push_back(WaitForRequest("local", local_request)); @@ -91,9 +91,9 @@ class WaitForHandlerUnitTest : public LoopTest { timeout_ = timeout; Connector::Ptr connector( - Memory::allocate(Address("127.0.0.1", PORT), - PROTOCOL_VERSION, - bind_callback(&WaitForHandlerUnitTest::on_connected, this))); + new Connector(Host::Ptr(new Host(Address("127.0.0.1", PORT))), + PROTOCOL_VERSION, + bind_callback(&WaitForHandlerUnitTest::on_connected, this))); connector->connect(loop()); uv_run(loop(), UV_RUN_DEFAULT); @@ -106,7 +106,7 @@ class WaitForHandlerUnitTest : public LoopTest { void on_timeout(Timer* timer) { connection->close(); - Memory::deallocate(this); + delete this; } void start(uint64_t timeout) { @@ -120,7 +120,7 @@ class WaitForHandlerUnitTest : public LoopTest { }; static void close(const Connection::Ptr& connection, uint64_t timeout) { - CloseConnectionHandler* handler(Memory::allocate(connection)); + CloseConnectionHandler* handler(new CloseConnectionHandler(connection)); handler->start(timeout); } @@ -145,17 +145,17 @@ class WaitForHandlerUnitTest : public LoopTest { }; TEST_F(WaitForHandlerUnitTest, CloseImmediatelyWhileWaiting) { - run(TestWaitForHandler::Ptr(Memory::allocate())); + run(TestWaitForHandler::Ptr(new RegularQueryHandler())); } TEST_F(WaitForHandlerUnitTest, CloseAfterTimeoutWhileWaiting) { - run(TestWaitForHandler::Ptr(Memory::allocate()), 500); + run(TestWaitForHandler::Ptr(new RegularQueryHandler()), 500); } TEST_F(WaitForHandlerUnitTest, CloseIdempotentImmediatelyWhileWaiting) { - run(TestWaitForHandler::Ptr(Memory::allocate())); + run(TestWaitForHandler::Ptr(new IdempotentQueryHandler())); } TEST_F(WaitForHandlerUnitTest, CloseIdempotentAfterTimeoutWhileWaiting) { - run(TestWaitForHandler::Ptr(Memory::allocate()), 500); + run(TestWaitForHandler::Ptr(new IdempotentQueryHandler()), 500); } diff --git a/include/cassandra.h b/include/cassandra.h index 8bc32a1c2..5d29b2475 100644 --- a/include/cassandra.h +++ b/include/cassandra.h @@ -52,7 +52,7 @@ */ #define CASS_VERSION_MAJOR 2 -#define CASS_VERSION_MINOR 11 +#define CASS_VERSION_MINOR 12 #define CASS_VERSION_PATCH 0 #define CASS_VERSION_SUFFIX "" @@ -1020,15 +1020,20 @@ cass_execution_profile_set_load_balance_round_robin(CassExecProfile* profile); * Note: Profile-based load balancing policy is disabled by default; * cluster load balancing policy is used when profile does not contain a policy. * + * @deprecated The remote DC settings for DC-aware are not suitable for most + * scenarios that require DC failover. There is also unhandled gap between + * replication factor number of nodes failing and the full cluster failing. Only + * the remote DC settings are being deprecated. + * * @public @memberof CassExecProfile * * @param[in] profile * @param[in] local_dc The primary data center to try first * @param[in] used_hosts_per_remote_dc The number of hosts used in each remote - * DC if no hosts are available in the local dc + * DC if no hosts are available in the local dc (deprecated) * @param[in] allow_remote_dcs_for_local_cl Allows remote hosts to be used if no * local dc hosts are available and the consistency level is LOCAL_ONE or - * LOCAL_QUORUM + * LOCAL_QUORUM (deprecated) * @return CASS_OK if successful, otherwise an error occurred. * * @see cass_cluster_set_load_balance_dc_aware() @@ -1043,13 +1048,18 @@ cass_execution_profile_set_load_balance_dc_aware(CassExecProfile* profile, * Same as cass_execution_profile_set_load_balance_dc_aware(), but with lengths * for string parameters. * + * @deprecated The remote DC settings for DC-aware are not suitable for most + * scenarios that require DC failover. There is also unhandled gap between + * replication factor number of nodes failing and the full cluster failing. Only + * the remote DC settings are being deprecated. + * * @public @memberof CassExecProfile * * @param[in] profile * @param[in] local_dc * @param[in] local_dc_length - * @param[in] used_hosts_per_remote_dc - * @param[in] allow_remote_dcs_for_local_cl + * @param[in] used_hosts_per_remote_dc (deprecated) + * @param[in] allow_remote_dcs_for_local_cl (deprecated) * @return same as cass_execution_profile_set_load_balance_dc_aware() * * @see cass_execution_profile_set_load_balance_dc_aware() @@ -2073,14 +2083,20 @@ cass_cluster_set_load_balance_round_robin(CassCluster* cluster); * query plans. If relying on this mechanism, be sure to use only contact * points from the local DC. * + * @deprecated The remote DC settings for DC-aware are not suitable for most + * scenarios that require DC failover. There is also unhandled gap between + * replication factor number of nodes failing and the full cluster failing. Only + * the remote DC settings are being deprecated. + * * @public @memberof CassCluster * * @param[in] cluster * @param[in] local_dc The primary data center to try first - * @param[in] used_hosts_per_remote_dc The number of hosts used in each remote DC if no hosts - * are available in the local dc - * @param[in] allow_remote_dcs_for_local_cl Allows remote hosts to be used if no local dc hosts - * are available and the consistency level is LOCAL_ONE or LOCAL_QUORUM + * @param[in] used_hosts_per_remote_dc The number of hosts used in each remote + * DC if no hosts are available in the local dc (deprecated) + * @param[in] allow_remote_dcs_for_local_cl Allows remote hosts to be used if no + * local dc hosts are available and the consistency level is LOCAL_ONE or + * LOCAL_QUORUM (deprecated) * @return CASS_OK if successful, otherwise an error occurred */ CASS_EXPORT CassError @@ -2094,13 +2110,18 @@ cass_cluster_set_load_balance_dc_aware(CassCluster* cluster, * Same as cass_cluster_set_load_balance_dc_aware(), but with lengths for string * parameters. * + * @deprecated The remote DC settings for DC-aware are not suitable for most + * scenarios that require DC failover. There is also unhandled gap between + * replication factor number of nodes failing and the full cluster failing. Only + * the remote DC settings are being deprecated. + * * @public @memberof CassCluster * * @param[in] cluster * @param[in] local_dc * @param[in] local_dc_length - * @param[in] used_hosts_per_remote_dc - * @param[in] allow_remote_dcs_for_local_cl + * @param[in] used_hosts_per_remote_dc (deprecated) + * @param[in] allow_remote_dcs_for_local_cl (deprecated) * @return same as cass_cluster_set_load_balance_dc_aware() * * @see cass_cluster_set_load_balance_dc_aware() diff --git a/src/abstract_data.hpp b/src/abstract_data.hpp index 20b4b2c16..b32745563 100644 --- a/src/abstract_data.hpp +++ b/src/abstract_data.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_ABSTRACT_DATA_HPP_INCLUDED__ #define __CASS_ABSTRACT_DATA_HPP_INCLUDED__ +#include "allocated.hpp" #include "buffer.hpp" #include "collection.hpp" #include "data_type.hpp" @@ -37,7 +38,7 @@ namespace cass { class Tuple; class UserTypeValue; -class AbstractData { +class AbstractData : public Allocated { public: class Element { public: diff --git a/src/address.hpp b/src/address.hpp index a59f3d384..94cf41403 100644 --- a/src/address.hpp +++ b/src/address.hpp @@ -17,8 +17,8 @@ #ifndef __CASS_ADDRESS_HPP_INCLUDED__ #define __CASS_ADDRESS_HPP_INCLUDED__ +#include "allocated.hpp" #include "hash.hpp" -#include "memory.hpp" #include "string.hpp" #include "vector.hpp" #include "dense_hash_set.hpp" @@ -32,7 +32,7 @@ namespace cass { class Row; class Value; -class Address { +class Address : public Allocated { public: static const Address EMPTY_KEY; static const Address DELETED_KEY; diff --git a/src/allocated.cpp b/src/allocated.cpp new file mode 100644 index 000000000..b2596f469 --- /dev/null +++ b/src/allocated.cpp @@ -0,0 +1,39 @@ +/* + Copyright (c) DataStax, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include "allocated.hpp" +#include "memory.hpp" +#include + +namespace cass { + +void* Allocated::operator new(size_t size) { + return Memory::malloc(size); +} + +void* Allocated::operator new[](size_t size) { + return Memory::malloc(size); +} + +void Allocated::operator delete(void* ptr) { + Memory::free(ptr); +} + +void Allocated::operator delete[](void* ptr) { + Memory::free(ptr); +} + +} // namespace cass diff --git a/src/allocated.hpp b/src/allocated.hpp new file mode 100644 index 000000000..5c318aa83 --- /dev/null +++ b/src/allocated.hpp @@ -0,0 +1,41 @@ +/* + Copyright (c) DataStax, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#ifndef __CASS_ALLOCATED_HPP_INCLUDED__ +#define __CASS_ALLOCATED_HPP_INCLUDED__ + +#include + +namespace cass { + +class Allocated { +public: + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void* ptr); + void operator delete[](void* ptr); + + void* operator new(size_t, void* p) { return p; } + void* operator new[](size_t, void* p) { return p; } +}; + +template +struct AllocatedT : public Allocated, public T { }; + + +} // namespace cass + +#endif diff --git a/src/allocator.hpp b/src/allocator.hpp index c6f27c2d2..5c7deed4a 100644 --- a/src/allocator.hpp +++ b/src/allocator.hpp @@ -10,6 +10,8 @@ #include "memory.hpp" +#include + namespace cass { template diff --git a/src/async.cpp b/src/async.cpp index 6889aabac..92c695929 100644 --- a/src/async.cpp +++ b/src/async.cpp @@ -16,8 +16,6 @@ #include "async.hpp" -#include "memory.hpp" - namespace cass { Async::Async() @@ -29,7 +27,7 @@ Async::~Async() { int Async::start(uv_loop_t* loop, const Async::Callback& callback) { if (handle_ == NULL) { - handle_ = Memory::allocate(); + handle_ = new AllocatedT(); handle_->data = this; int rc = uv_async_init(loop, handle_, on_async); if (rc != 0) return rc; @@ -60,7 +58,7 @@ void Async::on_async(uv_async_t* handle) { } void Async::on_close(uv_handle_t* handle) { - Memory::deallocate(reinterpret_cast(handle)); + delete reinterpret_cast*>(handle); } } // namespace cass diff --git a/src/async.hpp b/src/async.hpp index e2069001c..5949ece04 100644 --- a/src/async.hpp +++ b/src/async.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_ASYNC_HPP_INCLUDED__ #define __CASS_ASYNC_HPP_INCLUDED__ +#include "allocated.hpp" #include "callback.hpp" #include "macros.hpp" @@ -69,7 +70,7 @@ class Async { static void on_close(uv_handle_t* handle); private: - uv_async_t* handle_; + AllocatedT* handle_; Callback callback_; private: diff --git a/src/auth.hpp b/src/auth.hpp index d2a10c98a..d94b2521e 100644 --- a/src/auth.hpp +++ b/src/auth.hpp @@ -68,8 +68,9 @@ class AuthProvider : public RefCounted { public: typedef SharedRefPtr Ptr; - AuthProvider() - : RefCounted() { } + AuthProvider(const String& name = "") + : RefCounted() + , name_(name) { } virtual ~AuthProvider() { } @@ -79,8 +80,15 @@ class AuthProvider : public RefCounted { return Authenticator::Ptr(); } + // TODO: CPP-749; make the `name` immutable + const String& name() { return name_; } + void set_name(const String& name) { name_ = name; } + private: DISALLOW_COPY_AND_ASSIGN(AuthProvider); + +private: + String name_; }; class ExternalAuthenticator : public Authenticator { @@ -118,9 +126,10 @@ class ExternalAuthenticator : public Authenticator { class ExternalAuthProvider : public AuthProvider { public: ExternalAuthProvider(const CassAuthenticatorCallbacks* exchange_callbacks, - CassAuthenticatorDataCleanupCallback cleanup_callback, - void* data) - : exchange_callbacks_(*exchange_callbacks) + CassAuthenticatorDataCleanupCallback cleanup_callback, + void* data) + : AuthProvider("ExternalAuthProvider") + , exchange_callbacks_(*exchange_callbacks) , cleanup_callback_(cleanup_callback) , data_(data) { } @@ -133,11 +142,11 @@ class ExternalAuthProvider : public AuthProvider { virtual Authenticator::Ptr new_authenticator(const Address& address, const String& hostname, const String& class_name) const { - return Authenticator::Ptr(Memory::allocate(address, - hostname, - class_name, - &exchange_callbacks_, - data_)); + return Authenticator::Ptr(new ExternalAuthenticator(address, + hostname, + class_name, + &exchange_callbacks_, + data_)); } private: @@ -150,13 +159,14 @@ class PlainTextAuthProvider : public AuthProvider { public: PlainTextAuthProvider(const String& username, const String& password) - : username_(username) + : AuthProvider("PlainTextAuthProvider") + , username_(username) , password_(password) { } virtual Authenticator::Ptr new_authenticator(const Address& address, const String& hostname, const String& class_name) const { - return Authenticator::Ptr(Memory::allocate(username_, password_)); + return Authenticator::Ptr(new PlainTextAuthenticator(username_, password_)); } private: diff --git a/src/batch_request.cpp b/src/batch_request.cpp index e3e5a6ed5..29345596f 100644 --- a/src/batch_request.cpp +++ b/src/batch_request.cpp @@ -27,7 +27,7 @@ extern "C" { CassBatch* cass_batch_new(CassBatchType type) { - cass::BatchRequest* batch = cass::Memory::allocate(type); + cass::BatchRequest* batch = new cass::BatchRequest(type); batch->inc_ref(); return CassBatch::to(batch); } diff --git a/src/blacklist_dc_policy.hpp b/src/blacklist_dc_policy.hpp index 3a1fbea75..42774b067 100644 --- a/src/blacklist_dc_policy.hpp +++ b/src/blacklist_dc_policy.hpp @@ -34,7 +34,7 @@ class BlacklistDCPolicy : public ListPolicy { virtual ~BlacklistDCPolicy() {} BlacklistDCPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), dcs_); + return new BlacklistDCPolicy(child_policy_->new_instance(), dcs_); } private: diff --git a/src/blacklist_policy.hpp b/src/blacklist_policy.hpp index e452d0d0a..545a32a99 100644 --- a/src/blacklist_policy.hpp +++ b/src/blacklist_policy.hpp @@ -34,7 +34,7 @@ class BlacklistPolicy : public ListPolicy { virtual ~BlacklistPolicy() {} BlacklistPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), hosts_); + return new BlacklistPolicy(child_policy_->new_instance(), hosts_); } private: diff --git a/src/cluster.cpp b/src/cluster.cpp index 967f5297b..3c748fb85 100644 --- a/src/cluster.cpp +++ b/src/cluster.cpp @@ -92,6 +92,28 @@ class ClusterStartEvents : public Task { Cluster::Ptr cluster_; }; +class ClusterStartClientMonitor : public Task { +public: + ClusterStartClientMonitor(const Cluster::Ptr& cluster, + const String& client_id, + const String& session_id, + const Config& config) + : cluster_(cluster) + , client_id_(client_id) + , session_id_(session_id) + , config_(config) { } + + void run(EventLoop* event_loop) { + cluster_->internal_start_monitor_reporting(client_id_, session_id_, config_); + } + +private: + Cluster::Ptr cluster_; + String client_id_; + String session_id_; + Config config_; +}; + /** * A no operation cluster listener. This is used when a listener is not set. */ @@ -184,7 +206,7 @@ LockedHostMap&LockedHostMap::operator=(const HostMap& hosts) { } ClusterSettings::ClusterSettings() - : load_balancing_policy(Memory::allocate()) + : load_balancing_policy(new RoundRobinPolicy()) , port(CASS_DEFAULT_PORT) , reconnect_timeout_ms(CASS_DEFAULT_RECONNECT_WAIT_TIME_MS) , prepare_on_up_or_add_host(CASS_DEFAULT_PREPARE_ON_UP_OR_ADD_HOST) @@ -236,19 +258,28 @@ Cluster::Cluster(const ControlConnection::Ptr& connection, } void Cluster::close() { - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new ClusterRunClose(Ptr(this))); } void Cluster::notify_host_up(const Address& address) { - event_loop_->add(Memory::allocate(Ptr(this), address)); + event_loop_->add(new ClusterNotifyUp(Ptr(this), address)); } void Cluster::notify_host_down(const Address& address) { - event_loop_->add(Memory::allocate(Ptr(this), address)); + event_loop_->add(new ClusterNotifyDown(Ptr(this), address)); } void Cluster::start_events() { - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new ClusterStartEvents(Ptr(this))); +} + +void Cluster::start_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config) { + event_loop_->add(new ClusterStartClientMonitor(Ptr(this), + client_id, + session_id, + config)); } Metadata::SchemaSnapshot Cluster::schema_snapshot() { @@ -397,9 +428,9 @@ void Cluster::on_schedule_reconnect(Timer* timer) { void Cluster::handle_schedule_reconnect() { const Host::Ptr& host = query_plan_->compute_next(); if (host) { - reconnector_.reset(Memory::allocate(host->address(), - connection_->protocol_version(), - bind_callback(&Cluster::on_reconnect, this))); + reconnector_.reset(new ControlConnector(host, + connection_->protocol_version(), + bind_callback(&Cluster::on_reconnect, this))); reconnector_ ->with_settings(settings_.control_connection_settings) ->connect(connection_->loop()); @@ -454,6 +485,7 @@ void Cluster::on_reconnect(ControlConnector* connector) { void Cluster::internal_close() { is_closing_ = true; + monitor_reporting_timer_.stop(); if (timer_.is_running()) { timer_.stop(); handle_close(); @@ -548,6 +580,35 @@ void Cluster::internal_start_events() { } } +void Cluster::internal_start_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config) { + monitor_reporting_.reset(create_monitor_reporting(client_id, + session_id, + config)); + + if (!is_closing_ && + monitor_reporting_->interval_ms(connection_->dse_server_version()) > 0) { + monitor_reporting_->send_startup_message(connection_->connection(), + config, + available_hosts(), + load_balancing_policies_); + monitor_reporting_timer_.start(event_loop_->loop(), + monitor_reporting_->interval_ms(connection_->dse_server_version()), + bind_callback(&Cluster::on_monitor_reporting, this)); + } +} + +void Cluster::on_monitor_reporting(Timer* timer) { + if (!is_closing_) { + monitor_reporting_->send_status_message(connection_->connection(), + available_hosts()); + monitor_reporting_timer_.start(event_loop_->loop(), + monitor_reporting_->interval_ms(connection_->dse_server_version()), + bind_callback(&Cluster::on_monitor_reporting, this)); + } +} + void Cluster::notify_host_add(const Host::Ptr& host) { LockedHostMap::const_iterator host_it = hosts_.find(host->address()); @@ -631,11 +692,11 @@ bool Cluster::prepare_host(const Host::Ptr& host, const PrepareHostHandler::Callback& callback) { if (connection_ && settings_.prepare_on_up_or_add_host) { PrepareHostHandler::Ptr prepare_host_handler( - Memory::allocate(host, - prepared_metadata_.copy(), - callback, - connection_->protocol_version(), - settings_.max_prepares_per_flush)); + new PrepareHostHandler(host, + prepared_metadata_.copy(), + callback, + connection_->protocol_version(), + settings_.max_prepares_per_flush)); prepare_host_handler->prepare(connection_->loop(), settings_.control_connection_settings.connection_settings); diff --git a/src/cluster.hpp b/src/cluster.hpp index b13063510..caadfef6e 100644 --- a/src/cluster.hpp +++ b/src/cluster.hpp @@ -17,9 +17,9 @@ #ifndef __CASS_CLUSTER_HPP_INCLUDED__ #define __CASS_CLUSTER_HPP_INCLUDED__ +#include "monitor_reporting.hpp" #include "config.hpp" #include "control_connector.hpp" -#include "memory.hpp" #include "external.hpp" #include "event_loop.hpp" #include "metadata.hpp" @@ -235,7 +235,7 @@ class Cluster : public RefCounted * @param event_loop The event loop. * @param connected_host The currently connected host. * @param hosts Available hosts for the cluster (based on load balancing - * policies) + * policies). * @param schema Current schema metadata. * @param load_balancing_policy The default load balancing policy to use for * determining the next control connection host. @@ -260,7 +260,7 @@ class Cluster : public RefCounted * @param listener The cluster listener. */ void set_listener(ClusterListener* listener = NULL); - + /** * Close the current connection and stop the re-connection process (thread-safe). */ @@ -289,6 +289,17 @@ class Cluster : public RefCounted */ void start_events(); + /** + * Start the client monitor events (thread-safe). + * + * @param client_id Client ID associated with the session. + * @param session_id Session ID associated with the session. + * @param config The config object. + */ + void start_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config); + /** * Get the latest snapshot of the schema metadata (thread-safe). * @@ -335,12 +346,14 @@ class Cluster : public RefCounted ProtocolVersion protocol_version() const { return connection_->protocol_version(); } const Host::Ptr& connected_host() const { return connected_host_; } const TokenMap::Ptr& token_map() const { return token_map_; } + const VersionNumber& dse_server_version() const { return connection_->dse_server_version(); } private: friend class ClusterRunClose; friend class ClusterNotifyUp; friend class ClusterNotifyDown; friend class ClusterStartEvents; + friend class ClusterStartClientMonitor; private: void update_hosts(const HostMap& hosts); @@ -368,7 +381,12 @@ class Cluster : public RefCounted void internal_notify_host_down(const Address& address); void internal_start_events(); - + void internal_start_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config); + + void on_monitor_reporting(Timer* timer); + void notify_host_add(const Host::Ptr& host); void notify_host_add_after_prepare(const Host::Ptr& host); @@ -422,6 +440,8 @@ class Cluster : public RefCounted Timer timer_; bool is_recording_events_; ClusterEvent::Vec recorded_events_; + ScopedPtr monitor_reporting_; + Timer monitor_reporting_timer_; }; } // namespace cass diff --git a/src/cluster_config.cpp b/src/cluster_config.cpp index 3a11695ad..caece85db 100644 --- a/src/cluster_config.cpp +++ b/src/cluster_config.cpp @@ -19,7 +19,7 @@ extern "C" { CassCluster* cass_cluster_new() { - return CassCluster::to(cass::Memory::allocate()); + return CassCluster::to(new cass::ClusterConfig()); } CassError cass_cluster_set_port(CassCluster* cluster, @@ -221,12 +221,12 @@ void cass_cluster_set_max_schema_wait_time(CassCluster* cluster, } void cass_cluster_set_tracing_max_wait_time(CassCluster* cluster, - unsigned wait_time_ms) { + unsigned wait_time_ms) { cluster->config().set_max_tracing_wait_time_ms(wait_time_ms); } void cass_cluster_set_tracing_retry_wait_time(CassCluster* cluster, - unsigned wait_time_ms) { + unsigned wait_time_ms) { cluster->config().set_retry_tracing_wait_time_ms(wait_time_ms); } @@ -253,7 +253,7 @@ void cass_cluster_set_credentials_n(CassCluster* cluster, } void cass_cluster_set_load_balance_round_robin(CassCluster* cluster) { - cluster->config().set_load_balancing_policy(cass::Memory::allocate()); + cluster->config().set_load_balancing_policy(new cass::RoundRobinPolicy()); } CassError cass_cluster_set_load_balance_dc_aware(CassCluster* cluster, @@ -279,9 +279,9 @@ CassError cass_cluster_set_load_balance_dc_aware_n(CassCluster* cluster, return CASS_ERROR_LIB_BAD_PARAMS; } cluster->config().set_load_balancing_policy( - cass::Memory::allocate(cass::String(local_dc, local_dc_length), - used_hosts_per_remote_dc, - !allow_remote_dcs_for_local_cl)); + new cass::DCAwarePolicy(cass::String(local_dc, local_dc_length), + used_hosts_per_remote_dc, + !allow_remote_dcs_for_local_cl)); return CASS_OK; } @@ -403,8 +403,8 @@ CassError cass_cluster_set_authenticator_callbacks(CassCluster* cluster, CassAuthenticatorDataCleanupCallback cleanup_callback, void* data) { cluster->config().set_auth_provider(cass::AuthProvider::Ptr( - cass::Memory::allocate(exchange_callbacks, - cleanup_callback, data))); + new cass::ExternalAuthProvider(exchange_callbacks, + cleanup_callback, data))); return CASS_OK; } @@ -452,14 +452,14 @@ CassError cass_cluster_set_constant_speculative_execution_policy(CassCluster* cl return CASS_ERROR_LIB_BAD_PARAMS; } cluster->config().set_speculative_execution_policy( - cass::Memory::allocate(constant_delay_ms, - max_speculative_executions)); + new cass::ConstantSpeculativeExecutionPolicy(constant_delay_ms, + max_speculative_executions)); return CASS_OK; } CassError cass_cluster_set_no_speculative_execution_policy(CassCluster* cluster) { cluster->config().set_speculative_execution_policy( - cass::Memory::allocate()); + new cass::NoSpeculativeExecutionPolicy()); return CASS_OK; } @@ -473,15 +473,15 @@ CassError cass_cluster_set_execution_profile(CassCluster* cluster, const char* name, CassExecProfile* profile) { return cass_cluster_set_execution_profile_n(cluster, - name, - SAFE_STRLEN(name), + name, + SAFE_STRLEN(name), profile); } CassError cass_cluster_set_execution_profile_n(CassCluster* cluster, - const char* name, - size_t name_length, - CassExecProfile* profile) { + const char* name, + size_t name_length, + CassExecProfile* profile) { if (name_length == 0 || !profile) { return CASS_ERROR_LIB_BAD_PARAMS; } @@ -531,13 +531,13 @@ CassError cass_cluster_set_host_listener_callback(CassCluster* cluster, CassHostListenerCallback callback, void* data) { cluster->config().set_host_listener( - cass::DefaultHostListener::Ptr( - cass::Memory::allocate(callback, data))); + cass::DefaultHostListener::Ptr( + new cass::ExternalHostListener(callback, data))); return CASS_OK; } void cass_cluster_free(CassCluster* cluster) { - cass::Memory::deallocate(cluster->from()); + delete cluster->from(); } } // extern "C" diff --git a/src/cluster_config.hpp b/src/cluster_config.hpp index 59ea2437f..79a4062c8 100644 --- a/src/cluster_config.hpp +++ b/src/cluster_config.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_CLUSTER_CONFIG_HPP_INCLUDED__ #define __CASS_CLUSTER_CONFIG_HPP_INCLUDED__ +#include "allocated.hpp" #include "config.hpp" #include "external.hpp" @@ -24,7 +25,7 @@ namespace cass { -class ClusterConfig { +class ClusterConfig : public Allocated { public: const Config& config() const { return config_; } Config& config() { return config_; } diff --git a/src/cluster_connector.cpp b/src/cluster_connector.cpp index 2d1e6af29..3f2e1fe27 100644 --- a/src/cluster_connector.cpp +++ b/src/cluster_connector.cpp @@ -85,12 +85,12 @@ ClusterConnector* ClusterConnector::with_metrics(Metrics* metrics) { void ClusterConnector::connect(EventLoop* event_loop) { event_loop_ = event_loop; - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new RunResolveAndConnectCluster(Ptr(this))); } void ClusterConnector::cancel() { if (event_loop_) { - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new RunCancelCluster(Ptr(this))); } } @@ -119,7 +119,7 @@ void ClusterConnector::internal_resolve_and_connect() { } else { if (!resolver_) { resolver_.reset( - Memory::allocate( + new MultiResolver( bind_callback(&ClusterConnector::on_resolve, this))); } resolver_->resolve(event_loop_->loop(), @@ -135,9 +135,10 @@ void ClusterConnector::internal_resolve_and_connect() { } void ClusterConnector::internal_connect(const Address& address, ProtocolVersion version) { - ControlConnector::Ptr connector(Memory::allocate(address, - version, - bind_callback(&ClusterConnector::on_connect, this))); + Host::Ptr host(new Host(address)); + ControlConnector::Ptr connector(new ControlConnector(host, + version, + bind_callback(&ClusterConnector::on_connect, this))); connectors_[address] = connector; // Keep track of the connectors so they can be canceled. connector ->with_metrics(metrics_) @@ -299,15 +300,15 @@ void ClusterConnector::on_connect(ControlConnector* connector) { return; } - cluster_.reset(Memory::allocate(connector->release_connection(), - listener_, - event_loop_, - connected_host, - hosts, - connector->schema(), - default_policy, - policies, - settings_)); + cluster_.reset(new Cluster(connector->release_connection(), + listener_, + event_loop_, + connected_host, + hosts, + connector->schema(), + default_policy, + policies, + settings_)); // Clear any connection errors and set the final negotiated protocol version. error_code_ = CLUSTER_OK; diff --git a/src/collection.cpp b/src/collection.cpp index 8fd5b5c2d..2fe6af848 100644 --- a/src/collection.cpp +++ b/src/collection.cpp @@ -28,7 +28,7 @@ extern "C" { CassCollection* cass_collection_new(CassCollectionType type, size_t item_count) { - cass::Collection* collection = cass::Memory::allocate(type, item_count); + cass::Collection* collection = new cass::Collection(type, item_count); collection->inc_ref(); return CassCollection::to(collection); } @@ -39,7 +39,7 @@ CassCollection* cass_collection_new_from_data_type(const CassDataType* data_type return NULL; } cass::Collection* collection - = cass::Memory::allocate(cass::DataType::ConstPtr(data_type), + = new cass::Collection(cass::DataType::ConstPtr(data_type), item_count); collection->inc_ref(); return CassCollection::to(collection); diff --git a/src/collection.hpp b/src/collection.hpp index f73542f10..21e5e646d 100644 --- a/src/collection.hpp +++ b/src/collection.hpp @@ -38,7 +38,7 @@ class Collection : public RefCounted { public: Collection(CassCollectionType type, size_t item_count) - : data_type_(Memory::allocate(static_cast(type), false)) { + : data_type_(new CollectionType(static_cast(type), false)) { items_.reserve(item_count); } diff --git a/src/config.hpp b/src/config.hpp index d0ef370c5..f38b6efee 100644 --- a/src/config.hpp +++ b/src/config.hpp @@ -54,13 +54,13 @@ class Config { , log_level_(CASS_DEFAULT_LOG_LEVEL) , log_callback_(stderr_log_callback) , log_data_(NULL) - , auth_provider_(Memory::allocate()) + , auth_provider_(new AuthProvider()) , tcp_nodelay_enable_(CASS_DEFAULT_TCP_NO_DELAY_ENABLED) , tcp_keepalive_enable_(CASS_DEFAULT_TCP_KEEPALIVE_ENABLED) , tcp_keepalive_delay_secs_(CASS_DEFAULT_TCP_KEEPALIVE_DELAY_SECS) , connection_idle_timeout_secs_(CASS_DEFAULT_IDLE_TIMEOUT_SECS) , connection_heartbeat_interval_secs_(CASS_DEFAULT_HEARTBEAT_INTERVAL_SECS) - , timestamp_gen_(Memory::allocate()) + , timestamp_gen_(new MonotonicTimestampGenerator()) , use_schema_(CASS_DEFAULT_USE_SCHEMA) , use_hostname_resolution_(CASS_DEFAULT_HOSTNAME_RESOLUTION_ENABLED) , use_randomized_contact_points_(CASS_DEFAULT_USE_RANDOMIZED_CONTACT_POINTS) @@ -68,16 +68,18 @@ class Config { , prepare_on_all_hosts_(CASS_DEFAULT_PREPARE_ON_ALL_HOSTS) , prepare_on_up_or_add_host_(CASS_DEFAULT_PREPARE_ON_UP_OR_ADD_HOST) , no_compact_(CASS_DEFAULT_NO_COMPACT) - , host_listener_(Memory::allocate()) { + , is_client_id_set_(false) + , host_listener_(new DefaultHostListener()) + , monitor_reporting_interval_secs_(CASS_DEFAULT_CLIENT_MONITOR_EVENTS_INTERVAL_SECS) { profiles_.set_empty_key(String()); // Assign the defaults to the cluster profile default_profile_.set_consistency(CASS_DEFAULT_CONSISTENCY); default_profile_.set_serial_consistency(CASS_DEFAULT_SERIAL_CONSISTENCY); default_profile_.set_request_timeout(CASS_DEFAULT_REQUEST_TIMEOUT_MS); - default_profile_.set_load_balancing_policy(Memory::allocate()); - default_profile_.set_retry_policy(Memory::allocate()); - default_profile_.set_speculative_execution_policy(Memory::allocate()); + default_profile_.set_load_balancing_policy(new DCAwarePolicy()); + default_profile_.set_retry_policy(new DefaultRetryPolicy()); + default_profile_.set_speculative_execution_policy(new NoSpeculativeExecutionPolicy()); } Config new_instance() const { @@ -89,10 +91,12 @@ class Config { return config; } + CassConsistency consistency() { return default_profile_.consistency(); } void set_consistency(CassConsistency consistency) { default_profile_.set_consistency(consistency); } + CassConsistency serial_consistency() { return default_profile_.serial_consistency(); } void set_serial_consistency(CassConsistency serial_consistency) { default_profile_.set_serial_consistency(serial_consistency); } @@ -165,6 +169,7 @@ class Config { new_request_ratio_ = ratio; } + unsigned request_timeout() { return default_profile_.request_timeout_ms(); } void set_request_timeout(unsigned timeout_ms) { default_profile_.set_request_timeout(timeout_ms); } @@ -221,11 +226,11 @@ class Config { const AuthProvider::Ptr& auth_provider() const { return auth_provider_; } void set_auth_provider(const AuthProvider::Ptr& auth_provider) { - auth_provider_ = (!auth_provider ? AuthProvider::Ptr(Memory::allocate()) : auth_provider); + auth_provider_ = (!auth_provider ? AuthProvider::Ptr(new AuthProvider()) : auth_provider); } void set_credentials(const String& username, const String& password) { - auth_provider_.reset(Memory::allocate(username, password)); + auth_provider_.reset(new PlainTextAuthProvider(username, password)); } const LoadBalancingPolicy::Ptr& load_balancing_policy() const { @@ -398,16 +403,29 @@ class Config { application_version_ = application_version; } + CassUuid client_id() const { return client_id_; } + bool is_client_id_set() const { return is_client_id_set_; } + + void set_client_id(CassUuid client_id) { + client_id_ = client_id; + is_client_id_set_ = true; + } + const DefaultHostListener::Ptr& host_listener() const { return host_listener_; } - + void set_host_listener(const DefaultHostListener::Ptr& listener) { if (listener) { host_listener_ = listener; } else { - host_listener_.reset(Memory::allocate()); + host_listener_.reset(new DefaultHostListener()); } } + unsigned monitor_reporting_interval_secs() const { return monitor_reporting_interval_secs_; } + void set_monitor_reporting_interval_secs(unsigned interval_secs) { + monitor_reporting_interval_secs_ = interval_secs; + }; + private: void init_profiles(); @@ -451,7 +469,10 @@ class Config { bool no_compact_; String application_name_; String application_version_; + bool is_client_id_set_; + CassUuid client_id_; DefaultHostListener::Ptr host_listener_; + unsigned monitor_reporting_interval_secs_; }; } // namespace cass diff --git a/src/connection.cpp b/src/connection.cpp index 7bed90326..e5ff80285 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -40,7 +40,7 @@ class HeartbeatCallback : public SimpleRequestCallback { }; HeartbeatCallback::HeartbeatCallback(Connection* connection) - : SimpleRequestCallback(Request::ConstPtr(Memory::allocate())) + : SimpleRequestCallback(Request::ConstPtr(new OptionsRequest())) , connection_(connection) { } void HeartbeatCallback::on_internal_set(ResponseMessage* response) { @@ -105,18 +105,27 @@ void RecordingConnectionListener::process_events(const EventResponse::Vec& event } Connection::Connection(const Socket::Ptr& socket, + const Host::Ptr& host, ProtocolVersion protocol_version, unsigned int idle_timeout_secs, unsigned int heartbeat_interval_secs) : socket_(socket) + , host_(host) , inflight_request_count_(0) - , response_(Memory::allocate()) + , response_(new ResponseMessage()) , listener_(&nop_listener__) , protocol_version_(protocol_version) , idle_timeout_secs_(idle_timeout_secs) , heartbeat_interval_secs_(heartbeat_interval_secs) , heartbeat_outstanding_(false) { inc_ref(); // For the event loop + + assert(host_->address() == socket_->address() && "Host doesn't match socket address"); + host_->increment_connection_count(); +} + +Connection::~Connection() { + host_->decrement_connection_count(); } int32_t Connection::write(const RequestCallback::Ptr& callback) { @@ -276,7 +285,7 @@ void Connection::on_read(const char* buf, size_t size) { if (response_->is_body_ready()) { ScopedPtr response(response_.release()); - response_.reset(Memory::allocate()); + response_.reset(new ResponseMessage()); LOG_TRACE("Consumed message type %s with stream %d, input %u, remaining %u on host %s", opcode_to_string(response->opcode()).c_str(), @@ -352,7 +361,7 @@ void Connection::restart_heartbeat_timer() { void Connection::on_heartbeat(Timer* timer) { if (!heartbeat_outstanding_ && !socket_->is_closing()) { - if (!write_and_flush(RequestCallback::Ptr(Memory::allocate(this)))) { + if (!write_and_flush(RequestCallback::Ptr(new HeartbeatCallback(this)))) { // Recycling only this connection with a timeout error. This is unlikely and // it means the connection ran out of stream IDs as a result of requests // that never returned and as a result timed out. diff --git a/src/connection.hpp b/src/connection.hpp index 7630cb08f..675705e1c 100644 --- a/src/connection.hpp +++ b/src/connection.hpp @@ -135,15 +135,18 @@ class Connection : public RefCounted { * Constructor. Don't use directly. * * @param socket The wrapped socket. + * @param host The host associated with the connection. * @param protocol_version The protocol version to use for the connection. * @param idle_timeout_secs The amount of time (in seconds) without a write or heartbeat * where the connection is considered idle and is terminated. * @param heartbeat_interval_secs The interval (in seconds) to send a heartbeat. */ Connection(const Socket::Ptr& socket, + const Host::Ptr& host, ProtocolVersion protocol_version, unsigned int idle_timeout_secs, unsigned int heartbeat_interval_secs); + ~Connection(); /** * Write a request to the connection and coalesce with outstanding requests. This @@ -207,9 +210,11 @@ class Connection : public RefCounted { public: const Address& address() const { return socket_->address(); } const String& address_string() const { return socket_->address_string(); } + const Host::Ptr& host() const { return host_; } ProtocolVersion protocol_version() const { return protocol_version_; } const String& keyspace() { return keyspace_; } uv_loop_t* loop() { return socket_->loop(); } + const uv_tcp_t* handle() const { return socket_->handle(); } int inflight_request_count() const { return inflight_request_count_.load(MEMORY_ORDER_RELAXED); @@ -231,6 +236,7 @@ class Connection : public RefCounted { private: Socket::Ptr socket_; + const Host::Ptr host_; StreamManager stream_manager_; Atomic inflight_request_count_; diff --git a/src/connection_pool.cpp b/src/connection_pool.cpp index 6b5cf0387..37fc3e877 100644 --- a/src/connection_pool.cpp +++ b/src/connection_pool.cpp @@ -18,7 +18,6 @@ #include "config.hpp" #include "connection_pool_manager.hpp" -#include "memory.hpp" #include "metrics.hpp" #include "utils.hpp" @@ -48,8 +47,8 @@ class NopConnectionPoolListener : public ConnectionPoolListener { virtual void on_pool_down(const Address& address) { } virtual void on_pool_critical_error(const Address& address, - Connector::ConnectionError code, - const String& message) { } + Connector::ConnectionError code, + const String& message) { } virtual void on_close(ConnectionPool* pool) { } }; @@ -60,14 +59,14 @@ ConnectionPool::ConnectionPool(const Connection::Vec& connections, ConnectionPoolListener* listener, const String& keyspace, uv_loop_t* loop, - const Address& address, + const Host::Ptr& host, ProtocolVersion protocol_version, const ConnectionPoolSettings& settings, Metrics* metrics) : listener_(listener ? listener : &nop_connection_pool_listener__) , keyspace_(keyspace) , loop_(loop) - , address_(address) + , host_(host) , protocol_version_(protocol_version) , settings_(settings) , metrics_(metrics) @@ -81,7 +80,7 @@ ConnectionPool::ConnectionPool(const Connection::Vec& connections, const Connection::Ptr& connection(*it); if (!connection->is_closing()) { add_connection(PooledConnection::Ptr( - Memory::allocate(this, connection))); + new PooledConnection(this, connection))); } } @@ -171,31 +170,31 @@ void ConnectionPool::notify_up_or_down() { if ((notify_state_ == NOTIFY_STATE_NEW || notify_state_ == NOTIFY_STATE_UP) && connections_.empty()) { notify_state_ = NOTIFY_STATE_DOWN; - listener_->on_pool_down(address_); + listener_->on_pool_down(host_->address()); } else if ((notify_state_ == NOTIFY_STATE_NEW || notify_state_ == NOTIFY_STATE_DOWN) && !connections_.empty()) { notify_state_ = NOTIFY_STATE_UP; - listener_->on_pool_up(address_); + listener_->on_pool_up(host_->address()); } } void ConnectionPool::notify_critical_error(Connector::ConnectionError code, - const String& message) { + const String& message) { if (notify_state_ != NOTIFY_STATE_CRITICAL) { notify_state_ = NOTIFY_STATE_CRITICAL; - listener_->on_pool_critical_error(address_, code, message); + listener_->on_pool_critical_error(host_->address(), code, message); } } void ConnectionPool::schedule_reconnect() { LOG_INFO("Scheduling reconnect for host %s in %llu ms on connection pool (%p)", - address_.to_string().c_str(), + host_->address().to_string().c_str(), static_cast(settings_.reconnect_wait_time_ms), static_cast(this)); DelayedConnector::Ptr connector( - Memory::allocate(address_, - protocol_version_, - bind_callback(&ConnectionPool::on_reconnect, this))); + new DelayedConnector(host_, + protocol_version_, + bind_callback(&ConnectionPool::on_reconnect, this))); pending_connections_.push_back(connector); connector ->with_keyspace(keyspace()) @@ -238,7 +237,7 @@ void ConnectionPool::maybe_closed() { // Only mark DOWN if it's UP otherwise we might get multiple DOWN events // when connecting the pool. if (notify_state_ == NOTIFY_STATE_UP) { - listener_->on_pool_down(address_); + listener_->on_pool_down(host_->address()); } listener_->on_close(this); dec_ref(); @@ -257,7 +256,7 @@ void ConnectionPool::on_reconnect(DelayedConnector* connector) { if (connector->is_ok()) { add_connection( PooledConnection::Ptr( - Memory::allocate(this, connector->release_connection()))); + new PooledConnection(this, connector->release_connection()))); notify_up_or_down(); } else if (!connector->is_canceled()) { if(connector->is_critical_error()) { @@ -265,7 +264,7 @@ void ConnectionPool::on_reconnect(DelayedConnector* connector) { address().to_string().c_str(), connector->error_message().c_str()); notify_critical_error(connector->error_code(), - connector->error_message()); + connector->error_message()); internal_close(); } else { LOG_WARN("Connection pool was unable to reconnect to host %s because of the following error: %s", diff --git a/src/connection_pool.hpp b/src/connection_pool.hpp index 63f308ee5..9749a16a4 100644 --- a/src/connection_pool.hpp +++ b/src/connection_pool.hpp @@ -118,7 +118,7 @@ class ConnectionPool : public RefCounted { * @param listener * @param keyspace * @param loop - * @param address + * @param host * @param protocol_version * @param settings * @param metrics @@ -127,7 +127,7 @@ class ConnectionPool : public RefCounted { ConnectionPoolListener* listener, const String& keyspace, uv_loop_t* loop, - const Address& address, + const Host::Ptr& host, ProtocolVersion protocol_version, const ConnectionPoolSettings& settings, Metrics* metrics); @@ -171,7 +171,7 @@ class ConnectionPool : public RefCounted { public: const uv_loop_t* loop() const { return loop_; } - const Address& address() const { return address_; } + const Address& address() const { return host_->address(); } ProtocolVersion protocol_version() const { return protocol_version_; } const String& keyspace() const { return keyspace_; } @@ -233,7 +233,7 @@ class ConnectionPool : public RefCounted { ConnectionPoolListener* listener_; String keyspace_; uv_loop_t* const loop_; - const Address address_; + const Host::Ptr host_; const ProtocolVersion protocol_version_; const ConnectionPoolSettings settings_; Metrics* const metrics_; diff --git a/src/connection_pool_connector.cpp b/src/connection_pool_connector.cpp index de97c5bf9..9546adf3b 100644 --- a/src/connection_pool_connector.cpp +++ b/src/connection_pool_connector.cpp @@ -17,19 +17,18 @@ #include "connection_pool_connector.hpp" #include "event_loop.hpp" -#include "memory.hpp" #include "metrics.hpp" namespace cass { -ConnectionPoolConnector::ConnectionPoolConnector(const Address& address, +ConnectionPoolConnector::ConnectionPoolConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback) : loop_(NULL) , callback_(callback) , is_canceled_(false) , remaining_(0) - , address_(address) + , host_(host) , protocol_version_(protocol_version) , listener_(NULL) , metrics_(NULL) { } @@ -60,9 +59,9 @@ void ConnectionPoolConnector::connect(uv_loop_t* loop) { remaining_ = settings_.num_connections_per_host; for (size_t i = 0; i < settings_.num_connections_per_host; ++i) { Connector::Ptr connector( - Memory::allocate(address_, - protocol_version_, - bind_callback(&ConnectionPoolConnector::on_connect, this))); + new Connector(host_, + protocol_version_, + bind_callback(&ConnectionPoolConnector::on_connect, this))); pending_connections_.push_back(connector); connector ->with_keyspace(keyspace_) @@ -125,7 +124,7 @@ void ConnectionPoolConnector::on_connect(Connector* connector) { connections_.push_back(connector->release_connection()); } else if (!connector->is_canceled()){ LOG_ERROR("Connection pool was unable to connect to host %s because of the following error: %s", - address_.to_string().c_str(), + host_->address().to_string().c_str(), connector->error_message().c_str()); if (connector->is_critical_error()) { @@ -142,17 +141,17 @@ void ConnectionPoolConnector::on_connect(Connector* connector) { if (--remaining_ == 0) { if (!is_canceled_) { if (!critical_error_connector_) { - pool_.reset(Memory::allocate(connections_, - listener_, - keyspace_, - loop_, - address_, - protocol_version_, - settings_, - metrics_)); + pool_.reset(new ConnectionPool(connections_, + listener_, + keyspace_, + loop_, + host_, + protocol_version_, + settings_, + metrics_)); } else { if (listener_) { - listener_->on_pool_critical_error(address_, + listener_->on_pool_critical_error(host_->address(), critical_error_connector_->error_code(), critical_error_connector_->error_message()); } diff --git a/src/connection_pool_connector.hpp b/src/connection_pool_connector.hpp index 4abd1a3b5..02bfbd531 100644 --- a/src/connection_pool_connector.hpp +++ b/src/connection_pool_connector.hpp @@ -46,12 +46,12 @@ class ConnectionPoolConnector : public RefCounted { /** * Constructor * - * @param address The address to connect to. + * @param host The host to connect to. * @param protocol_version * @param callback A callback that is called when the connection is connected or * if an error occurred. */ - ConnectionPoolConnector(const Address& address, + ConnectionPoolConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback); @@ -108,7 +108,7 @@ class ConnectionPoolConnector : public RefCounted { ConnectionPool::Ptr release_pool(); public: - const Address& address() const { return address_; } + const Address& address() const { return host_->address(); } Connector::ConnectionError error_code() const; String error_message() const; @@ -131,7 +131,7 @@ class ConnectionPoolConnector : public RefCounted { Connection::Vec connections_; Connector::Ptr critical_error_connector_; - const Address address_; + Host::Ptr host_; const ProtocolVersion protocol_version_; ConnectionPoolSettings settings_; String keyspace_; diff --git a/src/connection_pool_manager.cpp b/src/connection_pool_manager.cpp index 116127c42..78ede8736 100644 --- a/src/connection_pool_manager.cpp +++ b/src/connection_pool_manager.cpp @@ -16,7 +16,6 @@ #include "connection_pool_manager.hpp" -#include "memory.hpp" #include "scoped_lock.hpp" #include "utils.hpp" @@ -29,8 +28,8 @@ class NopConnectionPoolManagerListener : public ConnectionPoolManagerListener { virtual void on_pool_down(const Address& address) { } virtual void on_pool_critical_error(const Address& address, - Connector::ConnectionError code, - const String& message) { } + Connector::ConnectionError code, + const String& message) { } virtual void on_close(ConnectionPoolManager* manager) { } }; @@ -51,9 +50,9 @@ ConnectionPoolManager::ConnectionPoolManager(const ConnectionPool::Map& pools, , close_state_(CLOSE_STATE_OPEN) , keyspace_(keyspace) , metrics_(metrics) -#ifdef CASS_INTERNAL_DIAGNOSTICS + #ifdef CASS_INTERNAL_DIAGNOSTICS , flush_bytes_("flushed") -#endif + #endif { inc_ref(); // Reference for the lifetime of the connection pools set_pointer_keys(to_flush_); @@ -97,19 +96,19 @@ AddressVec ConnectionPoolManager::available() const { return result; } -void ConnectionPoolManager::add(const Address& address) { - ConnectionPool::Map::iterator it = pools_.find(address); +void ConnectionPoolManager::add(const Host::Ptr& host) { + ConnectionPool::Map::iterator it = pools_.find(host->address()); if (it != pools_.end()) return; for (ConnectionPoolConnector::Vec::iterator it = pending_pools_.begin(), end = pending_pools_.end(); it != end; ++it) { - if ((*it)->address() == address) return; + if ((*it)->address() == host->address()) return; } ConnectionPoolConnector::Ptr connector( - Memory::allocate(address, - protocol_version_, - bind_callback(&ConnectionPoolManager::on_connect, this))); + new ConnectionPoolConnector(host, + protocol_version_, + bind_callback(&ConnectionPoolManager::on_connect, this))); pending_pools_.push_back(connector); connector ->with_listener(this) diff --git a/src/connection_pool_manager.hpp b/src/connection_pool_manager.hpp index c37a5c3f4..caf2a8f3f 100644 --- a/src/connection_pool_manager.hpp +++ b/src/connection_pool_manager.hpp @@ -113,9 +113,9 @@ class ConnectionPoolManager /** * Add a connection pool for the given host. * - * @param address The address of the host to add. + * @param host The host to add. */ - void add(const Address& address); + void add(const Host::Ptr& host); /** * Remove a connection pool for the given host. diff --git a/src/connection_pool_manager_initializer.cpp b/src/connection_pool_manager_initializer.cpp index c68e594c9..a91925aa4 100644 --- a/src/connection_pool_manager_initializer.cpp +++ b/src/connection_pool_manager_initializer.cpp @@ -16,8 +16,6 @@ #include "connection_pool_manager_initializer.hpp" -#include "memory.hpp" - namespace cass { ConnectionPoolManagerInitializer::ConnectionPoolManagerInitializer(ProtocolVersion protocol_version, @@ -30,16 +28,16 @@ ConnectionPoolManagerInitializer::ConnectionPoolManagerInitializer(ProtocolVersi , metrics_(NULL) { } void ConnectionPoolManagerInitializer::initialize(uv_loop_t* loop, - const AddressVec& addresses) { + const HostMap& hosts) { inc_ref(); loop_ = loop; - remaining_ = addresses.size(); - for (AddressVec::const_iterator it = addresses.begin(), - end = addresses.end(); it != end; ++it) { + remaining_ = hosts.size(); + for (HostMap::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { ConnectionPoolConnector::Ptr pool_connector( - Memory::allocate(*it, - protocol_version_, - bind_callback(&ConnectionPoolManagerInitializer::on_connect, this))); + new ConnectionPoolConnector(it->second, + protocol_version_, + bind_callback(&ConnectionPoolManagerInitializer::on_connect, this))); pending_pools_.push_back(pool_connector); pool_connector ->with_listener(this) @@ -129,13 +127,13 @@ void ConnectionPoolManagerInitializer::on_connect(ConnectionPoolConnector* pool_ if (--remaining_ == 0) { if (!is_canceled_) { - manager_.reset(Memory::allocate(pools_, - loop_, - protocol_version_, - keyspace_, - listener_, - metrics_, - settings_)); + manager_.reset(new ConnectionPoolManager(pools_, + loop_, + protocol_version_, + keyspace_, + listener_, + metrics_, + settings_)); } callback_(this); // If the manager hasn't been released then close it. diff --git a/src/connection_pool_manager_initializer.hpp b/src/connection_pool_manager_initializer.hpp index 4ce4d2c87..a29b2f57e 100644 --- a/src/connection_pool_manager_initializer.hpp +++ b/src/connection_pool_manager_initializer.hpp @@ -58,9 +58,9 @@ class ConnectionPoolManagerInitializer * Initialize a connection pool manager use the given hosts. * * @param loop Event loop to utilize for handling requests. - * @param addresses A vector of addresses to connect pools to. + * @param hosts A map of hosts to connect pools to. */ - void initialize(uv_loop_t* loop, const AddressVec& addresses); + void initialize(uv_loop_t* loop, const HostMap& hosts); /** * Cancel the initialization process of the manager. diff --git a/src/connector.cpp b/src/connector.cpp index 63529bc7f..897fd4315 100644 --- a/src/connector.cpp +++ b/src/connector.cpp @@ -152,7 +152,7 @@ void StartupCallback::on_result_response(ResponseMessage* response) { ConnectionSettings::ConnectionSettings() : connect_timeout_ms(CASS_DEFAULT_CONNECT_TIMEOUT_MS) - , auth_provider(Memory::allocate()) + , auth_provider(new AuthProvider()) , idle_timeout_secs(CASS_DEFAULT_IDLE_TIMEOUT_SECS) , heartbeat_interval_secs(CASS_DEFAULT_HEARTBEAT_INTERVAL_SECS) , no_compact(CASS_DEFAULT_NO_COMPACT) { } @@ -167,14 +167,15 @@ ConnectionSettings::ConnectionSettings(const Config& config) , application_name(config.application_name()) , application_version(config.application_version()) { } -Connector::Connector(const Address& address, +Connector::Connector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback) : callback_(callback) , loop_(NULL) + , host_(host) , socket_connector_( - Memory::allocate(address, - bind_callback(&Connector::on_connect, this))) + new SocketConnector(host->address(), + bind_callback(&Connector::on_connect, this))) , error_code_(CONNECTION_OK) , protocol_version_(protocol_version) , event_types_(0) @@ -207,7 +208,7 @@ Connector* Connector::with_settings(const ConnectionSettings& settings) { // authentication. settings_.socket_settings.hostname_resolution_enabled = settings.socket_settings.hostname_resolution_enabled && - (settings.auth_provider || settings.socket_settings.ssl_context); + (settings.auth_provider || settings.socket_settings.ssl_context); return this; } @@ -269,9 +270,9 @@ void Connector::on_ready_or_set_keyspace() { } else { connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate("USE " + keyspace_))))); + new StartupCallback(this, + Request::ConstPtr( + new QueryRequest("USE " + keyspace_))))); } } @@ -279,9 +280,9 @@ void Connector::on_ready_or_register_for_events() { if (event_types_ != 0) { connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate(event_types_))))); + new StartupCallback(this, + Request::ConstPtr( + new RegisterRequest(event_types_))))); // REGISTER requests also returns a READY response so this needs to be reset // to prevent a loop. event_types_ = 0; @@ -303,12 +304,12 @@ void ConnectionConnector::on_supported(ResponseMessage* response) { connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate(settings_.application_name, - settings_.application_version, - settings_.client_id, - settings_.no_compact))))); + new StartupCallback(this, + Request::ConstPtr( + new StartupRequest(settings_.application_name, + settings_.application_version, + settings_.client_id, + settings_.no_compact))))); } #endif @@ -326,9 +327,9 @@ void Connector::on_authenticate(const String& class_name) { } connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate(response, auth))))); + new StartupCallback(this, + Request::ConstPtr( + new AuthResponseRequest(response, auth))))); } } @@ -340,9 +341,9 @@ void Connector::on_auth_challenge(const AuthResponseRequest* request, const Stri } connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate(response, request->auth()))))); + new StartupCallback(this, + Request::ConstPtr( + new AuthResponseRequest(response, request->auth()))))); } void Connector::on_auth_success(const AuthResponseRequest* request, const String& token) { @@ -365,37 +366,38 @@ void Connector::on_connect(SocketConnector* socket_connector) { if (socket_connector->is_ok()) { Socket::Ptr socket(socket_connector->release_socket()); - connection_.reset(Memory::allocate(socket, - protocol_version_, - settings_.idle_timeout_secs, - settings_.heartbeat_interval_secs)); + connection_.reset(new Connection(socket, + host_, + protocol_version_, + settings_.idle_timeout_secs, + settings_.heartbeat_interval_secs)); connection_->set_listener(this); if (socket_connector->ssl_session()) { socket->set_handler( - Memory::allocate( + new SslConnectionHandler( socket_connector->ssl_session().release(), connection_.get())); } else { socket->set_handler( - Memory::allocate(connection_.get())); + new ConnectionHandler(connection_.get())); } #ifdef CASS_USE_OPTIONS connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate())))); + new StartupCallback(this, + Request::ConstPtr( + new OptionsRequest())))); #else connection_->write_and_flush( RequestCallback::Ptr( - Memory::allocate(this, - Request::ConstPtr( - Memory::allocate(settings_.application_name, - settings_.application_version, - settings_.client_id, - settings_.no_compact))))); + new StartupCallback(this, + Request::ConstPtr( + new StartupRequest(settings_.application_name, + settings_.application_version, + settings_.client_id, + settings_.no_compact))))); #endif } else if (socket_connector->is_canceled() || is_timeout_error()) { finish(); diff --git a/src/connector.hpp b/src/connector.hpp index 60df7743c..bc8d1ef5e 100644 --- a/src/connector.hpp +++ b/src/connector.hpp @@ -92,12 +92,12 @@ class Connector /** * Constructor * - * @param address The address to connect to. + * @param host The host to connect to. * @param protocol_version The protocol version to use for the connection. * @param callback A callback that is called when the connection is connected or * if an error occurred. */ - Connector(const Address& address, + Connector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback); @@ -224,6 +224,7 @@ class Connector private: Callback callback_; uv_loop_t* loop_; + Host::Ptr host_; Connection::Ptr connection_; SocketConnector::Ptr socket_connector_; diff --git a/src/constants.hpp b/src/constants.hpp index 6209ede9e..f4157bb90 100644 --- a/src/constants.hpp +++ b/src/constants.hpp @@ -144,6 +144,9 @@ #define CASS_DEFAULT_REQUEST_TIMEOUT_MS 12000u #define CASS_DEFAULT_SERIAL_CONSISTENCY CASS_CONSISTENCY_ANY +// Client monitoring defaults +#define CASS_DEFAULT_CLIENT_MONITOR_EVENTS_INTERVAL_SECS 300 + // Protocols #define CASS_HIGHEST_SUPPORTED_PROTOCOL_VERSION 4 #define CASS_LOWEST_SUPPORTED_PROTOCOL_VERSION 3 diff --git a/src/control_connection.cpp b/src/control_connection.cpp index 139da88d6..f3f380d92 100644 --- a/src/control_connection.cpp +++ b/src/control_connection.cpp @@ -332,11 +332,13 @@ ControlConnection::ControlConnection(const Connection::Ptr& connection, bool use_schema, bool token_aware_routing, const VersionNumber& server_version, + const VersionNumber& dse_server_version, ListenAddressMap listen_addresses) : connection_(connection) , use_schema_(use_schema) , token_aware_routing_(token_aware_routing) , server_version_(server_version) + , dse_server_version_(dse_server_version) , listen_addresses_(listen_addresses) , listener_(listener ? listener : &nop_listener__) { connection_->set_listener(this); @@ -386,7 +388,7 @@ void ControlConnection::refresh_node(RefreshNodeType type, const Address& addres LOG_DEBUG("Refresh node: %s", query.c_str()); if (write_and_flush(RequestCallback::Ptr( - Memory::allocate( + new RefreshNodeCallback( address, type, is_all_peers, query, this))) < 0) { LOG_ERROR("No more stream available while attempting to refresh node info"); defunct(); @@ -411,7 +413,7 @@ void ControlConnection::handle_refresh_node(RefreshNodeCallback* callback) { return; } - Host::Ptr host(Memory::allocate(callback->address)); + Host::Ptr host(new Host(callback->address)); if (!callback->is_all_peers) { host->set(&result->first_row(), token_aware_routing_); listen_addresses_[callback->address] @@ -469,14 +471,14 @@ void ControlConnection::refresh_keyspace(const StringRef& keyspace_name) { query.assign(SELECT_KEYSPACES_20); } query.append(" WHERE keyspace_name='") - .append(keyspace_name.data(), keyspace_name.size()) - .append("'"); + .append(keyspace_name.data(), keyspace_name.size()) + .append("'"); LOG_DEBUG("Refreshing keyspace %s", query.c_str()); if (write_and_flush( RequestCallback::Ptr( - Memory::allocate( + new RefreshKeyspaceCallback( keyspace_name.to_string(), query, this))) < 0) { LOG_ERROR("No more stream available while attempting to refresh keyspace info"); defunct(); @@ -524,7 +526,7 @@ void ControlConnection::refresh_table_or_view(const StringRef& keyspace_name, .append("' AND table_name='").append(table_or_view_name.data(), table_or_view_name.size()).append("'"); LOG_DEBUG("Refreshing table/view %s; %s; %s; %s", table_query.c_str(), view_query.c_str(), - column_query.c_str(), index_query.c_str()); + column_query.c_str(), index_query.c_str()); } else { table_query.assign(SELECT_COLUMN_FAMILIES_20); table_query.append(" WHERE keyspace_name='").append(keyspace_name.data(), keyspace_name.size()) @@ -538,7 +540,7 @@ void ControlConnection::refresh_table_or_view(const StringRef& keyspace_name, } ChainedRequestCallback::Ptr callback( - Memory::allocate( + new RefreshTableCallback( keyspace_name.to_string(), table_or_view_name.to_string(), "tables", table_query, this)); @@ -608,7 +610,7 @@ void ControlConnection::refresh_type(const StringRef& keyspace_name, if (!write_and_flush( RequestCallback::Ptr( - Memory::allocate( + new RefreshTypeCallback( keyspace_name.to_string(), type_name.to_string(), query, this)))) { LOG_ERROR("No more stream available while attempting to refresh type info"); @@ -661,8 +663,8 @@ void ControlConnection::refresh_function(const StringRef& keyspace_name, Metadata::full_function_name(function_name.to_string(), to_strings(arg_types)).c_str(), String(keyspace_name.data(), keyspace_name.length()).c_str()); - SharedRefPtr request(Memory::allocate(query, 3)); - SharedRefPtr signature(Memory::allocate(CASS_COLLECTION_TYPE_LIST, arg_types.size())); + SharedRefPtr request(new QueryRequest(query, 3)); + SharedRefPtr signature(new Collection(CASS_COLLECTION_TYPE_LIST, arg_types.size())); for (StringRefVec::const_iterator i = arg_types.begin(), end = arg_types.end(); @@ -677,7 +679,7 @@ void ControlConnection::refresh_function(const StringRef& keyspace_name, if (!write_and_flush( RequestCallback::Ptr( - Memory::allocate( + new RefreshFunctionCallback( keyspace_name.to_string(), function_name.to_string(), to_strings(arg_types), is_aggregate, request, this)))) { diff --git a/src/control_connection.hpp b/src/control_connection.hpp index d7a1bf4f2..6ddbc335c 100644 --- a/src/control_connection.hpp +++ b/src/control_connection.hpp @@ -187,6 +187,7 @@ class ControlConnection : public RefCounted * @param token_aware_routing If true the connection will get additional data * for keyspace schema changes, otherwise it will ignore those events. * @param server_version The version number of the server implementation. + * @param dse_server_version The version number of the DSE server implementation. * @param listen_addresses The current state of the listen addresses map. */ ControlConnection(const Connection::Ptr& connection, @@ -194,6 +195,7 @@ class ControlConnection : public RefCounted bool use_schema, bool token_aware_routing, const VersionNumber& server_version, + const VersionNumber& dse_server_version, ListenAddressMap listen_addresses); /** @@ -239,7 +241,12 @@ class ControlConnection : public RefCounted return server_version_; } + const VersionNumber& dse_server_version() { + return dse_server_version_; + } + uv_loop_t* loop() { return connection_->loop(); } + const Connection::Ptr& connection() const { return connection_; } private: friend class ControlConnector; @@ -284,6 +291,7 @@ class ControlConnection : public RefCounted bool use_schema_; bool token_aware_routing_; VersionNumber server_version_; + VersionNumber dse_server_version_; ListenAddressMap listen_addresses_; ControlConnectionListener* listener_; }; diff --git a/src/control_connector.cpp b/src/control_connector.cpp index a596676ec..cba5e0a50 100644 --- a/src/control_connector.cpp +++ b/src/control_connector.cpp @@ -89,12 +89,12 @@ ControlConnectionSettings::ControlConnectionSettings(const Config& config) , use_schema(config.use_schema()) , token_aware_routing(config.token_aware_routing()) { } -ControlConnector::ControlConnector(const Address& address, +ControlConnector::ControlConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback) - : connector_(Memory::allocate(address, - protocol_version, - bind_callback(&ControlConnector::on_connect, this))) + : connector_(new Connector(host, + protocol_version, + bind_callback(&ControlConnector::on_connect, this))) , callback_(callback) , error_code_(CONTROL_CONNECTION_OK) , listener_(NULL) @@ -166,12 +166,13 @@ void ControlConnector::on_success() { // Transfer ownership of the connection to the control connection. control_connection_.reset( - Memory::allocate(connection_, - listener_, - settings_.use_schema, - settings_.token_aware_routing, - server_version_, - listen_addresses_)); + new ControlConnection(connection_, + listener_, + settings_.use_schema, + settings_.token_aware_routing, + server_version_, + dse_server_version_, + listen_addresses_)); control_connection_->set_listener(listener_); @@ -221,9 +222,9 @@ void ControlConnector::query_hosts() { // a valid server version because this version determines which follow up // schema metadata queries are executed. ChainedRequestCallback::Ptr callback( - Memory::allocate( - "local", SELECT_LOCAL, this) - ->chain("peers", SELECT_PEERS)); + new HostsConnectorRequestCallback( + "local", SELECT_LOCAL, this)); + callback = callback->chain("peers", SELECT_PEERS); if (connection_->write_and_flush(callback) < 0) { on_error(CONTROL_CONNECTION_ERROR_HOSTS, @@ -234,10 +235,11 @@ void ControlConnector::query_hosts() { void ControlConnector::handle_query_hosts(HostsConnectorRequestCallback* callback) { ResultResponse::Ptr local_result(callback->result("local")); if (local_result && local_result->row_count() > 0) { - Host::Ptr host(Memory::allocate(connection_->address())); + const Host::Ptr& host = connection_->host(); host->set(&local_result->first_row(), settings_.token_aware_routing); hosts_[host->address()] = host; server_version_ = host->server_version(); + dse_server_version_ = host->dse_server_version(); } else { on_error(CONTROL_CONNECTION_ERROR_HOSTS, "No row found in " + connection_->address_string() + "'s local system table"); @@ -257,7 +259,7 @@ void ControlConnector::handle_query_hosts(HostsConnectorRequestCallback* callbac continue; } - Host::Ptr host(Memory::allocate(address)); + Host::Ptr host(new Host(address)); host->set(rows.row(), settings_.token_aware_routing); listen_addresses_[host->address()] = determine_listen_address(address, row); hosts_[host->address()] = host; @@ -276,7 +278,7 @@ void ControlConnector::query_schema() { ChainedRequestCallback::Ptr callback; if (server_version_ >= VersionNumber(3, 0, 0)) { - callback = ChainedRequestCallback::Ptr(Memory::allocate( + callback = ChainedRequestCallback::Ptr(new SchemaConnectorRequestCallback( "keyspaces", SELECT_KEYSPACES_30, this)); if (settings_.use_schema) { callback = callback @@ -296,7 +298,7 @@ void ControlConnector::query_schema() { } } } else { - callback = ChainedRequestCallback::Ptr(Memory::allocate( + callback = ChainedRequestCallback::Ptr(new SchemaConnectorRequestCallback( "keyspaces", SELECT_KEYSPACES_20, this)); if (settings_.use_schema) { callback = callback diff --git a/src/control_connector.hpp b/src/control_connector.hpp index 5d150979e..bcee23854 100644 --- a/src/control_connector.hpp +++ b/src/control_connector.hpp @@ -103,12 +103,12 @@ class ControlConnector : public RefCounted /** * Constructor * - * @param address The address to connect to. + * @param host The host to connect to. * @param protocol_version The initial protocol version to use for the * connection. * @param callback */ - ControlConnector(const Address& address, + ControlConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback); @@ -240,6 +240,7 @@ class ControlConnector : public RefCounted Connection::Ptr connection_; ControlConnection::Ptr control_connection_; VersionNumber server_version_; + VersionNumber dse_server_version_; HostMap hosts_; /** @@ -257,6 +258,7 @@ class ControlConnector : public RefCounted ControlConnectionListener* listener_; Metrics* metrics_; + Host::Ptr host_; ControlConnectionSettings settings_; }; diff --git a/src/copy_on_write_ptr.hpp b/src/copy_on_write_ptr.hpp index a7712bea3..0b33d6512 100644 --- a/src/copy_on_write_ptr.hpp +++ b/src/copy_on_write_ptr.hpp @@ -27,7 +27,7 @@ template class CopyOnWritePtr { public: CopyOnWritePtr(T* t) - : ptr_(Memory::allocate(t)) {} + : ptr_(new Referenced(t)) {} CopyOnWritePtr(const SharedRefPtr& shared) : ptr_(shared) {} @@ -71,7 +71,7 @@ class CopyOnWritePtr { void detach() { Referenced* temp = ptr_.get(); if (temp->ref != NULL && temp->ref_count() > 1) { - ptr_ = SharedRefPtr(Memory::allocate(Memory::allocate(*(temp->ref)))); + ptr_ = SharedRefPtr(new Referenced(new T(*(temp->ref)))); } } @@ -82,7 +82,7 @@ class CopyOnWritePtr { : ref(ref) {} ~Referenced() { - Memory::deallocate(ref); + delete ref; } T* ref; diff --git a/src/data_type.cpp b/src/data_type.cpp index 17cea8763..bd318ba2f 100644 --- a/src/data_type.cpp +++ b/src/data_type.cpp @@ -34,17 +34,17 @@ CassDataType* cass_data_type_new(CassValueType type) { case CASS_VALUE_TYPE_SET: case CASS_VALUE_TYPE_TUPLE: case CASS_VALUE_TYPE_MAP: - data_type = cass::Memory::allocate(type, false); + data_type = new cass::CollectionType(type, false); data_type->inc_ref(); break; case CASS_VALUE_TYPE_UDT: - data_type = cass::Memory::allocate(false); + data_type = new cass::UserType(false); data_type->inc_ref(); break; case CASS_VALUE_TYPE_CUSTOM: - data_type = cass::Memory::allocate(); + data_type = new cass::CustomType(); data_type->inc_ref(); break; @@ -54,7 +54,7 @@ CassDataType* cass_data_type_new(CassValueType type) { default: if (type < CASS_VALUE_TYPE_LAST_ENTRY) { - data_type = cass::Memory::allocate(type); + data_type = new cass::DataType(type); data_type->inc_ref(); } break; @@ -70,13 +70,13 @@ CassDataType* cass_data_type_new_from_existing(const CassDataType* data_type) { CassDataType* cass_data_type_new_tuple(size_t item_count) { cass::DataType* data_type - = cass::Memory::allocate(CASS_VALUE_TYPE_TUPLE, item_count); + = new cass::CollectionType(CASS_VALUE_TYPE_TUPLE, item_count); data_type->inc_ref(); return CassDataType::to(data_type); } CassDataType* cass_data_type_new_udt(size_t field_count) { - cass::DataType* data_type = cass::Memory::allocate(field_count); + cass::DataType* data_type = new cass::UserType(field_count); data_type->inc_ref(); return CassDataType::to(data_type); } @@ -133,8 +133,8 @@ cass_bool_t cass_data_type_is_frozen(const CassDataType* data_type) { } CassError cass_data_type_type_name(const CassDataType* data_type, - const char** name, - size_t* name_length) { + const char** name, + size_t* name_length) { if (!data_type->is_user_type()) { return CASS_ERROR_LIB_INVALID_VALUE_TYPE; } @@ -349,7 +349,7 @@ CassError cass_data_type_add_sub_type_by_name_n(CassDataType* data_type, CassError cass_data_type_add_sub_value_type(CassDataType* data_type, CassValueType sub_value_type) { cass::DataType::ConstPtr sub_data_type( - cass::Memory::allocate(sub_value_type)); + new cass::DataType(sub_value_type)); return cass_data_type_add_sub_type(data_type, CassDataType::to(sub_data_type.get())); } @@ -359,7 +359,7 @@ CassError cass_data_type_add_sub_value_type_by_name(CassDataType* data_type, const char* name, CassValueType sub_value_type) { cass::DataType::ConstPtr sub_data_type( - cass::Memory::allocate(sub_value_type)); + new cass::DataType(sub_value_type)); return cass_data_type_add_sub_type_by_name(data_type, name, CassDataType::to(sub_data_type.get())); } @@ -369,7 +369,7 @@ CassError cass_data_type_add_sub_value_type_by_name_n(CassDataType* data_type, size_t name_length, CassValueType sub_value_type) { cass::DataType::ConstPtr sub_data_type( - cass::Memory::allocate(sub_value_type)); + new cass::DataType(sub_value_type)); return cass_data_type_add_sub_type_by_name_n(data_type, name, name_length, CassDataType::to(sub_data_type.get())); } @@ -389,7 +389,7 @@ DataType::ConstPtr DataType::create_by_class(StringRef name) { if (value_type == CASS_VALUE_TYPE_UNKNOWN) { return DataType::NIL; } - return ConstPtr(Memory::allocate(value_type)); + return ConstPtr(new DataType(value_type)); } DataType::ConstPtr DataType::create_by_cql(StringRef name) { @@ -397,7 +397,7 @@ DataType::ConstPtr DataType::create_by_cql(StringRef name) { if (value_type == CASS_VALUE_TYPE_UNKNOWN) { return DataType::NIL; } - return ConstPtr(Memory::allocate(value_type)); + return ConstPtr(new DataType(value_type)); } ValueTypes::HashMap ValueTypes::value_types_by_class_; @@ -410,11 +410,11 @@ ValueTypes::ValueTypes() { value_types_by_cql_.set_empty_key(""); #define XX_VALUE_TYPE(name, type, cql, klass) \ - if (sizeof(klass) - 1 > 0) value_types_by_class_[klass] = name; \ - if (sizeof(cql) - 1 > 0) value_types_by_cql_[cql] = name; + if (sizeof(klass) - 1 > 0) value_types_by_class_[klass] = name; \ + if (sizeof(cql) - 1 > 0) value_types_by_cql_[cql] = name; CASS_VALUE_TYPE_MAPPING(XX_VALUE_TYPE) -#undef XX_VALUE_TYPE + #undef XX_VALUE_TYPE } CassValueType ValueTypes::by_class(StringRef name) { @@ -447,7 +447,7 @@ const DataType::ConstPtr& SimpleDataTypeCache::by_value_type(uint16_t value_type DataType::ConstPtr& data_type = cache_[value_type]; if (!data_type) { data_type = DataType::ConstPtr( - Memory::allocate(static_cast(value_type))); + new DataType(static_cast(value_type))); } return data_type; } diff --git a/src/data_type.hpp b/src/data_type.hpp index dac873196..6d008068e 100644 --- a/src/data_type.hpp +++ b/src/data_type.hpp @@ -110,7 +110,7 @@ class DataType : public RefCounted { } virtual DataType::Ptr copy() const { - return Ptr(Memory::allocate(value_type_)); + return Ptr(new DataType(value_type_)); } virtual String to_string() const { @@ -157,7 +157,7 @@ class CustomType : public DataType { } virtual DataType::Ptr copy() const { - return DataType::Ptr(Memory::allocate(class_name_)); + return DataType::Ptr(new CustomType(class_name_)); } virtual String to_string() const { @@ -250,7 +250,7 @@ class CollectionType : public CompositeType { } virtual DataType::Ptr copy() const { - return DataType::Ptr(Memory::allocate(value_type(), types_, is_frozen())); + return DataType::Ptr(new CollectionType(value_type(), types_, is_frozen())); } public: @@ -258,14 +258,14 @@ class CollectionType : public CompositeType { bool is_frozen) { DataType::Vec types; types.push_back(element_type); - return DataType::ConstPtr(Memory::allocate(CASS_VALUE_TYPE_LIST, types, is_frozen)); + return DataType::ConstPtr(new CollectionType(CASS_VALUE_TYPE_LIST, types, is_frozen)); } static DataType::ConstPtr set(DataType::ConstPtr element_type, bool is_frozen) { DataType::Vec types; types.push_back(element_type); - return DataType::ConstPtr(Memory::allocate(CASS_VALUE_TYPE_SET, types, is_frozen)); + return DataType::ConstPtr(new CollectionType(CASS_VALUE_TYPE_SET, types, is_frozen)); } static DataType::ConstPtr map(DataType::ConstPtr key_type, @@ -274,7 +274,7 @@ class CollectionType : public CompositeType { DataType::Vec types; types.push_back(key_type); types.push_back(value_type); - return DataType::ConstPtr(Memory::allocate(CASS_VALUE_TYPE_MAP, types, is_frozen)); + return DataType::ConstPtr(new CollectionType(CASS_VALUE_TYPE_MAP, types, is_frozen)); } }; @@ -314,7 +314,7 @@ class TupleType : public CompositeType { } virtual DataType::Ptr copy() const { - return DataType::Ptr(Memory::allocate(types_, is_frozen())); + return DataType::Ptr(new TupleType(types_, is_frozen())); } }; @@ -418,7 +418,7 @@ class UserType : public DataType { } virtual DataType::Ptr copy() const { - return DataType::Ptr(Memory::allocate(keyspace_, type_name_, fields_.entries(), is_frozen())); + return DataType::Ptr(new UserType(keyspace_, type_name_, fields_.entries(), is_frozen())); } virtual String to_string() const { diff --git a/src/data_type_parser.cpp b/src/data_type_parser.cpp index 4e0229727..dd3260f5b 100644 --- a/src/data_type_parser.cpp +++ b/src/data_type_parser.cpp @@ -120,7 +120,7 @@ DataType::ConstPtr DataTypeCqlNameParser::parse(const String& type, i != end; ++i) { types.push_back(parse(*i, cache, keyspace)); } - return DataType::ConstPtr(Memory::allocate(types, is_frozen)); + return DataType::ConstPtr(new TupleType(types, is_frozen)); } if (iequals(type_name, "frozen")) { @@ -137,21 +137,21 @@ DataType::ConstPtr DataTypeCqlNameParser::parse(const String& type, } if (iequals(type_name, "empty")) { - return DataType::ConstPtr(Memory::allocate(EMPTY_TYPE)); + return DataType::ConstPtr(new CustomType(EMPTY_TYPE)); } if (type_name[0] == '\'') { // Remove single quotes - return DataType::ConstPtr(Memory::allocate(type_name.substr(1, type_name.size() - 2))); + return DataType::ConstPtr(new CustomType(type_name.substr(1, type_name.size() - 2))); } UserType::ConstPtr user_type(keyspace->get_or_create_user_type(type_name, is_frozen)); if (user_type->is_frozen() != is_frozen) { - return UserType::Ptr(Memory::allocate(user_type->keyspace(), - user_type->type_name(), - user_type->fields(), - is_frozen)); + return UserType::Ptr(new UserType(user_type->keyspace(), + user_type->type_name(), + user_type->fields(), + is_frozen)); } return user_type; @@ -380,7 +380,7 @@ DataType::ConstPtr DataTypeClassNameParser::parse_one(const String& type, Simple fields.push_back(UserType::Field(i->first, data_type)); } - return DataType::ConstPtr(Memory::allocate(keyspace, type_name, fields, true)); + return DataType::ConstPtr(new UserType(keyspace, type_name, fields, true)); } if (is_tuple_type(type)) { @@ -399,7 +399,7 @@ DataType::ConstPtr DataTypeClassNameParser::parse_one(const String& type, Simple types.push_back(data_type); } - return DataType::ConstPtr(Memory::allocate(types, true)); + return DataType::ConstPtr(new TupleType(types, true)); } DataType::ConstPtr simple_type(cache.by_class(next)); @@ -407,7 +407,7 @@ DataType::ConstPtr DataTypeClassNameParser::parse_one(const String& type, Simple return simple_type; } - return DataType::ConstPtr(Memory::allocate(next)); + return DataType::ConstPtr(new CustomType(next)); } ParseResult::Ptr DataTypeClassNameParser::parse_with_composite(const String& type, SimpleDataTypeCache& cache) { @@ -421,7 +421,7 @@ ParseResult::Ptr DataTypeClassNameParser::parse_with_composite(const String& typ if (!data_type) { return ParseResult::Ptr(); } - return ParseResult::Ptr(Memory::allocate(data_type, is_reversed(next))); + return ParseResult::Ptr(new ParseResult(data_type, is_reversed(next))); } TypeParamsVec sub_class_names; @@ -469,7 +469,7 @@ ParseResult::Ptr DataTypeClassNameParser::parse_with_composite(const String& typ reversed.push_back(is_reversed(sub_class_names[i])); } - return ParseResult::Ptr(Memory::allocate(true, types, reversed, collections)); + return ParseResult::Ptr(new ParseResult(true, types, reversed, collections)); } bool DataTypeClassNameParser::get_nested_class_name(const String& type, String* class_name) { @@ -634,8 +634,8 @@ void DataTypeClassNameParser::Parser::read_next_identifier(String* name) { } void DataTypeClassNameParser::Parser::parse_error(const String& str, - size_t index, - const char* error) { + size_t index, + const char* error) { LOG_ERROR("Error parsing '%s' at %u index: %s", str.c_str(), static_cast(index), diff --git a/src/dc_aware_policy.cpp b/src/dc_aware_policy.cpp index dd368172c..3a4a26024 100644 --- a/src/dc_aware_policy.cpp +++ b/src/dc_aware_policy.cpp @@ -17,7 +17,6 @@ #include "dc_aware_policy.hpp" #include "logger.hpp" -#include "memory.hpp" #include "request_handler.hpp" #include "scoped_lock.hpp" @@ -31,9 +30,13 @@ DCAwarePolicy::DCAwarePolicy(const String& local_dc, : local_dc_(local_dc) , used_hosts_per_remote_dc_(used_hosts_per_remote_dc) , skip_remote_dcs_for_local_cl_(skip_remote_dcs_for_local_cl) - , local_dc_live_hosts_(Memory::allocate()) + , local_dc_live_hosts_(new HostVec()) , index_(0) { uv_rwlock_init(&available_rwlock_); + if (used_hosts_per_remote_dc_ > 0 || !skip_remote_dcs_for_local_cl) { + LOG_WARN("Remote multi-dc settings have been deprecated and will be removed" + " in the next major release"); + } } DCAwarePolicy::~DCAwarePolicy() { @@ -83,7 +86,7 @@ QueryPlan* DCAwarePolicy::new_query_plan(const String& keyspace, RequestHandler* request_handler, const TokenMap* token_map) { CassConsistency cl = request_handler != NULL ? request_handler->consistency() : CASS_DEFAULT_CONSISTENCY; - return Memory::allocate(this, cl, index_++); + return new DCAwareQueryPlan(this, cl, index_++); } bool DCAwarePolicy::is_host_up(const Address& address) const { @@ -137,11 +140,26 @@ void DCAwarePolicy::on_host_down(const Address& address) { available_.erase(address); } +bool DCAwarePolicy::skip_remote_dcs_for_local_cl() const { + ScopedReadLock rl(&available_rwlock_); + return skip_remote_dcs_for_local_cl_; +} + +size_t DCAwarePolicy::used_hosts_per_remote_dc() const { + ScopedReadLock rl(&available_rwlock_); + return used_hosts_per_remote_dc_; +} + +const String& DCAwarePolicy::local_dc() const { + ScopedReadLock rl(&available_rwlock_); + return local_dc_; +} + void DCAwarePolicy::PerDCHostMap::add_host_to_dc(const String& dc, const Host::Ptr& host) { ScopedWriteLock wl(&rwlock_); Map::iterator i = map_.find(dc); if (i == map_.end()) { - CopyOnWriteHostVec hosts(Memory::allocate()); + CopyOnWriteHostVec hosts(new HostVec()); hosts->push_back(host); map_.insert(Map::value_type(dc, hosts)); } else { @@ -223,7 +241,7 @@ Host::Ptr DCAwarePolicy::DCAwareQueryPlan::compute_next() { } if (!remote_dcs_) { - remote_dcs_.reset(Memory::allocate()); + remote_dcs_.reset(new PerDCHostMap::KeySet()); policy_->per_remote_dc_live_hosts_.copy_dcs(remote_dcs_.get()); } diff --git a/src/dc_aware_policy.hpp b/src/dc_aware_policy.hpp index da9fa9883..4baf7a1eb 100644 --- a/src/dc_aware_policy.hpp +++ b/src/dc_aware_policy.hpp @@ -52,10 +52,14 @@ class DCAwarePolicy : public LoadBalancingPolicy { virtual void on_host_up(const Host::Ptr& host); virtual void on_host_down(const Address& address); + virtual bool skip_remote_dcs_for_local_cl() const; + virtual size_t used_hosts_per_remote_dc() const; + virtual const String& local_dc() const; + virtual LoadBalancingPolicy* new_instance() { - return Memory::allocate(local_dc_, - used_hosts_per_remote_dc_, - skip_remote_dcs_for_local_cl_); + return new DCAwarePolicy(local_dc_, + used_hosts_per_remote_dc_, + skip_remote_dcs_for_local_cl_); } private: @@ -64,7 +68,7 @@ class DCAwarePolicy : public LoadBalancingPolicy { typedef cass::Map Map; typedef Set KeySet; - PerDCHostMap() : no_hosts_(Memory::allocate()) { + PerDCHostMap() : no_hosts_(new HostVec()) { uv_rwlock_init(&rwlock_); } ~PerDCHostMap() { uv_rwlock_destroy(&rwlock_); } diff --git a/src/decoder.hpp b/src/decoder.hpp index 025126a33..31ee20955 100644 --- a/src/decoder.hpp +++ b/src/decoder.hpp @@ -23,12 +23,6 @@ #include "serialization.hpp" #include "small_vector.hpp" -#ifdef _WIN32 -# ifndef snprintf -# define snprintf _snprintf -# endif -#endif - #define CHECK_REMAINING(SIZE, DETAIL) do { \ if (remaining_ < static_cast(SIZE)) { \ notify_error(DETAIL, SIZE); \ diff --git a/src/delayed_connector.cpp b/src/delayed_connector.cpp index 3cc415d6c..bb12ed675 100644 --- a/src/delayed_connector.cpp +++ b/src/delayed_connector.cpp @@ -17,16 +17,15 @@ #include "delayed_connector.hpp" #include "event_loop.hpp" -#include "memory.hpp" namespace cass { -DelayedConnector::DelayedConnector(const Address& address, +DelayedConnector::DelayedConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback) - : connector_(Memory::allocate(address, - protocol_version, - bind_callback(&DelayedConnector::on_connect, this))) + : connector_(new Connector(host, + protocol_version, + bind_callback(&DelayedConnector::on_connect, this))) , callback_(callback) , is_canceled_(false) { } diff --git a/src/delayed_connector.hpp b/src/delayed_connector.hpp index 87b41ab81..aa441d3fc 100644 --- a/src/delayed_connector.hpp +++ b/src/delayed_connector.hpp @@ -19,6 +19,7 @@ #include "callback.hpp" #include "connector.hpp" +#include "host.hpp" #include "ref_counted.hpp" #include "string.hpp" #include "vector.hpp" @@ -41,12 +42,12 @@ class DelayedConnector : public RefCounted { /** * Constructor * - * @param address The address to connect to. + * @param host The host to connect to. * @param protocol_version The protocol version to use for the connection. * @param callback A callback that is called when the connection is connected or * if an error occurred. */ - DelayedConnector(const Address& address, + DelayedConnector(const Host::Ptr& host, ProtocolVersion protocol_version, const Callback& callback); diff --git a/src/event_loop.cpp b/src/event_loop.cpp index cd78d9ebe..51ddfa4c0 100644 --- a/src/event_loop.cpp +++ b/src/event_loop.cpp @@ -189,7 +189,7 @@ void EventLoop::on_task(Async* async) { while (tasks_.dequeue(task)) { if (task) { task->run(this); - Memory::deallocate(task); + delete task; } } @@ -211,7 +211,7 @@ void EventLoop::on_prepare(uv_prepare_t* prepare) { #endif int RoundRobinEventLoopGroup::init(const String& thread_name /*= ""*/) { - for (size_t i = 0; i < threads_.size(); ++i) { + for (size_t i = 0; i < num_threads_; ++i) { int rc = threads_[i].init(thread_name); if (rc != 0) return rc; } @@ -219,7 +219,7 @@ int RoundRobinEventLoopGroup::init(const String& thread_name /*= ""*/) { } int RoundRobinEventLoopGroup::run() { - for (size_t i = 0; i < threads_.size(); ++i) { + for (size_t i = 0; i < num_threads_; ++i) { int rc = threads_[i].run(); if (rc != 0) return rc; } @@ -227,19 +227,19 @@ int RoundRobinEventLoopGroup::run() { } void RoundRobinEventLoopGroup::close_handles() { - for (size_t i = 0; i < threads_.size(); ++i) { + for (size_t i = 0; i < num_threads_; ++i) { threads_[i].close_handles(); } } void RoundRobinEventLoopGroup::join() { - for (size_t i = 0; i < threads_.size(); ++i) { + for (size_t i = 0; i < num_threads_; ++i) { threads_[i].join(); } } EventLoop* RoundRobinEventLoopGroup::add(Task* task) { - EventLoop* event_loop = &threads_[current_.fetch_add(1) % threads_.size()]; + EventLoop* event_loop = &threads_[current_.fetch_add(1) % num_threads_]; event_loop->add(task); return event_loop; } diff --git a/src/event_loop.hpp b/src/event_loop.hpp index d43752488..81633687c 100644 --- a/src/event_loop.hpp +++ b/src/event_loop.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_THREAD_HPP_INCLUDED__ #define __CASS_THREAD_HPP_INCLUDED__ +#include "allocated.hpp" #include "async.hpp" #include "atomic.hpp" #include "cassconfig.hpp" @@ -25,6 +26,7 @@ #include "macros.hpp" #include "loop_watcher.hpp" #include "scoped_lock.hpp" +#include "scoped_ptr.hpp" #include "utils.hpp" #include @@ -37,7 +39,7 @@ class EventLoop; /** * A task executed on an event loop thread. */ -class Task { +class Task : public Allocated { public: virtual ~Task() { } virtual void run(EventLoop* event_loop) = 0; @@ -46,7 +48,7 @@ class Task { /** * An event loop thread. Use tasks to run logic on an event loop. */ -class EventLoop { +class EventLoop : public Allocated { public: EventLoop(); @@ -173,7 +175,7 @@ class EventLoop { /** * A generic group of event loop threads. */ -class EventLoopGroup { +class EventLoopGroup : public Allocated { public: virtual ~EventLoopGroup() { } @@ -209,7 +211,8 @@ class RoundRobinEventLoopGroup : public EventLoopGroup { public: RoundRobinEventLoopGroup(size_t num_threads) : current_(0) - , threads_(num_threads) { } + , threads_(new EventLoop[num_threads]) + , num_threads_(num_threads) { } int init(const String& thread_name = ""); int run(); @@ -218,11 +221,12 @@ class RoundRobinEventLoopGroup : public EventLoopGroup { virtual EventLoop* add(Task* task); virtual EventLoop* get(size_t index) { return &threads_[index]; } - virtual size_t size() const { return threads_.size(); } + virtual size_t size() const { return num_threads_; } private: Atomic current_; - DynamicArray threads_; + ScopedArray threads_; + size_t num_threads_; }; } // namespace cass diff --git a/src/execution_profile.cpp b/src/execution_profile.cpp index 8a425dee4..e17bdebf1 100644 --- a/src/execution_profile.cpp +++ b/src/execution_profile.cpp @@ -6,18 +6,17 @@ */ #include "execution_profile.hpp" -#include "memory.hpp" extern "C" { CassExecProfile* cass_execution_profile_new() { cass::ExecutionProfile* profile = - cass::Memory::allocate(); + new cass::ExecutionProfile(); return CassExecProfile::to(profile); } void cass_execution_profile_free(CassExecProfile* profile) { - cass::Memory::deallocate(profile->from()); + delete profile->from(); } CassError cass_execution_profile_set_request_timeout(CassExecProfile* profile, @@ -40,7 +39,7 @@ CassError cass_execution_profile_set_serial_consistency(CassExecProfile* profile CassError cass_execution_profile_set_load_balance_round_robin(CassExecProfile* profile) { profile->set_load_balancing_policy( - cass::Memory::allocate()); + new cass::RoundRobinPolicy()); return CASS_OK; } @@ -67,9 +66,9 @@ CassError cass_execution_profile_set_load_balance_dc_aware_n(CassExecProfile* pr return CASS_ERROR_LIB_BAD_PARAMS; } profile->set_load_balancing_policy( - cass::Memory::allocate(cass::String(local_dc, local_dc_length), - used_hosts_per_remote_dc, - !allow_remote_dcs_for_local_cl)); + new cass::DCAwarePolicy(cass::String(local_dc, local_dc_length), + used_hosts_per_remote_dc, + !allow_remote_dcs_for_local_cl)); return CASS_OK; } @@ -197,13 +196,13 @@ CassError cass_execution_profile_set_constant_speculative_execution_policy(CassE return CASS_ERROR_LIB_BAD_PARAMS; } profile->set_speculative_execution_policy( - cass::Memory::allocate(constant_delay_ms, - max_speculative_executions)); + new cass::ConstantSpeculativeExecutionPolicy(constant_delay_ms, + max_speculative_executions)); return CASS_OK; } CassError cass_execution_profile_set_no_speculative_execution_policy(CassExecProfile* profile) { - profile->set_speculative_execution_policy(cass::Memory::allocate()); + profile->set_speculative_execution_policy(new cass::NoSpeculativeExecutionPolicy()); return CASS_OK; } diff --git a/src/execution_profile.hpp b/src/execution_profile.hpp index 6f5324975..1382fddf5 100644 --- a/src/execution_profile.hpp +++ b/src/execution_profile.hpp @@ -8,6 +8,7 @@ #ifndef __CASS_EXECUTION_PROFILE_HPP_INCLUDED__ #define __CASS_EXECUTION_PROFILE_HPP_INCLUDED__ +#include "allocated.hpp" #include "blacklist_policy.hpp" #include "blacklist_dc_policy.hpp" #include "cassandra.h" @@ -24,7 +25,7 @@ namespace cass { -class ExecutionProfile { +class ExecutionProfile : public Allocated { public: typedef DenseHashMap Map; @@ -60,10 +61,16 @@ class ExecutionProfile { ContactPointList& blacklist() { return blacklist_; } + const ContactPointList& blacklist() const { + return blacklist_; + } DcList& blacklist_dc() { return blacklist_dc_; } + const DcList& blacklist_dc() const { + return blacklist_dc_; + } bool host_targeting() const { return host_targeting_; } @@ -81,6 +88,10 @@ class ExecutionProfile { latency_aware_routing_settings_ = settings; } + LatencyAwarePolicy::Settings latency_aware_routing_settings() const { + return latency_aware_routing_settings_; + } + bool token_aware_routing() const { return token_aware_routing_; } void set_token_aware_routing(bool is_token_aware) { @@ -91,13 +102,23 @@ class ExecutionProfile { token_aware_routing_shuffle_replicas_ = shuffle_replicas; } + bool token_aware_routing_shuffle_replicas() const { + return token_aware_routing_shuffle_replicas_; + } + ContactPointList& whitelist() { return whitelist_; } + const ContactPointList& whitelist() const { + return whitelist_; + } DcList& whitelist_dc() { return whitelist_dc_; } + const DcList& whitelist_dc() const { + return whitelist_dc_; + } const LoadBalancingPolicy::Ptr& load_balancing_policy() const { return load_balancing_policy_; @@ -114,27 +135,27 @@ class ExecutionProfile { LoadBalancingPolicy* chain = load_balancing_policy_->new_instance(); if (!blacklist_.empty()) { - chain = Memory::allocate(chain, blacklist_); + chain = new BlacklistPolicy(chain, blacklist_); } if (!whitelist_.empty()) { - chain = Memory::allocate(chain, whitelist_); + chain = new WhitelistPolicy(chain, whitelist_); } if (!blacklist_dc_.empty()) { - chain = Memory::allocate(chain, blacklist_dc_); + chain = new BlacklistDCPolicy(chain, blacklist_dc_); } if (!whitelist_dc_.empty()) { - chain = Memory::allocate(chain, whitelist_dc_); + chain = new WhitelistDCPolicy(chain, whitelist_dc_); } if (token_aware_routing()) { - chain = Memory::allocate(chain, - token_aware_routing_shuffle_replicas_); + chain = new TokenAwarePolicy(chain, + token_aware_routing_shuffle_replicas_); } if (latency_aware()) { - chain = Memory::allocate(chain, - latency_aware_routing_settings_); + chain = new LatencyAwarePolicy(chain, + latency_aware_routing_settings_); } if (host_targeting()) { - chain = Memory::allocate(chain); + chain = new HostTargetingPolicy(chain); } load_balancing_policy_.reset(chain); diff --git a/src/future.cpp b/src/future.cpp index 7e474fcf5..6ee0b3f4b 100644 --- a/src/future.cpp +++ b/src/future.cpp @@ -79,9 +79,9 @@ const CassPrepared* cass_future_get_prepared(CassFuture* future) { return NULL; } - cass::Prepared* prepared = cass::Memory::allocate(result, - response_future->prepare_request, - *response_future->schema_metadata); + cass::Prepared* prepared = new cass::Prepared(result, + response_future->prepare_request, + *response_future->schema_metadata); prepared->inc_ref(); return CassPrepared::to(prepared); } diff --git a/src/future.hpp b/src/future.hpp index c63ccd6c2..e4567d636 100644 --- a/src/future.hpp +++ b/src/future.hpp @@ -45,7 +45,7 @@ class Future : public RefCounted { FUTURE_TYPE_RESPONSE }; - struct Error { + struct Error : public Allocated { Error(CassError code, const String& message) : code(code) , message(message) {} @@ -127,7 +127,7 @@ class Future : public RefCounted { void internal_set(ScopedMutex& lock); void internal_set_error(CassError code, const String& message, ScopedMutex& lock) { - error_.reset(Memory::allocate(code, message)); + error_.reset(new Error(code, message)); internal_set(lock); } diff --git a/src/hash_table.hpp b/src/hash_table.hpp index 9ab2b83cd..2cc202411 100644 --- a/src/hash_table.hpp +++ b/src/hash_table.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_HASH_INDEX_HPP_INCLUDED__ #define __CASS_HASH_INDEX_HPP_INCLUDED__ +#include "allocated.hpp" #include "hash.hpp" #include "macros.hpp" #include "small_vector.hpp" @@ -45,7 +46,7 @@ struct HashTableEntry { }; template -class CaseInsensitiveHashTable { +class CaseInsensitiveHashTable : public Allocated { public: typedef SmallVector EntryVec; diff --git a/src/host.cpp b/src/host.cpp index 5a76d4856..f484112d5 100644 --- a/src/host.cpp +++ b/src/host.cpp @@ -111,11 +111,10 @@ void Host::set(const Row* row, bool use_tokens) { String dse_version_str; row->get_string_by_name("dse_version", &dse_version_str); - VersionNumber dse_version; - if (dse_version.parse(dse_version_str)) { + if (dse_server_version_.parse(dse_version_str)) { // Versions before DSE 6.7 erroneously return they support Cassandra 4.0.0 // features even though they don't. - if (dse_version < VersionNumber(6, 7, 0)) { + if (dse_server_version_ < VersionNumber(6, 7, 0)) { server_version_ = VersionNumber(3, 11, 0); } } else { diff --git a/src/host.hpp b/src/host.hpp index 086b12a32..3adce5468 100644 --- a/src/host.hpp +++ b/src/host.hpp @@ -18,6 +18,7 @@ #define __CASS_HOST_HPP_INCLUDED__ #include "address.hpp" +#include "allocated.hpp" #include "atomic.hpp" #include "copy_on_write_ptr.hpp" #include "get_time.hpp" @@ -101,7 +102,9 @@ class Host : public RefCounted { : address_(address) , rack_id_(0) , dc_id_(0) - , address_string_(address.to_string()) { } + , address_string_(address.to_string()) + , connection_count_(0) + , inflight_request_count_(0) { } const Address& address() const { return address_; } const String& address_string() const { return address_string_; } @@ -134,6 +137,10 @@ class Host : public RefCounted { return server_version_; } + const VersionNumber& dse_server_version() const { + return dse_server_version_; + } + String to_string() const { OStringStream ss; ss << address_string_; @@ -145,7 +152,7 @@ class Host : public RefCounted { void enable_latency_tracking(uint64_t scale, uint64_t min_measured) { if (!latency_tracker_) { - latency_tracker_.reset(Memory::allocate(scale, (30LL * min_measured) / 100LL)); + latency_tracker_.reset(new LatencyTracker(scale, (30LL * min_measured) / 100LL)); } } @@ -163,8 +170,32 @@ class Host : public RefCounted { return TimestampedAverage(); } + void increment_connection_count() { + connection_count_.fetch_add(1, MEMORY_ORDER_RELAXED); + } + + void decrement_connection_count() { + connection_count_.fetch_sub(1, MEMORY_ORDER_RELAXED); + } + + int32_t connection_count() const { + return connection_count_.load(MEMORY_ORDER_RELAXED); + } + + void increment_inflight_requests() { + inflight_request_count_.fetch_add(1, MEMORY_ORDER_RELAXED); + } + + void decrement_inflight_requests() { + inflight_request_count_.fetch_sub(1, MEMORY_ORDER_RELAXED); + } + + int32_t inflight_request_count() const { + return inflight_request_count_.load(MEMORY_ORDER_RELAXED); + } + private: - class LatencyTracker { + class LatencyTracker : public Allocated { public: LatencyTracker(uint64_t scale_ns, uint64_t threshold_to_account) : scale_ns_(scale_ns) @@ -192,10 +223,13 @@ class Host : public RefCounted { uint32_t dc_id_; String address_string_; VersionNumber server_version_; + VersionNumber dse_server_version_; String rack_; String dc_; String partitioner_; Vector tokens_; + Atomic connection_count_; + Atomic inflight_request_count_; ScopedPtr latency_tracker_; diff --git a/src/host_targeting_policy.cpp b/src/host_targeting_policy.cpp index 615c6f903..c9a0ee17b 100644 --- a/src/host_targeting_policy.cpp +++ b/src/host_targeting_policy.cpp @@ -44,7 +44,7 @@ QueryPlan* HostTargetingPolicy::new_query_plan(const String& keyspace, return child_plan; } - return Memory::allocate(it->second, child_plan); + return new HostTargetingQueryPlan(it->second, child_plan); } void HostTargetingPolicy::on_host_added(const SharedRefPtr& host) { diff --git a/src/host_targeting_policy.hpp b/src/host_targeting_policy.hpp index 6e146c45a..2130f5a2d 100644 --- a/src/host_targeting_policy.hpp +++ b/src/host_targeting_policy.hpp @@ -37,7 +37,7 @@ class HostTargetingPolicy : public ChainedLoadBalancingPolicy { const TokenMap* token_map); virtual LoadBalancingPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance()); + return new HostTargetingPolicy(child_policy_->new_instance()); } virtual void on_host_added(const Host::Ptr& host); diff --git a/src/is_polymorphic.hpp b/src/is_polymorphic.hpp deleted file mode 100644 index bed9940f1..000000000 --- a/src/is_polymorphic.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - Copyright (c) DataStax, Inc. - - This software can be used solely with DataStax Enterprise. Please consult the - license at http://www.datastax.com/terms/datastax-dse-driver-license-terms -*/ - -// The implementation of cass::IsPolymorphic<> was taken from Boost and is under -// this copyright/license: - -// (C) Copyright John Maddock 2000. -// Use, modification and distribution are subject to the Boost Software License, -// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt). -// -// See http://www.boost.org/libs/type_traits for most recent version including documentation. - -#ifndef __CASS_IS_POLYMORPHIC_HPP_INCLUDED__ -#define __CASS_IS_POLYMORPHIC_HPP_INCLUDED__ - -#ifdef _MSC_VER -#include -#endif - -namespace cass { - -#ifdef _MSC_VER -template -class IsPolymorphic : public std::is_polymorphic { }; -#else -struct FalseType { static const bool value = false; }; -struct TrueType { static const bool value = true; }; - -template struct IsIntegral : public FalseType { }; -template struct IsIntegral : public IsIntegral { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; -template<> struct IsIntegral : public TrueType { }; - -template struct IsFloating : public FalseType { }; -template struct IsFloating : public IsFloating { }; -template <> struct IsFloating : public FalseType { }; -template <> struct IsFloating : public FalseType { }; - -template struct IsReference : public FalseType { }; -template struct IsReference : public TrueType { }; - -template struct IsArray : public FalseType { }; -template struct IsArray : public TrueType { }; -template struct IsArray : public TrueType { }; - -template struct IsVoid : public FalseType { }; -template <> struct IsVoid : public TrueType { }; -template <> struct IsVoid : public TrueType { }; - -// *Important* This doesn't work for enums and unions -template -struct IsClass { - static const bool value= !IsIntegral::value && !IsFloating::value && - !IsReference::value && !IsArray::value && - !IsVoid::value; -}; - -// This is how Boost implements its version of is_polymorphic<> which seems to -// be compatabile with the compilers we care about. This checks the difference between -// a virtual derived class and a non-virtual derived class and if the size are the same -// then it's a polymorphic type because adding a virtual destructor in a derived class -// didn't add vtable pointer to the size. -template -struct IsPolymorphicImpl { - struct Type1 : public T { - Type1(); - ~Type1(); - Type1(const Type1&); - Type1& operator=(const Type1&); - char padding[256]; - }; - - struct Type2 : public T { - Type2(); - virtual ~Type2(); // Add a vtable to this type - Type2(const Type2&); - Type2& operator=(const Type2&); - char padding[256]; - }; - - static const bool value = (sizeof(Type1) == sizeof(Type2)); -}; - -template -class IsPolymorphicImplNotClass : public FalseType { }; - -template -struct IsPolymorphicSelector { - template - struct Rebind { - typedef IsPolymorphicImplNotClass Type; - }; -}; - -template <> -struct IsPolymorphicSelector { - template - struct Rebind { - typedef IsPolymorphicImpl Type; - }; -}; - -template -struct IsPolymorphic { - typedef IsPolymorphicSelector::value> Selector; - typedef typename Selector::template Rebind Binder; - static const bool value = Binder::Type::value; -}; - -#endif - -} // namespace cass - -#endif diff --git a/src/iterator.cpp b/src/iterator.cpp index 4906a1b9e..5ccfcbb5c 100644 --- a/src/iterator.cpp +++ b/src/iterator.cpp @@ -26,7 +26,7 @@ extern "C" { void cass_iterator_free(CassIterator* iterator) { - cass::Memory::deallocate(iterator->from()); + delete iterator->from(); } cass_bool_t cass_iterator_next(CassIterator* iterator) { @@ -38,39 +38,39 @@ CassIteratorType cass_iterator_type(CassIterator* iterator) { } CassIterator* cass_iterator_from_result(const CassResult* result) { - return CassIterator::to(cass::Memory::allocate(result)); + return CassIterator::to(new cass::ResultIterator(result)); } CassIterator* cass_iterator_from_row(const CassRow* row) { - return CassIterator::to(cass::Memory::allocate(row)); + return CassIterator::to(new cass::RowIterator(row)); } CassIterator* cass_iterator_from_collection(const CassValue* value) { if (value->is_null() || !value->is_collection()) { return NULL; } - return CassIterator::to(cass::Memory::allocate(value)); + return CassIterator::to(new cass::CollectionIterator(value)); } CassIterator* cass_iterator_from_tuple(const CassValue* value) { if (value->is_null() || !value->is_tuple()) { return NULL; } - return CassIterator::to(cass::Memory::allocate(value)); + return CassIterator::to(new cass::TupleIterator(value)); } CassIterator* cass_iterator_from_map(const CassValue* value) { if (value->is_null() || !value->is_map()) { return NULL; } - return CassIterator::to(cass::Memory::allocate(value)); + return CassIterator::to(new cass::MapIterator(value)); } CassIterator* cass_iterator_fields_from_user_type(const CassValue* value) { if (value->is_null() || !value->is_user_type()) { return NULL; } - return CassIterator::to(cass::Memory::allocate(value)); + return CassIterator::to(new cass::UserTypeFieldIterator(value)); } CassError cass_iterator_get_user_type_field_name(const CassIterator* iterator, diff --git a/src/iterator.hpp b/src/iterator.hpp index 54218f29c..f46731702 100644 --- a/src/iterator.hpp +++ b/src/iterator.hpp @@ -17,12 +17,13 @@ #ifndef __CASS_ITERATOR_HPP_INCLUDED__ #define __CASS_ITERATOR_HPP_INCLUDED__ +#include "allocated.hpp" #include "cassandra.h" #include "external.hpp" namespace cass { -class Iterator { +class Iterator : public Allocated { public: Iterator(CassIteratorType type) : type_(type) {} diff --git a/src/json.hpp b/src/json.hpp index e9e3ccf9b..67dbd252e 100644 --- a/src/json.hpp +++ b/src/json.hpp @@ -18,16 +18,42 @@ #define __CASS_JSON_HPP_INCLUDED__ #include "memory.hpp" + +namespace cass { +namespace json { + +template +static T* new_() { + T* ptr = reinterpret_cast(Memory::malloc(sizeof(T))); + return new (ptr) T(); +} + +// Doesn't work for polymorphic types +// TODO: Add static_assert() for !is_polymorphic +template +static void delete_(T* ptr) { + if (!ptr) return; + ptr->~T(); + Memory::free(ptr); +} + +} } // namespace cass::json + #define RAPIDJSON_NAMESPACE cass::rapidjson #define RAPIDJSON_NAMESPACE_BEGIN namespace cass { namespace rapidjson { #define RAPIDJSON_NAMESPACE_END } } -#define RAPIDJSON_NEW(x) cass::Memory::allocate -#define RAPIDJSON_DELETE(x) cass::Memory::deallocate(x) +#define RAPIDJSON_NEW(x) cass::json::new_ +#define RAPIDJSON_DELETE(x) cass::json::delete_(x) #include "third_party/rapidjson/rapidjson/document.h" -#include "third_party/rapidjson/rapidjson/writer.h" #include "third_party/rapidjson/rapidjson/stringbuffer.h" - +#ifndef JSON_DEBUG +# include "third_party/rapidjson/rapidjson/writer.h" +# define JSON_WRITE_TYPE Writer +#else +# include "third_party/rapidjson/rapidjson/prettywriter.h" +# define JSON_WRITE_TYPE PrettyWriter +#endif namespace cass { namespace json { @@ -52,9 +78,9 @@ typedef cass::rapidjson::GenericValue, cass::rapidjson:: typedef cass::rapidjson::GenericStringBuffer, json::Allocator> StringBuffer; template, typename TargetEncoding = cass::rapidjson::UTF8<>, typename StackAllocator = json::Allocator, unsigned writeFlags = cass::rapidjson::kWriteDefaultFlags> -class Writer : public cass::rapidjson::Writer { +class Writer : public cass::rapidjson::JSON_WRITE_TYPE { public: - typedef cass::rapidjson::Writer Type; + typedef cass::rapidjson::JSON_WRITE_TYPE Type; explicit Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = Type::kDefaultLevelDepth) : Type(os, stackAllocator, levelDepth) { } diff --git a/src/latency_aware_policy.cpp b/src/latency_aware_policy.cpp index 6a37ffbb1..0ea1bdff4 100644 --- a/src/latency_aware_policy.cpp +++ b/src/latency_aware_policy.cpp @@ -47,10 +47,10 @@ void LatencyAwarePolicy::close_handles() { QueryPlan* LatencyAwarePolicy::new_query_plan(const String& keyspace, RequestHandler* request_handler, const TokenMap* token_map) { - return Memory::allocate(this, - child_policy_->new_query_plan(keyspace, - request_handler, - token_map)); + return new LatencyAwareQueryPlan(this, + child_policy_->new_query_plan(keyspace, + request_handler, + token_map)); } void LatencyAwarePolicy::on_host_added(const Host::Ptr& host) { diff --git a/src/latency_aware_policy.hpp b/src/latency_aware_policy.hpp index e27b893a9..39e5474e3 100644 --- a/src/latency_aware_policy.hpp +++ b/src/latency_aware_policy.hpp @@ -46,7 +46,7 @@ class LatencyAwarePolicy : public ChainedLoadBalancingPolicy { : ChainedLoadBalancingPolicy(child_policy) , min_average_(-1) , settings_(settings) - , hosts_(Memory::allocate()) {} + , hosts_(new HostVec()) {} virtual ~LatencyAwarePolicy() {} @@ -60,7 +60,7 @@ class LatencyAwarePolicy : public ChainedLoadBalancingPolicy { const TokenMap* token_map); virtual LoadBalancingPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), settings_); + return new LatencyAwarePolicy(child_policy_->new_instance(), settings_); } virtual void on_host_added(const Host::Ptr& host); diff --git a/src/load_balancing.hpp b/src/load_balancing.hpp index 7ac3dd027..db7c8085d 100644 --- a/src/load_balancing.hpp +++ b/src/load_balancing.hpp @@ -17,10 +17,10 @@ #ifndef __CASS_LOAD_BALANCING_HPP_INCLUDED__ #define __CASS_LOAD_BALANCING_HPP_INCLUDED__ +#include "allocated.hpp" #include "cassandra.h" #include "constants.hpp" #include "host.hpp" -#include "memory.hpp" #include "request.hpp" #include "string.hpp" #include "vector.hpp" @@ -58,7 +58,7 @@ inline bool is_dc_local(CassConsistency cl) { return cl == CASS_CONSISTENCY_LOCAL_ONE || cl == CASS_CONSISTENCY_LOCAL_QUORUM; } -class QueryPlan { +class QueryPlan : public Allocated { public: virtual ~QueryPlan() {} virtual Host::Ptr compute_next() = 0; @@ -126,7 +126,13 @@ class ChainedLoadBalancingPolicy : public LoadBalancingPolicy { return child_policy_->init(connected_host, hosts, random); } - virtual CassHostDistance distance(const Host::Ptr& host) const { return child_policy_->distance(host); } + virtual const LoadBalancingPolicy::Ptr& child_policy() const { + return child_policy_; + } + + virtual CassHostDistance distance(const Host::Ptr& host) const { + return child_policy_->distance(host); + } virtual bool is_host_up(const Address& address) const { return child_policy_->is_host_up(address); diff --git a/src/loop_watcher.hpp b/src/loop_watcher.hpp index 14f00393b..16c1242bf 100644 --- a/src/loop_watcher.hpp +++ b/src/loop_watcher.hpp @@ -17,9 +17,9 @@ #ifndef __CASS_LOOP_WATCHER_HPP_INCLUDED__ #define __CASS_LOOP_WATCHER_HPP_INCLUDED__ +#include "allocated.hpp" #include "callback.hpp" #include "macros.hpp" -#include "memory.hpp" #include @@ -48,7 +48,7 @@ class LoopWatcher { int start(uv_loop_t* loop, const Callback& callback) { int rc = 0; if (handle_ == NULL) { - handle_ = Memory::allocate(); + handle_ = new AllocatedT(); handle_->loop = NULL; handle_->data = this; } @@ -82,7 +82,7 @@ class LoopWatcher { void close_handle() { if (handle_ != NULL) { if (state_ == CLOSED) { // The handle was allocated, but initialization failed. - Memory::deallocate(handle_); + delete handle_; } else { // If initialized or started then close the handle properly. uv_close(reinterpret_cast(handle_), on_close); } @@ -102,7 +102,7 @@ class LoopWatcher { } static void on_close(uv_handle_t* handle) { - Memory::deallocate(reinterpret_cast(handle)); + delete reinterpret_cast*>(handle); } private: @@ -113,7 +113,7 @@ class LoopWatcher { }; private: - HandleType* handle_; + AllocatedT* handle_; State state_; Callback callback_; diff --git a/src/map.hpp b/src/map.hpp index 86ab655c3..1bc285c4a 100644 --- a/src/map.hpp +++ b/src/map.hpp @@ -8,6 +8,7 @@ #ifndef __DSE_MAP_HPP_INCLUDED__ #define __DSE_MAP_HPP_INCLUDED__ +#include "allocated.hpp" #include "allocator.hpp" #include @@ -15,7 +16,9 @@ namespace cass { template > -class Map : public std::map > > { +class Map : + public Allocated, + public std::map > > { public: typedef cass::Allocator > Allocator; diff --git a/src/memory.hpp b/src/memory.hpp index d03e7ed86..5f3bc6caa 100644 --- a/src/memory.hpp +++ b/src/memory.hpp @@ -9,207 +9,37 @@ #define __DSE_MEMORY_HPP_INCLUDED__ #include "cassandra.h" -#include "is_polymorphic.hpp" - -#include -#include -#include +#include namespace cass { -// Placement new can return a pointer to the polymorphic class instead of the -// base/allocated address in the case of multiple inheritance. In this case -// dynamic_cast() can be used to get the original base/allocated address, -// but it's only valid for polymorphic types. - -template -struct GetAllocatedPtr { - static void* cast(T* ptr) { return reinterpret_cast(ptr); } -}; - -template -struct GetAllocatedPtr { - static void* cast(T* ptr) { return dynamic_cast(ptr); } -}; - class Memory { public: static void set_functions(CassMallocFunction malloc_func, CassReallocFunction realloc_func, CassFreeFunction free_func); - template - static T* allocate() { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(); - } - - template - static T* allocate(const Arg1& arg1) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9, const Arg10& arg10) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); - } - - template - static T* allocate(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6, const Arg7& arg7, const Arg8& arg8, const Arg9& arg9, const Arg10& arg10, const Arg11& arg11) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); - } - - template - static T* allocate(Arg1& arg1) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6, Arg7& arg7) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6, Arg7& arg7, Arg8& arg8) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6, Arg7& arg7, Arg8& arg8, Arg9& arg9) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6, Arg7& arg7, Arg8& arg8, Arg9& arg9, Arg10& arg10) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); - } - - template - static T* allocate(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6, Arg7& arg7, Arg8& arg8, Arg9& arg9, Arg10& arg10, Arg11& arg11) { - T* ptr = reinterpret_cast(malloc(sizeof(T))); - return new (ptr) T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); - } - - template - static void deallocate(T* ptr) { - if (!ptr) return; - void* base_ptr = GetAllocatedPtr::value>::cast(ptr); - ptr->~T(); - free(base_ptr); - } - - template - static void deallocate(const T* ptr) { - deallocate(const_cast(ptr)); - } - static CassMallocFunction malloc_func() { return malloc_func_; } static CassReallocFunction realloc_func() { return realloc_func_; } static CassFreeFunction free_func() { return free_func_; } static void* malloc(size_t size) { if (malloc_func_ == NULL) { - return ::malloc(size); + return std::malloc(size); } return malloc_func_(size); } static void* realloc(void* ptr, size_t size) { if (realloc_func_ == NULL) { - return ::realloc(ptr, size); + return std::realloc(ptr, size); } return realloc_func_(ptr, size); } static void free(void* ptr) { if (free_func_ == NULL) { - return ::free(ptr); + return std::free(ptr); } free_func_(ptr); } @@ -220,51 +50,6 @@ class Memory { static CassFreeFunction free_func_; }; -template -class DynamicArray { -public: - DynamicArray(size_t n) - : n_(n) - , elements_(reinterpret_cast(Memory::malloc(sizeof(T) * n_))) { - for (size_t i = 0; i < n_; ++i) { - new (elements_ + i) T(); - } - } - - DynamicArray(const DynamicArray& other) - : n_(other.n_) - , elements_(reinterpret_cast(Memory::malloc(sizeof(T) * n_))) { - for (size_t i = 0; i < n_; ++i) { - new (elements_ + i) T(other[i]); - } - } - - ~DynamicArray() { - for (size_t i = 0; i < n_; ++i) { - (elements_ + i)->~T(); - } - Memory::free(elements_); - } - - T& operator[](size_t index) { - return *(elements_ + index); - } - - const T& operator[](size_t index) const { - return *(elements_ + index); - } - - size_t size() const { return n_; } - - T* data() { return elements_; } - - const T* data() const { return elements_; } - -private: - const size_t n_; - T* const elements_; -}; - } // namespace cass #endif diff --git a/src/metadata.cpp b/src/metadata.cpp index be408766e..b8c95d672 100644 --- a/src/metadata.cpp +++ b/src/metadata.cpp @@ -62,7 +62,7 @@ static cass::String& append_arguments(cass::String& full_name, extern "C" { void cass_schema_meta_free(const CassSchemaMeta* schema_meta) { - cass::Memory::deallocate(schema_meta->from()); + delete schema_meta->from(); } cass_uint32_t cass_schema_meta_snapshot_version(const CassSchemaMeta* schema_meta) { @@ -78,7 +78,7 @@ CassVersion cass_schema_meta_version(const CassSchemaMeta* schema_meta) { } const CassKeyspaceMeta* cass_schema_meta_keyspace_by_name(const CassSchemaMeta* schema_meta, - const char* keyspace) { + const char* keyspace) { return cass_schema_meta_keyspace_by_name_n(schema_meta, keyspace, SAFE_STRLEN(keyspace)); } @@ -128,8 +128,8 @@ const CassDataType* cass_keyspace_meta_user_type_by_name(const CassKeyspaceMeta* } const CassDataType* cass_keyspace_meta_user_type_by_name_n(const CassKeyspaceMeta* keyspace_meta, - const char* type, - size_t type_length) { + const char* type, + size_t type_length) { return CassDataType::to(keyspace_meta->get_user_type(cass::String(type, type_length))); } @@ -406,7 +406,7 @@ cass_column_meta_field_by_name_n(const CassColumnMeta* column_meta, } void cass_index_meta_name(const CassIndexMeta* index_meta, - const char** name, size_t* name_length) { + const char** name, size_t* name_length) { *name = index_meta->name().data(); *name_length = index_meta->name().size(); } @@ -433,34 +433,34 @@ cass_index_meta_field_by_name(const CassIndexMeta* index_meta, const CassValue* cass_index_meta_field_by_name_n(const CassIndexMeta* index_meta, - const char* name, size_t name_length) { + const char* name, size_t name_length) { return CassValue::to(index_meta->get_field(cass::String(name, name_length))); } void cass_function_meta_name(const CassFunctionMeta* function_meta, - const char** name, - size_t* name_length) { + const char** name, + size_t* name_length) { *name = function_meta->simple_name().data(); *name_length = function_meta->simple_name().size(); } void cass_function_meta_full_name(const CassFunctionMeta* function_meta, - const char** full_name, - size_t* full_name_length) { + const char** full_name, + size_t* full_name_length) { *full_name = function_meta->name().data(); *full_name_length = function_meta->name().size(); } void cass_function_meta_body(const CassFunctionMeta* function_meta, - const char** body, - size_t* body_length) { + const char** body, + size_t* body_length) { *body = function_meta->body().data(); *body_length = function_meta->body().size(); } void cass_function_meta_language(const CassFunctionMeta* function_meta, - const char** language, - size_t* language_length) { + const char** language, + size_t* language_length) { *language = function_meta->language().data(); *language_length = function_meta->language().size(); } @@ -712,8 +712,8 @@ const CassIndexMeta* cass_iterator_get_index_meta(const CassIterator* iterator) } CassError cass_iterator_get_meta_field_name(const CassIterator* iterator, - const char** name, - size_t* name_length) { + const char** name, + size_t* name_length) { if (iterator->type() != CASS_ITERATOR_TYPE_META_FIELD) { return CASS_ERROR_LIB_BAD_PARAMS; } @@ -1018,7 +1018,7 @@ void MetadataBase::add_json_list_field(const Row* row, const String& name) { return; } - Collection collection(CollectionType::list(DataType::Ptr(Memory::allocate(CASS_VALUE_TYPE_TEXT)), false), + Collection collection(CollectionType::list(DataType::Ptr(new DataType(CASS_VALUE_TYPE_TEXT)), false), d.Size()); for (json::Value::ConstValueIterator i = d.Begin(); i != d.End(); ++i) { collection.append(cass::CassString(i->GetString(), i->GetStringLength())); @@ -1058,8 +1058,8 @@ const Value* MetadataBase::add_json_map_field(const Row* row, const String& name return (fields_[name] = MetadataField(name)).value(); } - Collection collection(CollectionType::map(DataType::Ptr(Memory::allocate(CASS_VALUE_TYPE_TEXT)), - DataType::Ptr(Memory::allocate(CASS_VALUE_TYPE_TEXT)), + Collection collection(CollectionType::map(DataType::Ptr(new DataType(CASS_VALUE_TYPE_TEXT)), + DataType::Ptr(new DataType(CASS_VALUE_TYPE_TEXT)), false), 2 * d.MemberCount()); for (json::Value::ConstMemberIterator i = d.MemberBegin(); i != d.MemberEnd(); ++i) { @@ -1111,7 +1111,7 @@ void KeyspaceMetadata::internal_add_table(const TableMetadata::Ptr& table, // Copy all the views and update the table and keyspace views for (ViewMetadata::Vec::const_iterator i = views.begin(); i != views.end(); ++i) { - ViewMetadata::Ptr view(Memory::allocate(**i, table.get())); + ViewMetadata::Ptr view(new ViewMetadata(**i, table.get())); table->add_view(view); (*views_)[view->name()] = view; } @@ -1137,7 +1137,7 @@ void KeyspaceMetadata::add_view(const ViewMetadata::Ptr& view) { void KeyspaceMetadata::drop_table_or_view(const String& table_or_view_name) { TableMetadata::Map::iterator table_it = tables_->find(table_or_view_name); if (table_it != tables_->end()) { // The name is for a table, remove the - // table and views from keyspace + // table and views from keyspace TableMetadata::Ptr table(table_it->second); // Cassandra doesn't allow for tables to be dropped while it has active // views, but it could be possible for the drop events to arrive out of @@ -1160,7 +1160,7 @@ void KeyspaceMetadata::drop_table_or_view(const String& table_or_view_name) { } // Create and add a new copy of the base table - TableMetadata::Ptr table(Memory::allocate(*view->base_table())); + TableMetadata::Ptr table(new TableMetadata(*view->base_table())); internal_add_table(table, views); // Remove the dropped view @@ -1173,8 +1173,8 @@ const UserType::Ptr& KeyspaceMetadata::get_or_create_user_type(const String& nam UserType::Map::iterator i = user_types_->find(name); if (i == user_types_->end()) { i = user_types_->insert(std::make_pair(name, - UserType::Ptr(Memory::allocate(MetadataBase::name(), name, - is_frozen)))).first; + UserType::Ptr(new UserType(MetadataBase::name(), name, + is_frozen)))).first; } return i->second; } @@ -1401,10 +1401,10 @@ void TableMetadataBase::build_keys_and_sort(const VersionNumber& server_version, } key_alias = ss.str(); } - partition_key_.push_back(ColumnMetadata::Ptr(Memory::allocate(key_alias, - partition_key_.size(), - CASS_COLUMN_TYPE_PARTITION_KEY, - key_validator->types()[i]))); + partition_key_.push_back(ColumnMetadata::Ptr(new ColumnMetadata(key_alias, + partition_key_.size(), + CASS_COLUMN_TYPE_PARTITION_KEY, + key_validator->types()[i]))); } } @@ -1443,10 +1443,10 @@ void TableMetadataBase::build_keys_and_sort(const VersionNumber& server_version, } column_alias = ss.str(); } - clustering_key_.push_back(ColumnMetadata::Ptr(Memory::allocate(column_alias, - clustering_key_.size(), - CASS_COLUMN_TYPE_CLUSTERING_KEY, - comparator->types()[i]))); + clustering_key_.push_back(ColumnMetadata::Ptr(new ColumnMetadata(column_alias, + clustering_key_.size(), + CASS_COLUMN_TYPE_CLUSTERING_KEY, + comparator->types()[i]))); clustering_key_order_.push_back(comparator->reversed()[i] ? CASS_CLUSTERING_ORDER_DESC : CASS_CLUSTERING_ORDER_ASC); } @@ -1496,7 +1496,7 @@ void TableMetadata::add_column(const VersionNumber& server_version, const Column } const ViewMetadata* TableMetadata::get_view(const String& name) const { - ViewMetadata::Vec::const_iterator i = std::lower_bound(views_.begin(), views_.end(), name); + ViewMetadata::Vec::const_iterator i = std::lower_bound(views_.begin(), views_.end(), name); if (i == views_.end() || (*i)->name() != name) return NULL; return i->get(); } @@ -1617,13 +1617,13 @@ FunctionMetadata::FunctionMetadata(const VersionNumber& server_version, SimpleDa value1 = add_field(buffer, row, "body"); if (value1 != NULL && value1->value_type() == CASS_VALUE_TYPE_VARCHAR) { - body_ = value1->to_string_ref(); + body_ = value1->to_string_ref(); } value1 = add_field(buffer, row, "language"); if (value1 != NULL && value1->value_type() == CASS_VALUE_TYPE_VARCHAR) { - language_ = value1->to_string_ref(); + language_ = value1->to_string_ref(); } value1 = add_field(buffer, row, "called_on_null_input"); @@ -1726,7 +1726,7 @@ AggregateMetadata::AggregateMetadata(const VersionNumber& server_version, Simple IndexMetadata::Ptr IndexMetadata::from_row(const String& index_name, const RefBuffer::Ptr& buffer, const Row* row) { - IndexMetadata::Ptr index(Memory::allocate(index_name)); + IndexMetadata::Ptr index(new IndexMetadata(index_name)); StringRef kind; const Value* value = index->add_field(buffer, row, "kind"); @@ -1759,7 +1759,7 @@ void IndexMetadata::update(StringRef kind, const Value* options) { IndexMetadata::Ptr IndexMetadata::from_legacy(const String& index_name, const ColumnMetadata* column, const RefBuffer::Ptr& buffer, const Row* row) { - IndexMetadata::Ptr index(Memory::allocate(index_name)); + IndexMetadata::Ptr index(new IndexMetadata(index_name)); index->add_field(buffer, row, "index_name"); @@ -1783,7 +1783,7 @@ void IndexMetadata::update_legacy(StringRef index_type, const ColumnMetadata* co } String IndexMetadata::target_from_legacy(const ColumnMetadata* column, - const Value* options) { + const Value* options) { String column_name(column->name()); escape_id(column_name); @@ -1955,10 +1955,10 @@ void Metadata::InternalData::update_tables(const VersionNumber& server_version, keyspace = get_or_create_keyspace(keyspace_name); } - keyspace->add_table(TableMetadata::Ptr(Memory::allocate(server_version, - table_name, - buffer, row, - keyspace->is_virtual()))); + keyspace->add_table(TableMetadata::Ptr(new TableMetadata(server_version, + table_name, + buffer, row, + keyspace->is_virtual()))); } } @@ -2006,11 +2006,11 @@ void Metadata::InternalData::update_views(const VersionNumber& server_version, continue; } - ViewMetadata::Ptr view(Memory::allocate(server_version, - table.get(), - view_name, - buffer, row, - keyspace->is_virtual())); + ViewMetadata::Ptr view(new ViewMetadata(server_version, + table.get(), + view_name, + buffer, row, + keyspace->is_virtual())); keyspace->add_view(view); table->add_view(view); updated_tables.push_back(table); @@ -2132,10 +2132,10 @@ void Metadata::InternalData::update_functions(const VersionNumber& server_versio keyspace = get_or_create_keyspace(keyspace_name); } - keyspace->add_function(FunctionMetadata::Ptr(Memory::allocate(server_version, cache, - function_name, signature, - keyspace, - buffer, row))); + keyspace->add_function(FunctionMetadata::Ptr(new FunctionMetadata(server_version, cache, + function_name, signature, + keyspace, + buffer, row))); } } @@ -2167,10 +2167,10 @@ void Metadata::InternalData::update_aggregates(const VersionNumber& server_versi keyspace = get_or_create_keyspace(keyspace_name); } - keyspace->add_aggregate(AggregateMetadata::Ptr(Memory::allocate(server_version, cache, - aggregate_name, signature, - keyspace, - buffer, row))); + keyspace->add_aggregate(AggregateMetadata::Ptr(new AggregateMetadata(server_version, cache, + aggregate_name, signature, + keyspace, + buffer, row))); } } @@ -2251,9 +2251,9 @@ void Metadata::InternalData::update_columns(const VersionNumber& server_version, if (table_or_view) { table_or_view->add_column(server_version, - ColumnMetadata::Ptr(Memory::allocate(server_version, - cache, column_name, - keyspace, buffer, row))); + ColumnMetadata::Ptr(new ColumnMetadata(server_version, + cache, column_name, + keyspace, buffer, row))); } } diff --git a/src/metadata.hpp b/src/metadata.hpp index 40f1d31ab..518a24c7f 100644 --- a/src/metadata.hpp +++ b/src/metadata.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_SCHEMA_METADATA_HPP_INCLUDED__ #define __CASS_SCHEMA_METADATA_HPP_INCLUDED__ +#include "allocated.hpp" #include "copy_on_write_ptr.hpp" #include "external.hpp" #include "host.hpp" @@ -151,7 +152,7 @@ class MetadataBase { const Value* get_field(const String& name) const; String get_string_field(const String& name) const; - Iterator* iterator_fields() const { return Memory::allocate(fields_); } + Iterator* iterator_fields() const { return new MetadataFieldIterator(fields_); } void swap_fields(MetadataBase& meta) { fields_.swap(meta.fields_); @@ -374,7 +375,7 @@ class TableMetadataBase : public MetadataBase, public RefCounted(columns_); } + Iterator* iterator_columns() const { return new ColumnIterator(columns_); } const ColumnMetadata* get_column(const String& name) const; virtual void add_column(const VersionNumber& server_version, const ColumnMetadata::Ptr& column); void clear_columns(); @@ -493,13 +494,13 @@ class TableMetadata : public TableMetadataBase { const ViewMetadata::Vec& views() const { return views_; } const IndexMetadata::Vec& indexes() const { return indexes_; } - Iterator* iterator_views() const { return Memory::allocate(views_); } + Iterator* iterator_views() const { return new ViewIteratorVec(views_); } const ViewMetadata* get_view(const String& name) const; virtual void add_column(const VersionNumber& server_version, const ColumnMetadata::Ptr& column); void add_view(const ViewMetadata::Ptr& view); void sort_views(); - Iterator* iterator_indexes() const { return Memory::allocate(indexes_); } + Iterator* iterator_indexes() const { return new IndexIterator(indexes_); } const IndexMetadata* get_index(const String& name) const; void add_index(const IndexMetadata::Ptr& index); void clear_indexes(); @@ -548,11 +549,11 @@ class KeyspaceMetadata : public MetadataBase { KeyspaceMetadata(const String& name, bool is_virtual = false) : MetadataBase(name) , is_virtual_(is_virtual) - , tables_(Memory::allocate()) - , views_(Memory::allocate()) - , user_types_(Memory::allocate()) - , functions_(Memory::allocate()) - , aggregates_(Memory::allocate()) { } + , tables_(new TableMetadata::Map()) + , views_(new ViewMetadata::Map()) + , user_types_(new UserType::Map()) + , functions_(new FunctionMetadata::Map()) + , aggregates_(new AggregateMetadata::Map()) { } void update(const VersionNumber& server_version, const RefBuffer::Ptr& buffer, const Row* row); @@ -562,29 +563,29 @@ class KeyspaceMetadata : public MetadataBase { const FunctionMetadata::Map& functions() const { return *functions_; } const UserType::Map& user_types() const { return *user_types_; } - Iterator* iterator_tables() const { return Memory::allocate(*tables_); } + Iterator* iterator_tables() const { return new TableIterator(*tables_); } const TableMetadata* get_table(const String& name) const; const TableMetadata::Ptr& get_table(const String& name); void add_table(const TableMetadata::Ptr& table); - Iterator* iterator_views() const { return Memory::allocate(*views_); } + Iterator* iterator_views() const { return new ViewIteratorMap(*views_); } const ViewMetadata* get_view(const String& name) const; const ViewMetadata::Ptr& get_view(const String& name); void add_view(const ViewMetadata::Ptr& view); void drop_table_or_view(const String& table_name); - Iterator* iterator_user_types() const { return Memory::allocate(*user_types_); } + Iterator* iterator_user_types() const { return new TypeIterator(*user_types_); } const UserType* get_user_type(const String& type_name) const; const UserType::Ptr& get_or_create_user_type(const String& name, bool is_frozen); void drop_user_type(const String& type_name); - Iterator* iterator_functions() const { return Memory::allocate(*functions_); } + Iterator* iterator_functions() const { return new FunctionIterator(*functions_); } const FunctionMetadata* get_function(const String& full_function_name) const; void add_function(const FunctionMetadata::Ptr& function); void drop_function(const String& full_function_name); - Iterator* iterator_aggregates() const { return Memory::allocate(*aggregates_); } + Iterator* iterator_aggregates() const { return new AggregateIterator(*aggregates_); } const AggregateMetadata* get_aggregate(const String& full_aggregate_name) const; void add_aggregate(const AggregateMetadata::Ptr& aggregate); void drop_aggregate(const String& full_aggregate_name); @@ -617,7 +618,7 @@ class Metadata { const KeyspaceMetadata* keyspace() const { return &impl_.item(); } }; - class SchemaSnapshot { + class SchemaSnapshot : public Allocated { public: SchemaSnapshot(uint32_t version, const VersionNumber& server_version, @@ -630,7 +631,7 @@ class Metadata { VersionNumber server_version() const { return server_version_; } const KeyspaceMetadata* get_keyspace(const String& name) const; - Iterator* iterator_keyspaces() const { return Memory::allocate(*keyspaces_); } + Iterator* iterator_keyspaces() const { return new KeyspaceIterator(*keyspaces_); } const UserType* get_user_type(const String& keyspace_name, const String& type_name) const; @@ -688,7 +689,7 @@ class Metadata { class InternalData { public: InternalData() - : keyspaces_(Memory::allocate()) { } + : keyspaces_(new KeyspaceMetadata::Map()) { } const KeyspaceMetadata::MapPtr& keyspaces() const { return keyspaces_; } diff --git a/src/metrics.hpp b/src/metrics.hpp index 49f26895e..70c50ed6f 100644 --- a/src/metrics.hpp +++ b/src/metrics.hpp @@ -20,12 +20,12 @@ #ifndef __CASS_METRICS_HPP_INCLUDED__ #define __CASS_METRICS_HPP_INCLUDED__ +#include "allocated.hpp" #include "atomic.hpp" #include "constants.hpp" #include "scoped_ptr.hpp" #include "scoped_lock.hpp" #include "utils.hpp" -#include "vector.hpp" #include "third_party/hdr_histogram/hdr_histogram.hpp" @@ -36,7 +36,7 @@ namespace cass { -class Metrics { +class Metrics : public Allocated { public: class ThreadState { public: @@ -75,7 +75,7 @@ class Metrics { public: Counter(ThreadState* thread_state) : thread_state_(thread_state) - , counters_(thread_state->max_threads()) {} + , counters_(new PerThreadCounter[thread_state->max_threads()]) {} void inc() { counters_[thread_state_->current_thread_id()].add(1LL); @@ -102,7 +102,7 @@ class Metrics { } private: - class PerThreadCounter { + class PerThreadCounter : public Allocated { public: PerThreadCounter() : value_(0) {} @@ -133,7 +133,7 @@ class Metrics { private: ThreadState* thread_state_; - DynamicArray counters_; + ScopedArray counters_; private: DISALLOW_COPY_AND_ASSIGN(Counter); @@ -287,7 +287,7 @@ class Metrics { Histogram(ThreadState* thread_state) : thread_state_(thread_state) - , histograms_(thread_state->max_threads()) { + , histograms_(new PerThreadHistogram[thread_state->max_threads()]) { hdr_init(1LL, HIGHEST_TRACKABLE_VALUE, 3, &histogram_); uv_mutex_init(&mutex_); } @@ -389,7 +389,7 @@ class Metrics { Atomic odd_end_epoch_; }; - class PerThreadHistogram { + class PerThreadHistogram : public Allocated { public: PerThreadHistogram() : active_index_(0) { @@ -424,7 +424,7 @@ class Metrics { }; ThreadState* thread_state_; - DynamicArray histograms_; + ScopedArray histograms_; hdr_histogram* histogram_; mutable uv_mutex_t mutex_; diff --git a/src/micro_timer.cpp b/src/micro_timer.cpp index e3ffe0e47..a372d7a6d 100644 --- a/src/micro_timer.cpp +++ b/src/micro_timer.cpp @@ -16,7 +16,6 @@ #include "micro_timer.hpp" -#include "memory.hpp" #ifdef HAVE_TIMERFD #include @@ -42,7 +41,7 @@ int MicroTimer::start(uv_loop_t* loop, if (fd_ == -1) return errno; } if (handle_ == NULL) { - handle_ = Memory::allocate(); + handle_ = new AllocatedT(); handle_->loop = NULL; handle_->data = this; } @@ -79,7 +78,7 @@ void MicroTimer::stop() { } if (handle_ != NULL) { if (state_ == CLOSED) { // The handle was allocated, but initialization failed. - Memory::deallocate(handle_); + delete handle_; } else { // If initialized or started then close the handle properly. uv_close(reinterpret_cast(handle_), on_close); } @@ -107,7 +106,7 @@ void MicroTimer::handle_timeout() { } void MicroTimer::on_close(uv_handle_t* handle) { - Memory::deallocate(reinterpret_cast(handle)); + delete reinterpret_cast*>(handle); } #else diff --git a/src/micro_timer.hpp b/src/micro_timer.hpp index 7e66827b7..bf95f0498 100644 --- a/src/micro_timer.hpp +++ b/src/micro_timer.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_MICRO_TIMER_HPP_INCLUDED__ #define __CASS_MICRO_TIMER_HPP_INCLUDED__ +#include "allocated.hpp" #include "callback.hpp" #include "cassconfig.hpp" #include "macros.hpp" @@ -98,7 +99,7 @@ class MicroTimer { STARTED }; - uv_poll_t* handle_; + AllocatedT* handle_; int fd_; State state_; #else diff --git a/src/monitor_reporting.cpp b/src/monitor_reporting.cpp new file mode 100644 index 000000000..588298f29 --- /dev/null +++ b/src/monitor_reporting.cpp @@ -0,0 +1,27 @@ +/* + Copyright (c) DataStax, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include "monitor_reporting.hpp" + +namespace cass { + +MonitorReporting* create_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config) { + return new NopMonitorReporting(); +} + +} // namespace cass diff --git a/src/monitor_reporting.hpp b/src/monitor_reporting.hpp new file mode 100644 index 000000000..6cfc1a3ba --- /dev/null +++ b/src/monitor_reporting.hpp @@ -0,0 +1,58 @@ +/* + Copyright (c) DataStax, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#ifndef __CASS_MONITOR_REPORTING_HPP_INCLUDED__ +#define __CASS_MONITOR_REPORTING_HPP_INCLUDED__ + +#include "connection.hpp" +#include "host.hpp" +#include "load_balancing.hpp" +#include "string.hpp" + +namespace cass { + +class Config; + +class MonitorReporting { +public: + virtual ~MonitorReporting() { } + virtual uint64_t interval_ms(const VersionNumber& dse_server_version) const = 0; + virtual void send_startup_message(const Connection::Ptr& connection, + const Config& config, + const HostMap& hosts, + const LoadBalancingPolicy::Vec& initialized_policies) = 0; + virtual void send_status_message(const Connection::Ptr& connection, + const HostMap& hosts) = 0; +}; + +class NopMonitorReporting : public MonitorReporting { +public: + uint64_t interval_ms(const VersionNumber& dse_server_version) const { return 0; } + void send_startup_message(const Connection::Ptr& connection, + const Config& config, + const HostMap& hosts, + const LoadBalancingPolicy::Vec& initialized_policies) { } + void send_status_message(const Connection::Ptr& connection, + const HostMap& hosts) { } +}; + +MonitorReporting* create_monitor_reporting(const String& client_id, + const String& session_id, + const Config& config); + +} // namespace cass + +#endif // __CASS_MONITOR_REPORTING_HPP_INCLUDED__ diff --git a/src/mpmc_queue.hpp b/src/mpmc_queue.hpp index 5de42b4ac..f1cfc875f 100644 --- a/src/mpmc_queue.hpp +++ b/src/mpmc_queue.hpp @@ -22,10 +22,11 @@ #ifndef __CASS_MPMC_QUEUE_INCLUDED__ #define __CASS_MPMC_QUEUE_INCLUDED__ +#include "allocated.hpp" #include "atomic.hpp" #include "cassconfig.hpp" #include "macros.hpp" -#include "memory.hpp" +#include "scoped_ptr.hpp" #include "utils.hpp" #include @@ -33,14 +34,14 @@ namespace cass { template -class MPMCQueue { +class MPMCQueue : public Allocated { public: typedef T EntryType; MPMCQueue(size_t size) : size_(next_pow_2(size)) , mask_(size_ - 1) - , buffer_(size_) + , buffer_(new Node[size_]) , tail_(0) , head_(0) { // populate the sequence initial values @@ -138,7 +139,7 @@ class MPMCQueue { } private: - struct Node { + struct Node : public Allocated { Atomic seq; T data; }; @@ -149,7 +150,7 @@ class MPMCQueue { CachePad pad0_; const size_t size_; const size_t mask_; - DynamicArray buffer_; + ScopedArray buffer_; CachePad pad1_; Atomic tail_; CachePad pad2_; diff --git a/src/pooled_connection.cpp b/src/pooled_connection.cpp index 10c06e8d9..4e17dcbe4 100644 --- a/src/pooled_connection.cpp +++ b/src/pooled_connection.cpp @@ -60,8 +60,8 @@ ChainedSetKeyspaceCallback::ChainedSetKeyspaceCallback(Connection* connection, const RequestCallback::Ptr& chained_callback) : SimpleRequestCallback( Request::ConstPtr( - Memory::allocate(keyspace, - chained_callback->request_timeout_ms()))) + new SetKeyspaceRequest(keyspace, + chained_callback->request_timeout_ms()))) , connection_(connection) , chained_callback_(chained_callback) { } @@ -127,7 +127,7 @@ bool PooledConnection::write(RequestCallback* callback) { static_cast(connection_.get()), static_cast(pool_)); result = connection_->write(RequestCallback::Ptr( - Memory::allocate( + new ChainedSetKeyspaceCallback( connection_.get(), keyspace, RequestCallback::Ptr(callback)))); diff --git a/src/pooled_connection.hpp b/src/pooled_connection.hpp index b64c43250..483a32d52 100644 --- a/src/pooled_connection.hpp +++ b/src/pooled_connection.hpp @@ -50,7 +50,7 @@ class PooledConnection : public RefCounted * Writes a request to a connection, but it's not written to the socket until * the connection pool manager flushes the request. * - * @param callback A request callback that handlets the request. + * @param callback A request callback that handles the request. * @return Returns true if the request was written, otherwise, an error * occurred. */ diff --git a/src/prepare_host_handler.cpp b/src/prepare_host_handler.cpp index 4f21d3603..9b5571bb0 100644 --- a/src/prepare_host_handler.cpp +++ b/src/prepare_host_handler.cpp @@ -16,7 +16,6 @@ #include "prepare_host_handler.hpp" -#include "memory.hpp" #include "prepare_request.hpp" #include "protocol.hpp" #include "query_request.hpp" @@ -65,13 +64,13 @@ void PrepareHostHandler::prepare(uv_loop_t* loop, inc_ref(); // Reference for the event loop - Connector::Ptr connector(Memory::allocate(host_->address(), - protocol_version_, - bind_callback(&PrepareHostHandler::on_connect, this))); + Connector::Ptr connector(new Connector(host_, + protocol_version_, + bind_callback(&PrepareHostHandler::on_connect, this))); connector->with_settings(settings) - ->with_listener(this) - ->connect(loop); + ->with_listener(this) + ->connect(loop); } void PrepareHostHandler::on_close(Connection* connection) { @@ -115,13 +114,13 @@ void PrepareHostHandler::prepare_next() { check_and_set_keyspace() && prepares_outstanding_ < max_prepares_outstanding_) { const String& query((*current_entry_it_)->query()); - PrepareRequest::Ptr prepare_request(Memory::allocate(query)); + PrepareRequest::Ptr prepare_request(new PrepareRequest(query)); // Set the keyspace in case per request keyspaces are supported prepare_request->set_keyspace(current_keyspace_); if (!connection_->write(PrepareCallback::Ptr( - Memory::allocate(prepare_request, Ptr(this))))) { + new PrepareCallback(prepare_request, Ptr(this))))) { LOG_WARN("Failed to write prepare request while preparing all queries on host %s", host_->address_string().c_str()); close(); @@ -144,7 +143,7 @@ bool PrepareHostHandler::check_and_set_keyspace() { if (keyspace != current_keyspace_) { if (!connection_->write_and_flush(PrepareCallback::Ptr( - Memory::allocate(keyspace, Ptr(this))))) { + new SetKeyspaceCallback(keyspace, Ptr(this))))) { LOG_WARN("Failed to write \"USE\" keyspace request while preparing all queries on host %s", host_->address_string().c_str()); close(); @@ -194,7 +193,7 @@ void PrepareHostHandler::PrepareCallback::on_internal_timeout() { PrepareHostHandler::SetKeyspaceCallback::SetKeyspaceCallback(const String& keyspace, const PrepareHostHandler::Ptr& handler) : SimpleRequestCallback(Request::ConstPtr( - Memory::allocate("USE " + keyspace))) + new QueryRequest("USE " + keyspace))) , handler_(handler) { } void PrepareHostHandler::SetKeyspaceCallback::on_internal_set(ResponseMessage* response) { diff --git a/src/prepared.cpp b/src/prepared.cpp index f660443dc..4e1000e5d 100644 --- a/src/prepared.cpp +++ b/src/prepared.cpp @@ -27,7 +27,7 @@ void cass_prepared_free(const CassPrepared* prepared) { } CassStatement* cass_prepared_bind(const CassPrepared* prepared) { - cass::ExecuteRequest* execute = cass::Memory::allocate(prepared); + cass::ExecuteRequest* execute = new cass::ExecuteRequest(prepared); execute->inc_ref(); return CassStatement::to(execute); } diff --git a/src/query_request.cpp b/src/query_request.cpp index 862c98f3c..16dcdc041 100644 --- a/src/query_request.cpp +++ b/src/query_request.cpp @@ -60,7 +60,7 @@ int32_t QueryRequest::encode_values_with_names(ProtocolVersion version, RequestC size_t QueryRequest::get_indices(StringRef name, IndexVec* indices) { if (!value_names_) { set_has_names_for_values(true); - value_names_.reset(Memory::allocate(elements().size())); + value_names_.reset(new ValueNameHashTable(elements().size())); } if (value_names_->get_indices(name, indices) == 0) { diff --git a/src/random.hpp b/src/random.hpp index 473835cd1..e6d2fe77b 100644 --- a/src/random.hpp +++ b/src/random.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_RANDOM_HPP_INCLUDED__ #define __CASS_RANDOM_HPP_INCLUDED__ +#include "allocated.hpp" #include "third_party/mt19937_64/mt19937_64.hpp" #include @@ -24,7 +25,7 @@ namespace cass { -class Random { +class Random : public Allocated { public: Random(); ~Random(); diff --git a/src/ref_counted.hpp b/src/ref_counted.hpp index 2cc6d7a8b..f56574f0b 100644 --- a/src/ref_counted.hpp +++ b/src/ref_counted.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_REF_COUNTED_HPP_INCLUDED__ #define __CASS_REF_COUNTED_HPP_INCLUDED__ +#include "allocated.hpp" #include "atomic.hpp" #include "macros.hpp" #include "memory.hpp" @@ -27,10 +28,8 @@ namespace cass { -struct RefCountedBase { }; - template -class RefCounted : public RefCountedBase { +class RefCounted : public Allocated { public: RefCounted() : ref_count_(0) { } @@ -48,7 +47,7 @@ class RefCounted : public RefCountedBase { assert(new_ref_count >= 1); if (new_ref_count == 1) { atomic_thread_fence(MEMORY_ORDER_ACQUIRE); - Memory::deallocate(static_cast(this)); + delete static_cast(this); } } diff --git a/src/request.cpp b/src/request.cpp index bb6499efa..c40a2bd41 100644 --- a/src/request.cpp +++ b/src/request.cpp @@ -21,7 +21,7 @@ extern "C" { CassCustomPayload* cass_custom_payload_new() { - cass::CustomPayload* payload = cass::Memory::allocate(); + cass::CustomPayload* payload = new cass::CustomPayload(); payload->inc_ref(); return CassCustomPayload::to(payload); } diff --git a/src/request.hpp b/src/request.hpp index 4890ac8a2..a3b75997c 100644 --- a/src/request.hpp +++ b/src/request.hpp @@ -204,7 +204,7 @@ class Request : public RefCounted { } void set_host(const Address& host) { - host_.reset(Memory::allocate
(host)); + host_.reset(new Address(host)); } const Address* host() const { return host_.get(); } diff --git a/src/request_callback.cpp b/src/request_callback.cpp index 50a39c458..f4c35d363 100644 --- a/src/request_callback.cpp +++ b/src/request_callback.cpp @@ -49,7 +49,7 @@ void RequestCallback::notify_write(Connection* connection, int stream) { } bool RequestCallback::skip_metadata() const { - // Skip the metadata if this an execute request and we have an entry cached + // Skip the metadata if this an execute request and we have an entry cached return request()->opcode() == CQL_OPCODE_EXECUTE && prepared_metadata_entry() && prepared_metadata_entry()->result()->result_metadata(); @@ -175,7 +175,7 @@ void RequestCallback::set_state(RequestCallback::State next_state) { SimpleRequestCallback::SimpleRequestCallback(const String& query, uint64_t request_timeout_ms) : RequestCallback( - RequestWrapper(Request::ConstPtr(Memory::allocate(query)), + RequestWrapper(Request::ConstPtr(new QueryRequest(query)), request_timeout_ms)) { } void SimpleRequestCallback::on_write(Connection* connection) { @@ -229,13 +229,13 @@ ChainedRequestCallback::ChainedRequestCallback(const String& key, const Request: ChainedRequestCallback::Ptr ChainedRequestCallback::chain(const String& key, const String& query) { has_pending_ = true; return ChainedRequestCallback::Ptr( - Memory::allocate(key, query, Ptr(this))); + new ChainedRequestCallback(key, query, Ptr(this))); } ChainedRequestCallback::Ptr ChainedRequestCallback::chain(const String& key, const Request::ConstPtr& request) { has_pending_ = true; return ChainedRequestCallback::Ptr( - Memory::allocate(key, request, Ptr(this))); + new ChainedRequestCallback(key, request, Ptr(this))); } ResultResponse::Ptr ChainedRequestCallback::result(const String& key) const { diff --git a/src/request_callback.hpp b/src/request_callback.hpp index 33ab130cf..200f1b946 100644 --- a/src/request_callback.hpp +++ b/src/request_callback.hpp @@ -180,13 +180,13 @@ class RequestCallback : public RefCounted, public SocketRequest return wrapper_.request_timeout_ms(); } - int64_t timestamp() { - return wrapper_.timestamp(); - } + int64_t timestamp() { + return wrapper_.timestamp(); + } - const RetryPolicy::Ptr& retry_policy() { - return wrapper_.retry_policy(); - } + const RetryPolicy::Ptr& retry_policy() { + return wrapper_.retry_policy(); + } const PreparedMetadata::Entry::Ptr& prepared_metadata_entry() const { return wrapper_.prepared_metadata_entry(); diff --git a/src/request_handler.cpp b/src/request_handler.cpp index 39fac18a1..c671f0db9 100644 --- a/src/request_handler.cpp +++ b/src/request_handler.cpp @@ -37,7 +37,7 @@ namespace cass { class SingleHostQueryPlan : public QueryPlan { public: SingleHostQueryPlan(const Address& address) - : host_(Memory::allocate(address)) { } + : host_(new Host(address)) { } virtual Host::Ptr compute_next() { Host::Ptr temp = host_; @@ -77,7 +77,7 @@ class PrepareCallback : public SimpleRequestCallback { PrepareCallback::PrepareCallback(const String& query, RequestExecution* request_execution) : SimpleRequestCallback( Request::ConstPtr( - Memory::allocate(query, + new PrepareRequest(query, request_execution->request()->keyspace(), request_execution->request_timeout_ms()))) , request_execution_(request_execution) { } @@ -174,7 +174,7 @@ void RequestHandler::init(const ExecutionProfile& profile, // If a specific host is set then bypass the load balancing policy and use a // specialized single host query plan. if (request()->host()) { - query_plan_.reset(Memory::allocate(*request()->host())); + query_plan_.reset(new SingleHostQueryPlan(*request()->host())); } else { query_plan_.reset(profile.load_balancing_policy()->new_query_plan(keyspace, this, token_map)); } @@ -183,7 +183,7 @@ void RequestHandler::init(const ExecutionProfile& profile, } void RequestHandler::execute() { - RequestExecution::Ptr request_execution(Memory::allocate(this)); + RequestExecution::Ptr request_execution(new RequestExecution(this)); running_executions_++; internal_retry(request_execution.get()); } @@ -220,10 +220,10 @@ void RequestHandler::notify_result_metadata_changed(const String& prepared_id, const String& result_metadata_id, const ResultResponse::ConstPtr& result_response, Protected) { PreparedMetadata::Entry::Ptr entry( - Memory::allocate(query, - keyspace, - result_metadata_id, - result_response)); + new PreparedMetadata::Entry(query, + keyspace, + result_metadata_id, + result_response)); listener_->on_prepared_metadata_changed(prepared_id, entry); } @@ -361,6 +361,7 @@ void RequestExecution::on_retry_current_host() { } void RequestExecution::on_retry_next_host() { + current_host_->decrement_inflight_requests(); retry_next_host(); } @@ -378,6 +379,7 @@ void RequestExecution::retry_next_host() { void RequestExecution::on_write(Connection* connection) { assert(current_host_ && "Tried to start on a non-existent host"); + current_host_->increment_inflight_requests(); connection_ = connection; if (request()->record_attempted_addresses()) { request_handler_->add_attempted_address(current_host_->address(), RequestHandler::Protected()); @@ -398,6 +400,7 @@ void RequestExecution::on_set(ResponseMessage* response) { assert(connection_ != NULL); assert(current_host_ && "Tried to set on a non-existent host"); + current_host_->decrement_inflight_requests(); Connection* connection = connection_; switch (response->opcode()) { @@ -415,6 +418,8 @@ void RequestExecution::on_set(ResponseMessage* response) { } void RequestExecution::on_error(CassError code, const String& message) { + current_host_->decrement_inflight_requests(); + // Handle recoverable errors by retrying with the next host if (code == CASS_ERROR_LIB_WRITE_ERROR || code == CASS_ERROR_LIB_UNABLE_TO_SET_KEYSPACE) { @@ -615,7 +620,7 @@ void RequestExecution::on_error_response(Connection* connection, ResponseMessage break; case RetryPolicy::RetryDecision::IGNORE: - set_response(Response::Ptr(Memory::allocate())); + set_response(Response::Ptr(new ResultResponse())); break; } } @@ -642,7 +647,7 @@ void RequestExecution::on_error_unprepared(Connection* connection, ErrorResponse } if (!connection->write_and_flush(RequestCallback::Ptr( - Memory::allocate(query, this)))) { + new PrepareCallback(query, this)))) { // Try to prepare on the same host but on a different connection retry_current_host(); } diff --git a/src/request_handler.hpp b/src/request_handler.hpp index 7af3f7c08..4130c1b2c 100644 --- a/src/request_handler.hpp +++ b/src/request_handler.hpp @@ -56,7 +56,7 @@ class ResponseFuture : public Future { ResponseFuture(const Metadata::SchemaSnapshot& schema_metadata) : Future(FUTURE_TYPE_RESPONSE) - , schema_metadata(Memory::allocate(schema_metadata)) { } + , schema_metadata(new Metadata::SchemaSnapshot(schema_metadata)) { } bool set_response(Address address, const Response::Ptr& response) { ScopedMutex lock(&mutex_); diff --git a/src/request_processor.cpp b/src/request_processor.cpp index 348dbaa3e..b293feaa8 100644 --- a/src/request_processor.cpp +++ b/src/request_processor.cpp @@ -146,7 +146,7 @@ static NopRequestProcessorListener nop_request_processor_listener__; RequestProcessorSettings::RequestProcessorSettings() : max_schema_wait_time_ms(10000) , prepare_on_all_hosts(true) - , timestamp_generator(Memory::allocate()) + , timestamp_generator(new ServerSideTimestampGenerator()) , default_profile(Config().default_profile()) , request_queue_size(8192) , coalesce_delay_us(CASS_DEFAULT_COALESCE_DELAY) @@ -186,7 +186,7 @@ RequestProcessor::RequestProcessor(RequestProcessorListener* listener, , default_profile_(settings.default_profile) , profiles_(settings.profiles) , request_count_(0) - , request_queue_(Memory::allocate >(settings.request_queue_size)) + , request_queue_(new MPMCQueue(settings.request_queue_size)) , is_closing_(false) , is_processing_(false) , attempts_without_requests_(0) @@ -230,7 +230,7 @@ RequestProcessor::RequestProcessor(RequestProcessorListener* listener, } void RequestProcessor::close() { - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new ProcessorRunClose(Ptr(this))); } void RequestProcessor::set_listener(RequestProcessorListener* listener) { @@ -245,28 +245,28 @@ void RequestProcessor::set_keyspace(const String& keyspace, if (event_loop_->is_running_on()) { connection_pool_manager_->set_keyspace(keyspace); } else { - event_loop_->add(Memory::allocate(connection_pool_manager_, keyspace, handler)); + event_loop_->add(new SetKeyspaceProcessor(connection_pool_manager_, keyspace, handler)); } } void RequestProcessor::notify_host_added(const Host::Ptr& host) { - event_loop_->add(Memory::allocate(host, Ptr(this))); + event_loop_->add(new ProcessorNotifyHostAdd(host, Ptr(this))); } void RequestProcessor::notify_host_removed(const Host::Ptr& host) { - event_loop_->add(Memory::allocate(host, Ptr(this))); + event_loop_->add(new ProcessorNotifyHostRemove(host, Ptr(this))); } void RequestProcessor::notify_host_ready(const Host::Ptr& host) { - event_loop_->add(Memory::allocate(host, Ptr(this))); + event_loop_->add(new ProcessorNotifyHostReady(host, Ptr(this))); } void RequestProcessor::notify_host_maybe_up(const Address& address) { - event_loop_->add(Memory::allocate(address, Ptr(this))); + event_loop_->add(new ProcessorNotifyMaybeHostUp(address, Ptr(this))); } void RequestProcessor::notify_token_map_updated(const TokenMap::Ptr& token_map) { - event_loop_->add(Memory::allocate(token_map, Ptr(this))); + event_loop_->add(new ProcessorNotifyTokenMapUpdate(token_map, Ptr(this))); } void RequestProcessor::process_request(const RequestHandler::Ptr& request_handler) { @@ -279,7 +279,7 @@ void RequestProcessor::process_request(const RequestHandler::Ptr& request_handle if (!is_processing_.load(MEMORY_ORDER_RELAXED) && is_processing_.compare_exchange_strong(expected, true)) { async_.send(); - } + } } else { request_handler->dec_ref(); request_handler->set_error(CASS_ERROR_LIB_REQUEST_QUEUE_FULL, @@ -339,18 +339,18 @@ void RequestProcessor::on_keyspace_changed(const String& keyspace, KeyspaceChangedResponse response) { listener_->on_keyspace_changed(keyspace, KeyspaceChangedHandler::Ptr( - Memory::allocate(event_loop_, response))); + new KeyspaceChangedHandler(event_loop_, response))); } bool RequestProcessor::on_wait_for_tracing_data(const RequestHandler::Ptr& request_handler, const Host::Ptr& current_host, const Response::Ptr& response) { - TracingDataHandler::Ptr handler(Memory::allocate(request_handler, - current_host, - response, - settings_.tracing_consistency, - settings_.max_tracing_wait_time_ms, - settings_.retry_tracing_wait_time_ms)); + TracingDataHandler::Ptr handler(new TracingDataHandler(request_handler, + current_host, + response, + settings_.tracing_consistency, + settings_.max_tracing_wait_time_ms, + settings_.retry_tracing_wait_time_ms)); return write_wait_callback(request_handler, current_host, handler->callback()); } @@ -358,11 +358,11 @@ bool RequestProcessor::on_wait_for_tracing_data(const RequestHandler::Ptr& reque bool RequestProcessor::on_wait_for_schema_agreement(const RequestHandler::Ptr& request_handler, const Host::Ptr& current_host, const Response::Ptr& response) { - SchemaAgreementHandler::Ptr handler(Memory::allocate(request_handler, - current_host, - response, - this, - settings_.max_schema_wait_time_ms)); + SchemaAgreementHandler::Ptr handler(new SchemaAgreementHandler(request_handler, + current_host, + response, + this, + settings_.max_schema_wait_time_ms)); return write_wait_callback(request_handler, current_host, handler->callback()); } @@ -380,11 +380,11 @@ bool RequestProcessor::on_prepare_all(const RequestHandler::Ptr& request_handler return false; } - PrepareAllHandler::Ptr prepare_all_handler(Memory::allocate(current_host, - response, - request_handler, - // Subtract the node that's already been prepared - addresses.size() - 1)); + PrepareAllHandler::Ptr prepare_all_handler(new PrepareAllHandler(current_host, + response, + request_handler, + // Subtract the node that's already been prepared + addresses.size() - 1)); for (AddressVec::const_iterator it = addresses.begin(), end = addresses.end(); it != end; ++it) { @@ -398,8 +398,8 @@ bool RequestProcessor::on_prepare_all(const RequestHandler::Ptr& request_handler // The destructor of `PrepareAllCallback` will decrement the remaining // count in `PrepareAllHandler` even if this is unable to write to a // connection successfully. - PrepareAllCallback::Ptr prepare_all_callback(Memory::allocate(address, - prepare_all_handler)); + PrepareAllCallback::Ptr prepare_all_callback(new PrepareAllCallback(address, + prepare_all_handler)); PooledConnection::Ptr connection(connection_pool_manager_->find_least_busy(address)); if (connection) { @@ -456,7 +456,7 @@ void RequestProcessor::internal_host_add(const Host::Ptr& host) { if (connection_pool_manager_) { LoadBalancingPolicy::Vec policies = load_balancing_policies(); if (!is_host_ignored(policies, host)) { - connection_pool_manager_->add(host->address()); + connection_pool_manager_->add(host); for (LoadBalancingPolicy::Vec::const_iterator it = policies.begin(); it != policies.end(); ++it) { if ((*it)->distance(host) != CASS_HOST_DISTANCE_IGNORE) { diff --git a/src/request_processor.hpp b/src/request_processor.hpp index 92d39a2c8..0567428cf 100644 --- a/src/request_processor.hpp +++ b/src/request_processor.hpp @@ -56,7 +56,7 @@ class KeyspaceChangedHandler : public RefCounted { , response_(response) { } ~KeyspaceChangedHandler() { - event_loop_->add(Memory::allocate(response_)); + event_loop_->add(new Task(response_)); } private: diff --git a/src/request_processor_initializer.cpp b/src/request_processor_initializer.cpp index 4e351f1c3..8ba01642e 100644 --- a/src/request_processor_initializer.cpp +++ b/src/request_processor_initializer.cpp @@ -59,7 +59,7 @@ RequestProcessorInitializer::~RequestProcessorInitializer() { void RequestProcessorInitializer::initialize(EventLoop* event_loop) { ScopedMutex l(&mutex_); event_loop_ = event_loop; - event_loop_->add(Memory::allocate(Ptr(this))); + event_loop_->add(new RunInitializeProcessor(Ptr(this))); } RequestProcessorInitializer* RequestProcessorInitializer::with_settings(const RequestProcessorSettings& settings) { @@ -120,22 +120,15 @@ void RequestProcessorInitializer::on_close(ConnectionPoolManager* manager) { void RequestProcessorInitializer::internal_intialize() { inc_ref(); connection_pool_manager_initializer_.reset( - Memory::allocate(protocol_version_, - bind_callback(&RequestProcessorInitializer::on_initialize, this))); - - AddressVec addresses; - addresses.reserve(addresses.size()); - for (HostMap::const_iterator it = hosts_.begin(), - end = hosts_.end(); it != end; ++it) { - addresses.push_back(it->first); - } + new ConnectionPoolManagerInitializer(protocol_version_, + bind_callback(&RequestProcessorInitializer::on_initialize, this))); connection_pool_manager_initializer_ ->with_settings(settings_.connection_pool_settings) ->with_listener(this) ->with_keyspace(keyspace_) ->with_metrics(metrics_) - ->initialize(event_loop_->loop(), addresses); + ->initialize(event_loop_->loop(), hosts_); } void RequestProcessorInitializer::on_initialize(ConnectionPoolManagerInitializer* initializer) { @@ -162,14 +155,14 @@ void RequestProcessorInitializer::on_initialize(ConnectionPoolManagerInitializer error_code_ = REQUEST_PROCESSOR_ERROR_NO_HOSTS_AVAILABLE; error_message_ = "Unable to connect to any hosts"; } else { - processor_.reset(Memory::allocate(listener_, - event_loop_, - initializer->release_manager(), - connected_host_, - hosts_, - token_map_, - settings_, - random_)); + processor_.reset(new RequestProcessor(listener_, + event_loop_, + initializer->release_manager(), + connected_host_, + hosts_, + token_map_, + settings_, + random_)); int rc = processor_->init(RequestProcessor::Protected()); if (rc != 0) { diff --git a/src/resolver.hpp b/src/resolver.hpp index 6c74404ea..13e076c64 100644 --- a/src/resolver.hpp +++ b/src/resolver.hpp @@ -48,10 +48,10 @@ class Resolver : public RefCounted { }; Resolver(const String& hostname, int port, const Callback& callback) - : hostname_(hostname) - , port_(port) - , status_(NEW) - , callback_(callback) { + : hostname_(hostname) + , port_(port) + , status_(NEW) + , callback_(callback) { req_.data = this; } @@ -173,8 +173,8 @@ class MultiResolver : public RefCounted { uint64_t timeout, struct addrinfo* hints = NULL) { inc_ref(); Resolver::Ptr resolver( - Memory::allocate(host, port, - bind_callback(&MultiResolver::on_resolve, this))); + new Resolver(host, port, + bind_callback(&MultiResolver::on_resolve, this))); resolver->resolve(loop, timeout, hints); resolvers_.push_back(resolver); remaining_++; diff --git a/src/response.cpp b/src/response.cpp index 8f6099990..eb54cb9a0 100644 --- a/src/response.cpp +++ b/src/response.cpp @@ -69,35 +69,35 @@ bool ResponseMessage::allocate_body(int8_t opcode) { switch (opcode) { case CQL_OPCODE_ERROR: - response_body_.reset(Memory::allocate()); + response_body_.reset(new ErrorResponse()); return true; case CQL_OPCODE_READY: - response_body_.reset(Memory::allocate()); + response_body_.reset(new ReadyResponse()); return true; case CQL_OPCODE_AUTHENTICATE: - response_body_.reset(Memory::allocate()); + response_body_.reset(new AuthenticateResponse()); return true; case CQL_OPCODE_SUPPORTED: - response_body_.reset(Memory::allocate()); + response_body_.reset(new SupportedResponse()); return true; case CQL_OPCODE_RESULT: - response_body_.reset(Memory::allocate()); + response_body_.reset(new ResultResponse()); return true; case CQL_OPCODE_EVENT: - response_body_.reset(Memory::allocate()); + response_body_.reset(new EventResponse()); return true; case CQL_OPCODE_AUTH_CHALLENGE: - response_body_.reset(Memory::allocate()); + response_body_.reset(new AuthChallengeResponse()); return true; case CQL_OPCODE_AUTH_SUCCESS: - response_body_.reset(Memory::allocate()); + response_body_.reset(new AuthSuccessResponse()); return true; default: @@ -151,7 +151,7 @@ ssize_t ResponseMessage::decode(const char* input, size_t size) { // If a deprecated version of the protocol is encountered then we fake // an invalid protocol error. if (version_ < CASS_PROTOCOL_VERSION_V3) { - response_body_.reset(Memory::allocate()); + response_body_.reset(new InvalidProtocolErrorResponse()); } else if (!allocate_body(opcode_) || !response_body_) { return -1; } diff --git a/src/response.hpp b/src/response.hpp index bddc16070..eb89f6222 100644 --- a/src/response.hpp +++ b/src/response.hpp @@ -17,14 +17,13 @@ #ifndef __CASS_RESPONSE_HPP_INCLUDED__ #define __CASS_RESPONSE_HPP_INCLUDED__ -#include "utils.hpp" +#include "allocated.hpp" #include "constants.hpp" #include "decoder.hpp" #include "hash_table.hpp" #include "macros.hpp" -#include "memory.hpp" #include "ref_counted.hpp" -#include "scoped_ptr.hpp" +#include "utils.hpp" #include @@ -77,7 +76,7 @@ class Response : public RefCounted { DISALLOW_COPY_AND_ASSIGN(Response); }; -class ResponseMessage { +class ResponseMessage : public Allocated { public: ResponseMessage() : version_(0) diff --git a/src/result_response.cpp b/src/result_response.cpp index 465aa20b9..a4b4532b7 100644 --- a/src/result_response.cpp +++ b/src/result_response.cpp @@ -90,8 +90,8 @@ cass_bool_t cass_result_has_more_pages(const CassResult* result) { } CassError cass_result_paging_state_token(const CassResult* result, - const char** paging_state, - size_t* paging_state_size) { + const char** paging_state, + size_t* paging_state_size) { if (!result->has_more_pages()) { return CASS_ERROR_LIB_NO_PAGING_STATE; } @@ -144,7 +144,7 @@ class DataTypeDecoder { if (type) return type; // If no mapping exists, return an actual custom type. - return DataType::ConstPtr(Memory::allocate(class_name.to_string())); + return DataType::ConstPtr(new CustomType(class_name.to_string())); } DataType::ConstPtr decode_collection(CassValueType collection_type) { @@ -153,7 +153,7 @@ class DataTypeDecoder { if (collection_type == CASS_VALUE_TYPE_MAP) { types.push_back(decode()); } - return DataType::ConstPtr(Memory::allocate(collection_type, types, false)); + return DataType::ConstPtr(new CollectionType(collection_type, types, false)); } DataType::ConstPtr decode_user_type() { @@ -172,10 +172,10 @@ class DataTypeDecoder { if (!decoder_.decode_string(&field_name)) return DataType::NIL; fields.push_back(UserType::Field(field_name.to_string(), decode())); } - return DataType::ConstPtr(Memory::allocate(keyspace.to_string(), - type_name.to_string(), - fields, - false)); + return DataType::ConstPtr(new UserType(keyspace.to_string(), + type_name.to_string(), + fields, + false)); } DataType::ConstPtr decode_tuple() { @@ -186,7 +186,7 @@ class DataTypeDecoder { for (uint16_t i = 0; i < n; ++i) { types.push_back(decode()); } - return DataType::ConstPtr(Memory::allocate(types, false)); + return DataType::ConstPtr(new TupleType(types, false)); } private: @@ -280,7 +280,7 @@ bool ResultResponse::decode_metadata(Decoder& decoder, CHECK_RESULT(decoder.decode_string(&table_)); } - metadata->reset(Memory::allocate(column_count, this->buffer())); + metadata->reset(new ResultMetadata(column_count, this->buffer())); SimpleDataTypeCache cache; diff --git a/src/retry_policy.cpp b/src/retry_policy.cpp index ae250c3ad..629aa463a 100644 --- a/src/retry_policy.cpp +++ b/src/retry_policy.cpp @@ -23,19 +23,19 @@ extern "C" { CassRetryPolicy* cass_retry_policy_default_new() { - cass::RetryPolicy* policy = cass::Memory::allocate(); + cass::RetryPolicy* policy = new cass::DefaultRetryPolicy(); policy->inc_ref(); return CassRetryPolicy::to(policy); } CassRetryPolicy* cass_retry_policy_downgrading_consistency_new() { - cass::RetryPolicy* policy = cass::Memory::allocate(); + cass::RetryPolicy* policy = new cass::DowngradingConsistencyRetryPolicy(); policy->inc_ref(); return CassRetryPolicy::to(policy); } CassRetryPolicy* cass_retry_policy_fallthrough_new() { - cass::RetryPolicy* policy = cass::Memory::allocate(); + cass::RetryPolicy* policy = new cass::FallthroughRetryPolicy(); policy->inc_ref(); return CassRetryPolicy::to(policy); } @@ -45,7 +45,7 @@ CassRetryPolicy* cass_retry_policy_logging_new(CassRetryPolicy* child_retry_poli return NULL; } cass::RetryPolicy* policy - = cass::Memory::allocate( + = new cass::LoggingRetryPolicy( cass::SharedRefPtr(child_retry_policy)); policy->inc_ref(); return CassRetryPolicy::to(policy); diff --git a/src/ring_buffer.cpp b/src/ring_buffer.cpp index e6702ed73..824072f44 100644 --- a/src/ring_buffer.cpp +++ b/src/ring_buffer.cpp @@ -51,7 +51,7 @@ RingBuffer::~RingBuffer() { Buffer* current = head_.next_; while (current != &head_) { Buffer* next = current->next_; - Memory::deallocate(current); + delete current; current = next; } @@ -132,7 +132,7 @@ void RingBuffer::free_empty() { assert(cur->write_pos_ == cur->read_pos_); Buffer* next = cur->next_; - Memory::deallocate(cur); + delete cur; cur = next; } assert(prev == child || prev == &head_); @@ -248,7 +248,7 @@ void RingBuffer::try_allocate_for_write() { if (write_head_->write_pos_ == BUFFER_LENGTH && (write_head_->next_ == read_head_ || write_head_->next_->write_pos_ != 0)) { - Buffer* next = Memory::allocate(); + Buffer* next = new Buffer(); next->next_ = write_head_->next_; write_head_->next_ = next; } diff --git a/src/ring_buffer.hpp b/src/ring_buffer.hpp index ba1503a2f..4ee363eea 100644 --- a/src/ring_buffer.hpp +++ b/src/ring_buffer.hpp @@ -42,6 +42,7 @@ #ifndef __CASS_RING_BUFFER_HPP_INCLUDED__ #define __CASS_RING_BUFFER_HPP_INCLUDED__ +#include "allocated.hpp" #include "small_vector.hpp" #include @@ -55,7 +56,7 @@ class RingBuffer { // to fit whole ClientHello into one Buffer of RingBuffer. static const size_t BUFFER_LENGTH = 16 * 1024 + 5; - class Buffer { + class Buffer : public Allocated { public: Buffer() : read_pos_(0), write_pos_(0), next_(NULL) { } diff --git a/src/round_robin_policy.cpp b/src/round_robin_policy.cpp index c7dfdb693..06e95f014 100644 --- a/src/round_robin_policy.cpp +++ b/src/round_robin_policy.cpp @@ -23,7 +23,7 @@ namespace cass { RoundRobinPolicy::RoundRobinPolicy() - : hosts_(Memory::allocate()) + : hosts_(new HostVec()) , index_(0) { uv_rwlock_init(&available_rwlock_); } @@ -53,7 +53,7 @@ CassHostDistance RoundRobinPolicy::distance(const Host::Ptr& host) const { QueryPlan* RoundRobinPolicy::new_query_plan(const String& keyspace, RequestHandler* request_handler, const TokenMap* token_map) { - return Memory::allocate(this, hosts_, index_++); + return new RoundRobinQueryPlan(this, hosts_, index_++); } bool RoundRobinPolicy::is_host_up(const Address& address) const { diff --git a/src/round_robin_policy.hpp b/src/round_robin_policy.hpp index a65a1040e..9ea1ea7d3 100644 --- a/src/round_robin_policy.hpp +++ b/src/round_robin_policy.hpp @@ -45,7 +45,7 @@ class RoundRobinPolicy : public LoadBalancingPolicy { virtual void on_host_up(const Host::Ptr& host); virtual void on_host_down(const Address& address); - virtual LoadBalancingPolicy* new_instance() { return Memory::allocate(); } + virtual LoadBalancingPolicy* new_instance() { return new RoundRobinPolicy(); } private: class RoundRobinQueryPlan : public QueryPlan { diff --git a/src/scoped_ptr.hpp b/src/scoped_ptr.hpp index 068428126..cbac8d432 100644 --- a/src/scoped_ptr.hpp +++ b/src/scoped_ptr.hpp @@ -18,7 +18,6 @@ #define __CASS_SCOPED_PTR_HPP_INCLUDED__ #include "macros.hpp" -#include "ref_counted.hpp" #include "utils.hpp" #include @@ -27,7 +26,7 @@ namespace cass { template struct DefaultDeleter { - void operator()(T* ptr) const { Memory::deallocate(ptr); } + void operator()(T* ptr) const { delete ptr; } }; template > @@ -66,6 +65,46 @@ class ScopedPtr { DISALLOW_COPY_AND_ASSIGN(ScopedPtr); }; +template +struct DefaultArrayDeleter { + void operator()(T* ptr) const { delete[] ptr; } +}; + +template > +class ScopedArray { +public: + typedef T type; + typedef D deleter; + + explicit ScopedArray(type* ptr = NULL) + : ptr_(ptr) {} + + ~ScopedArray() { deleter()(ptr_); } + + void reset(type* ptr = NULL) { + if (ptr_ != NULL) { + deleter()(ptr_); + } + ptr_ = ptr; + } + + type* release() { + type* temp = ptr_; + ptr_ = NULL; + return temp; + } + + type* get() const { return ptr_; } + type& operator[](size_t index) const { return ptr_[index]; } + operator bool() const { return ptr_ != NULL; } + +private: + type* ptr_; + +private: + DISALLOW_COPY_AND_ASSIGN(ScopedArray); +}; + } // namespace cass #endif diff --git a/src/session.cpp b/src/session.cpp index 77a1dda99..69d43e4bc 100644 --- a/src/session.cpp +++ b/src/session.cpp @@ -23,6 +23,7 @@ #include "external.hpp" #include "logger.hpp" #include "metrics.hpp" +#include "monitor_reporting.hpp" #include "prepare_all_handler.hpp" #include "prepare_request.hpp" #include "request_processor_initializer.hpp" @@ -32,7 +33,7 @@ extern "C" { CassSession* cass_session_new() { - cass::Session* session = cass::Memory::allocate(); + cass::Session* session = new cass::Session(); return CassSession::to(session); } @@ -42,7 +43,7 @@ void cass_session_free(CassSession* session) { // if the session is already closed. session->close()->wait(); - cass::Memory::deallocate(session->from()); + delete session->from(); } CassFuture* cass_session_connect(CassSession* session, const CassCluster* cluster) { @@ -108,7 +109,7 @@ CassFuture* cass_session_execute_batch(CassSession* session, const CassBatch* ba const CassSchemaMeta* cass_session_get_schema_meta(const CassSession* session) { return CassSchemaMeta::to( - cass::Memory::allocate( + new cass::Metadata::SchemaSnapshot( session->cluster()->schema_snapshot())); } @@ -212,14 +213,15 @@ class SessionInitializer : public RefCounted { const HostMap& hosts, const TokenMap::Ptr& token_map) { inc_ref(); + const size_t thread_count_io = remaining_ = session_->config().thread_count_io(); for (size_t i = 0; i < thread_count_io; ++i) { RequestProcessorInitializer::Ptr initializer( - Memory::allocate(connected_host, - protocol_version, - hosts, - token_map, - bind_callback(&SessionInitializer::on_initialize, this))); + new RequestProcessorInitializer(connected_host, + protocol_version, + hosts, + token_map, + bind_callback(&SessionInitializer::on_initialize, this))); RequestProcessorSettings settings(session_->config()); settings.connection_pool_settings.connection_settings.client_id = to_string(session_->client_id()); @@ -271,6 +273,9 @@ class SessionInitializer : public RefCounted { session_->notify_connect_failed(error_code_, error_message_); } else { session_->notify_connected(); + session_->cluster()->start_monitor_reporting(to_string(session_->client_id()), + to_string(session_->session_id()), + session_->config()); } l.unlock(); // Unlock before destroying the object dec_ref(); @@ -298,13 +303,13 @@ Session::~Session() { } Future::Ptr Session::prepare(const char* statement, size_t length) { - PrepareRequest::Ptr prepare(Memory::allocate(String(statement, length))); + PrepareRequest::Ptr prepare(new PrepareRequest(String(statement, length))); - ResponseFuture::Ptr future(Memory::allocate(cluster()->schema_snapshot())); + ResponseFuture::Ptr future(new ResponseFuture(cluster()->schema_snapshot())); future->prepare_request = PrepareRequest::ConstPtr(prepare); execute(RequestHandler::Ptr( - Memory::allocate(prepare, future, metrics()))); + new RequestHandler(prepare, future, metrics()))); return future; } @@ -318,26 +323,26 @@ Future::Ptr Session::prepare(const Statement* statement) { query = static_cast(statement)->prepared()->query(); } - PrepareRequest::Ptr prepare(Memory::allocate(query)); + PrepareRequest::Ptr prepare(new PrepareRequest(query)); // Inherit the settings of the existing statement. These will in turn be // inherited by bound statements. prepare->set_settings(statement->settings()); - ResponseFuture::Ptr future(Memory::allocate(cluster()->schema_snapshot())); + ResponseFuture::Ptr future(new ResponseFuture(cluster()->schema_snapshot())); future->prepare_request = PrepareRequest::ConstPtr(prepare); execute(RequestHandler::Ptr( - Memory::allocate(prepare, future, metrics()))); + new RequestHandler(prepare, future, metrics()))); return future; } Future::Ptr Session::execute(const Request::ConstPtr& request, const Address* preferred_address) { - ResponseFuture::Ptr future(Memory::allocate()); + ResponseFuture::Ptr future(new ResponseFuture()); RequestHandler::Ptr request_handler( - Memory::allocate(request, future, + new RequestHandler(request, future, metrics(), preferred_address)); @@ -390,7 +395,7 @@ void Session::on_connect(const Host::Ptr& connected_host, } join(); - event_loop_group_.reset(Memory::allocate(config().thread_count_io())); + event_loop_group_.reset(new RoundRobinEventLoopGroup(config().thread_count_io())); rc = event_loop_group_->init("Request Processor"); if (rc != 0) { notify_connect_failed(CASS_ERROR_LIB_UNABLE_TO_INIT, @@ -405,10 +410,17 @@ void Session::on_connect(const Host::Ptr& connected_host, return; } + for (HostMap::const_iterator it = hosts.begin(), + end = hosts.end(); it != end; ++it) { + const Host::Ptr& host = it->second; + config().host_listener()->on_host_added(host); + config().host_listener()->on_host_up(host); // If host is down it will be marked down later in the connection process + } + request_processors_.clear(); request_processor_count_ = 0; is_closing_ = false; - SessionInitializer::Ptr initializer(Memory::allocate(this)); + SessionInitializer::Ptr initializer(new SessionInitializer(this)); initializer->initialize(connected_host, protocol_version, hosts, @@ -505,8 +517,8 @@ void Session::on_pool_down(const Address& address) { } void Session::on_pool_critical_error(const Address& address, - Connector::ConnectionError code, - const String& message) { + Connector::ConnectionError code, + const String& message) { cluster()->notify_host_down(address); } diff --git a/src/session.hpp b/src/session.hpp index 140485a65..504785715 100644 --- a/src/session.hpp +++ b/src/session.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_SESSION_HPP_INCLUDED__ #define __CASS_SESSION_HPP_INCLUDED__ +#include "allocated.hpp" #include "metrics.hpp" #include "mpmc_queue.hpp" #include "request_processor.hpp" @@ -30,7 +31,8 @@ class RequestProcessorInitializer; class Statement; class Session - : public SessionBase + : public Allocated + , public SessionBase , public RequestProcessorListener { public: Session(); diff --git a/src/session_base.cpp b/src/session_base.cpp index b7855547e..2a0ecefde 100644 --- a/src/session_base.cpp +++ b/src/session_base.cpp @@ -40,6 +40,7 @@ SessionBase::SessionBase() UuidGen generator; generator.generate_random(&client_id_); + generator.generate_random(&session_id_); } SessionBase::~SessionBase() { @@ -52,7 +53,7 @@ SessionBase::~SessionBase() { Future::Ptr SessionBase::connect(const Config& config, const String& keyspace) { - cass::Future::Ptr future(cass::Memory::allocate()); + cass::Future::Ptr future(new SessionFuture()); ScopedMutex l(&mutex_); if (state_ != SESSION_STATE_CLOSED) { @@ -63,7 +64,7 @@ Future::Ptr SessionBase::connect(const Config& config, if (!event_loop_) { int rc = 0; - event_loop_.reset(Memory::allocate()); + event_loop_.reset(new EventLoop()); rc = event_loop_->init("Session/Control Connection"); if (rc != 0) { @@ -80,7 +81,11 @@ Future::Ptr SessionBase::connect(const Config& config, } } + if (config.is_client_id_set()) { + client_id_ = config.client_id(); + } LOG_INFO("Client id is %s", to_string(client_id_).c_str()); + LOG_INFO("Session id is %s", to_string(session_id_).c_str()); config_ = config.new_instance(); connect_keyspace_ = keyspace; @@ -88,18 +93,18 @@ Future::Ptr SessionBase::connect(const Config& config, state_ = SESSION_STATE_CONNECTING; if (config.use_randomized_contact_points()) { - random_.reset(Memory::allocate()); + random_.reset(new Random()); } else { random_.reset(); } - metrics_.reset(Memory::allocate(config.thread_count_io() + 1)); + metrics_.reset(new Metrics(config.thread_count_io() + 1)); cluster_.reset(); ClusterConnector::Ptr connector( - Memory::allocate(config_.contact_points(), - config_.protocol_version(), - bind_callback(&SessionBase::on_initialize, this))); + new ClusterConnector(config_.contact_points(), + config_.protocol_version(), + bind_callback(&SessionBase::on_initialize, this))); ClusterSettings settings(config_); settings.control_connection_settings.connection_settings.client_id = to_string(client_id_); @@ -116,7 +121,7 @@ Future::Ptr SessionBase::connect(const Config& config, } Future::Ptr SessionBase::close() { - cass::Future::Ptr future(cass::Memory::allocate()); + cass::Future::Ptr future(new SessionFuture()); ScopedMutex l(&mutex_); if (state_ == SESSION_STATE_CLOSED || diff --git a/src/session_base.hpp b/src/session_base.hpp index 5ede8ab16..ffbe6384f 100644 --- a/src/session_base.hpp +++ b/src/session_base.hpp @@ -70,6 +70,7 @@ class SessionBase : public ClusterListener { public: CassUuid client_id() const { return client_id_; } + CassUuid session_id() const { return session_id_; } String connect_keyspace() const { return connect_keyspace_; } const Config& config() const { return config_; } Cluster::Ptr cluster() const { return cluster_; } @@ -158,6 +159,7 @@ class SessionBase : public ClusterListener { Future::Ptr connect_future_; Future::Ptr close_future_; CassUuid client_id_; + CassUuid session_id_; }; } // namespace cass diff --git a/src/set.hpp b/src/set.hpp index 2940480f4..fb2876497 100644 --- a/src/set.hpp +++ b/src/set.hpp @@ -8,6 +8,7 @@ #ifndef __DSE_SET_HPP_INCLUDED__ #define __DSE_SET_HPP_INCLUDED__ +#include "allocated.hpp" #include "allocator.hpp" #include @@ -15,7 +16,9 @@ namespace cass { template > -class Set : public std::set > { +class Set + : public Allocated + , public std::set > { public: typedef cass::Allocator Allocator; diff --git a/src/socket.cpp b/src/socket.cpp index b060a1967..230da4ec0 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -69,7 +69,7 @@ SocketHandler::~SocketHandler() { } SocketWriteBase* SocketHandler::new_pending_write(Socket* socket) { - return Memory::allocate(socket); + return new SocketWrite(socket); } void SocketHandler::alloc_buffer(size_t suggested_size, uv_buf_t* buf) { @@ -195,7 +195,7 @@ void SslSocketWrite::on_write(uv_write_t* req, int status) { } SocketWriteBase* SslSocketHandler::new_pending_write(Socket* socket) { - return Memory::allocate(socket, ssl_session_.get()); + return new SslSocketWrite(socket, ssl_session_.get()); } void SslSocketHandler::alloc_buffer(size_t suggested_size, uv_buf_t* buf) { @@ -271,7 +271,7 @@ void SocketWriteBase::handle_write(uv_write_t* req, int status) { clear(); socket->free_writes_.push_back(this); } else { - Memory::deallocate(this); + delete this; } socket->flush(); @@ -385,7 +385,7 @@ void Socket::handle_close() { while (!pending_writes_.is_empty()) { SocketWriteBase* pending_write = pending_writes_.pop_front(); pending_write->on_close(); - Memory::deallocate(pending_write); + delete pending_write; } if (handler_) { @@ -397,7 +397,7 @@ void Socket::handle_close() { void Socket::cleanup_free_writes() { for (SocketWriteVec::iterator i = free_writes_.begin(), end = free_writes_.end(); i != end; ++i) { - Memory::deallocate(*i); + delete *i; } } diff --git a/src/socket.hpp b/src/socket.hpp index fcfad3a1c..c53ebc448 100644 --- a/src/socket.hpp +++ b/src/socket.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_SOCKET_HPP_INCLUDED__ #define __CASS_SOCKET_HPP_INCLUDED__ +#include "allocated.hpp" #include "buffer.hpp" #include "constants.hpp" #include "tcp_connector.hpp" @@ -39,7 +40,9 @@ class SocketWriteBase; * A generic socket request that handles encoding data to be written to a * socket. */ -class SocketRequest : public List::Node { +class SocketRequest + : public Allocated + , public List::Node { public: virtual ~SocketRequest() { } @@ -93,7 +96,7 @@ class BufferSocketRequest : public SocketRequest { * incoming/outgoing data streams e.g. encryption/decryption, * compression/decompression, etc. */ -class SocketHandlerBase { +class SocketHandlerBase : public Allocated { public: virtual ~SocketHandlerBase() { } @@ -192,7 +195,9 @@ class SslSocketHandler : public SocketHandlerBase { * A generic write handler. This is used to coalesce several write requests * into a flush (a write() system call). */ -class SocketWriteBase : public List::Node { +class SocketWriteBase + : public Allocated + , public List::Node { public: typedef cass::List List; diff --git a/src/socket_connector.cpp b/src/socket_connector.cpp index 20e86466d..edb696d8d 100644 --- a/src/socket_connector.cpp +++ b/src/socket_connector.cpp @@ -44,7 +44,7 @@ class SslHandshakeHandler : public SocketHandler { } virtual void on_write(Socket* socket, int status, SocketRequest* request) { - Memory::deallocate(request); + delete request; if (status != 0) { connector_->on_error(SocketConnector::SOCKET_ERROR_WRITE, "Write error"); } @@ -97,8 +97,8 @@ void SocketConnector::connect(uv_loop_t* loop) { if (settings_.hostname_resolution_enabled) { // Run hostname resolution then connect. resolver_.reset( - Memory::allocate(address_, - bind_callback(&SocketConnector::on_resolve, this))); + new NameResolver(address_, + bind_callback(&SocketConnector::on_resolve, this))); resolver_->resolve(loop, settings_.resolve_timeout_ms); } else { // Postpone the connection process until after this method ends because it @@ -125,8 +125,8 @@ Socket::Ptr SocketConnector::release_socket() { void SocketConnector::internal_connect(uv_loop_t* loop) { Socket::Ptr socket( - Memory::allocate(address_, - settings_.max_reusable_write_objects)); + new Socket(address_, + settings_.max_reusable_write_objects)); if (uv_tcp_init(loop, socket->handle()) != 0) { on_error(SOCKET_ERROR_INIT, "Unable to initialize TCP object"); @@ -163,7 +163,7 @@ void SocketConnector::internal_connect(uv_loop_t* loop) { ssl_session_.reset(settings_.ssl_context->create_session(address_, hostname_)); } - connector_.reset(Memory::allocate(address_)); + connector_.reset(new TcpConnector(address_)); connector_->connect(socket_->handle(), bind_callback(&SocketConnector::on_connect, this)); } @@ -184,7 +184,7 @@ void SocketConnector::ssl_handshake() { char buf[SSL_HANDSHAKE_MAX_BUFFER_SIZE]; size_t size = ssl_session_->outgoing().read(buf, SSL_HANDSHAKE_MAX_BUFFER_SIZE); if (size > 0) { - socket_->write_and_flush(Memory::allocate(Buffer(buf, size))); + socket_->write_and_flush(new BufferSocketRequest(Buffer(buf, size))); } // If the handshake process is done then verify the certificate and finish. @@ -245,7 +245,7 @@ void SocketConnector::on_connect(TcpConnector* tcp_connector) { #endif if (ssl_session_) { - socket_->set_handler(Memory::allocate(this)); + socket_->set_handler(new SslHandshakeHandler(this)); ssl_handshake(); } else { finish(); diff --git a/src/speculative_execution.hpp b/src/speculative_execution.hpp index 17b151dea..6f7238f6e 100644 --- a/src/speculative_execution.hpp +++ b/src/speculative_execution.hpp @@ -17,8 +17,8 @@ #ifndef __CASS_SPECULATIVE_EXECUTION_HPP_INCLUDED__ #define __CASS_SPECULATIVE_EXECUTION_HPP_INCLUDED__ +#include "allocated.hpp" #include "host.hpp" -#include "memory.hpp" #include "ref_counted.hpp" #include "string.hpp" @@ -28,7 +28,7 @@ namespace cass { class Request; -class SpeculativeExecutionPlan { +class SpeculativeExecutionPlan : public Allocated { public: virtual ~SpeculativeExecutionPlan() { } @@ -56,11 +56,11 @@ class NoSpeculativeExecutionPolicy : public SpeculativeExecutionPolicy { public: virtual SpeculativeExecutionPlan* new_plan(const String& keyspace, const Request* request) { - return Memory::allocate(); + return new NoSpeculativeExecutionPlan(); } virtual SpeculativeExecutionPolicy* new_instance() { - return Memory::allocate(); + return new NoSpeculativeExecutionPolicy(); } }; @@ -87,13 +87,13 @@ class ConstantSpeculativeExecutionPolicy : public SpeculativeExecutionPolicy { virtual SpeculativeExecutionPlan* new_plan(const String& keyspace, const Request* request) { - return Memory::allocate(constant_delay_ms_, - max_speculative_executions_); + return new ConstantSpeculativeExecutionPlan(constant_delay_ms_, + max_speculative_executions_); } virtual SpeculativeExecutionPolicy* new_instance() { - return Memory::allocate(constant_delay_ms_, - max_speculative_executions_); + return new ConstantSpeculativeExecutionPolicy(constant_delay_ms_, + max_speculative_executions_); } const int64_t constant_delay_ms_; diff --git a/src/spsc_queue.hpp b/src/spsc_queue.hpp index 9db1cb6de..506175845 100644 --- a/src/spsc_queue.hpp +++ b/src/spsc_queue.hpp @@ -31,6 +31,7 @@ #include "atomic.hpp" #include "cassconfig.hpp" #include "macros.hpp" +#include "scoped_ptr.hpp" #include "utils.hpp" namespace cass { @@ -43,7 +44,7 @@ class SPSCQueue { SPSCQueue(size_t size) : size_(next_pow_2(size)) , mask_(size_ - 1) - , buffer_(size_) + , buffer_(new T[size]) , tail_(0) , head_(0) {} @@ -89,7 +90,7 @@ class SPSCQueue { cache_line_pad_t pad0_; const size_t size_; const size_t mask_; - DynamicArray buffer_; + ScopedArray buffer_; cache_line_pad_t pad1_; Atomic tail_; diff --git a/src/ssl.hpp b/src/ssl.hpp index 4178829ba..50d29415d 100644 --- a/src/ssl.hpp +++ b/src/ssl.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_SSL_HPP_INCLUDED__ #define __CASS_SSL_HPP_INCLUDED__ +#include "allocated.hpp" #include "address.hpp" #include "cassandra.h" #include "cassconfig.hpp" @@ -29,7 +30,7 @@ namespace cass { -class SslSession { +class SslSession : public Allocated { public: SslSession(const Address& address, const String& hostname, @@ -85,6 +86,9 @@ class SslContext : public RefCounted { void set_verify_flags(int flags) { verify_flags_ = flags; } + bool is_cert_validation_enabled() { + return verify_flags_ != CASS_SSL_VERIFY_NONE; + } virtual SslSession* create_session(const Address& address, const String& hostname) = 0; virtual CassError add_trusted_cert(const char* cert, size_t cert_length) = 0; diff --git a/src/ssl/ssl_no_impl.cpp b/src/ssl/ssl_no_impl.cpp index e2d7499e3..3a9763cf5 100644 --- a/src/ssl/ssl_no_impl.cpp +++ b/src/ssl/ssl_no_impl.cpp @@ -25,7 +25,7 @@ NoSslSession::NoSslSession(const Address& address, const String& hostname) } SslSession* cass::NoSslContext::create_session(const Address& address, const String& hostname) { - return Memory::allocate(address, hostname); + return new NoSslSession(address, hostname); } CassError cass::NoSslContext::add_trusted_cert(const char* cert, @@ -46,7 +46,7 @@ CassError cass::NoSslContext::set_private_key(const char* key, } SslContext::Ptr NoSslContextFactory::create() { - return SslContext::Ptr(Memory::allocate()); + return SslContext::Ptr(new NoSslContext()); } diff --git a/src/ssl/ssl_openssl_impl.cpp b/src/ssl/ssl_openssl_impl.cpp index 4fc2b783e..725e705e7 100644 --- a/src/ssl/ssl_openssl_impl.cpp +++ b/src/ssl/ssl_openssl_impl.cpp @@ -17,7 +17,6 @@ #include "ssl.hpp" #include "logger.hpp" -#include "memory.hpp" #include "utils.hpp" #include "third_party/curl/hostcheck.hpp" @@ -539,7 +538,7 @@ OpenSslContext::~OpenSslContext() { } SslSession* OpenSslContext::create_session(const Address& address, const String& hostname) { - return Memory::allocate(address, hostname, verify_flags_, ssl_ctx_); + return new OpenSslSession(address, hostname, verify_flags_, ssl_ctx_); } CassError OpenSslContext::add_trusted_cert(const char* cert, @@ -591,7 +590,7 @@ CassError OpenSslContext::set_private_key(const char* key, } SslContext::Ptr OpenSslContextFactory::create() { - return SslContext::Ptr(Memory::allocate()); + return SslContext::Ptr(new OpenSslContext()); } namespace openssl { diff --git a/src/statement.cpp b/src/statement.cpp index 02734bb85..65a423adc 100644 --- a/src/statement.cpp +++ b/src/statement.cpp @@ -42,7 +42,7 @@ CassStatement* cass_statement_new_n(const char* query, size_t query_length, size_t parameter_count) { cass::QueryRequest* query_request - = cass::Memory::allocate(query, query_length, parameter_count); + = new cass::QueryRequest(query, query_length, parameter_count); query_request->inc_ref(); return CassStatement::to(query_request); } diff --git a/src/tcp_connector.hpp b/src/tcp_connector.hpp index 4739fe9a3..447be4a81 100644 --- a/src/tcp_connector.hpp +++ b/src/tcp_connector.hpp @@ -21,7 +21,6 @@ #include "address.hpp" #include "callback.hpp" -#include "memory.hpp" #include "ref_counted.hpp" namespace cass { diff --git a/src/timer.cpp b/src/timer.cpp index b08cd49d0..c5039aac9 100644 --- a/src/timer.cpp +++ b/src/timer.cpp @@ -16,8 +16,6 @@ #include "timer.hpp" -#include "memory.hpp" - namespace cass { Timer::Timer() @@ -31,7 +29,7 @@ Timer::~Timer() { int Timer::start(uv_loop_t* loop, uint64_t timeout, const Timer::Callback& callback) { int rc = 0; if (handle_ == NULL) { - handle_ = Memory::allocate(); + handle_ = new AllocatedT(); handle_->loop = NULL; handle_->data = this; } @@ -50,7 +48,7 @@ int Timer::start(uv_loop_t* loop, uint64_t timeout, const Timer::Callback& callb void Timer::stop() { if (handle_ != NULL) { if (state_ == CLOSED) { // The handle was allocated, but initialization failed. - Memory::deallocate(handle_); + delete handle_; } else { // If initialized or started then close the handle properly. uv_close(reinterpret_cast(handle_), on_close); } @@ -70,7 +68,7 @@ void Timer::handle_timeout() { } void Timer::on_close(uv_handle_t* handle) { - Memory::deallocate(reinterpret_cast(handle)); + delete reinterpret_cast*>(handle); } } // namespace cass diff --git a/src/timer.hpp b/src/timer.hpp index 3a9d18830..b1d6a7ce1 100644 --- a/src/timer.hpp +++ b/src/timer.hpp @@ -17,6 +17,7 @@ #ifndef __CASS_TIMER_HPP_INCLUDED__ #define __CASS_TIMER_HPP_INCLUDED__ +#include "allocated.hpp" #include "callback.hpp" #include "macros.hpp" @@ -52,7 +53,7 @@ class Timer { }; private: - uv_timer_t* handle_; + AllocatedT* handle_; State state_; Callback callback_; diff --git a/src/timestamp_generator.cpp b/src/timestamp_generator.cpp index 0f7c93641..758df3037 100644 --- a/src/timestamp_generator.cpp +++ b/src/timestamp_generator.cpp @@ -23,13 +23,13 @@ extern "C" { CassTimestampGen* cass_timestamp_gen_server_side_new() { - cass::TimestampGenerator* timestamp_gen = cass::Memory::allocate(); + cass::TimestampGenerator* timestamp_gen = new cass::ServerSideTimestampGenerator(); timestamp_gen->inc_ref(); return CassTimestampGen::to(timestamp_gen); } CassTimestampGen* cass_timestamp_gen_monotonic_new() { - cass::TimestampGenerator* timestamp_gen = cass::Memory::allocate(); + cass::TimestampGenerator* timestamp_gen = new cass::MonotonicTimestampGenerator(); timestamp_gen->inc_ref(); return CassTimestampGen::to(timestamp_gen); } @@ -37,8 +37,8 @@ CassTimestampGen* cass_timestamp_gen_monotonic_new() { CassTimestampGen* cass_timestamp_gen_monotonic_new_with_settings(int64_t warning_threshold_us, int64_t warning_interval_ms) { cass::TimestampGenerator* timestamp_gen - = cass::Memory::allocate(warning_threshold_us, - warning_interval_ms); + = new cass::MonotonicTimestampGenerator(warning_threshold_us, + warning_interval_ms); timestamp_gen->inc_ref(); return CassTimestampGen::to(timestamp_gen); } diff --git a/src/token_aware_policy.cpp b/src/token_aware_policy.cpp index 302acb7c7..56d71ce7f 100644 --- a/src/token_aware_policy.cpp +++ b/src/token_aware_policy.cpp @@ -59,26 +59,26 @@ QueryPlan* TokenAwarePolicy::new_query_plan(const String& keyspace, switch (request->opcode()) { { case CQL_OPCODE_QUERY: - case CQL_OPCODE_EXECUTE: - case CQL_OPCODE_BATCH: - String routing_key; - if (request->get_routing_key(&routing_key) && !keyspace.empty()) { - if (token_map != NULL) { - CopyOnWriteHostVec replicas = token_map->get_replicas(keyspace, routing_key); - if (replicas && !replicas->empty()) { - if (random_ != NULL) { - random_shuffle(replicas->begin(), replicas->end(), random_); + case CQL_OPCODE_EXECUTE: + case CQL_OPCODE_BATCH: + String routing_key; + if (request->get_routing_key(&routing_key) && !keyspace.empty()) { + if (token_map != NULL) { + CopyOnWriteHostVec replicas = token_map->get_replicas(keyspace, routing_key); + if (replicas && !replicas->empty()) { + if (random_ != NULL) { + random_shuffle(replicas->begin(), replicas->end(), random_); + } + return new TokenAwareQueryPlan(child_policy_.get(), + child_policy_->new_query_plan(keyspace, + request_handler, + token_map), + replicas, + index_); } - return Memory::allocate(child_policy_.get(), - child_policy_->new_query_plan(keyspace, - request_handler, - token_map), - replicas, - index_); } } - } - break; + break; } default: diff --git a/src/token_aware_policy.hpp b/src/token_aware_policy.hpp index 76ca9b9f3..9fbe09fcb 100644 --- a/src/token_aware_policy.hpp +++ b/src/token_aware_policy.hpp @@ -41,7 +41,7 @@ class TokenAwarePolicy : public ChainedLoadBalancingPolicy { const TokenMap* token_map); LoadBalancingPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), shuffle_replicas_); + return new TokenAwarePolicy(child_policy_->new_instance(), shuffle_replicas_); } private: diff --git a/src/token_map.cpp b/src/token_map.cpp index 3be6102a2..db7ac7d73 100644 --- a/src/token_map.cpp +++ b/src/token_map.cpp @@ -22,11 +22,11 @@ namespace cass { TokenMap::Ptr TokenMap::from_partitioner(StringRef partitioner) { if (ends_with(partitioner, Murmur3Partitioner::name())) { - return Ptr(Memory::allocate >()); + return Ptr(new TokenMapImpl()); } else if (ends_with(partitioner, RandomPartitioner::name())) { - return Ptr(Memory::allocate >()); + return Ptr(new TokenMapImpl()); } else if (ends_with(partitioner, ByteOrderedPartitioner::name())) { - return Ptr(Memory::allocate >()); + return Ptr(new TokenMapImpl()); } else { LOG_WARN("Unsupported partitioner class '%s'", partitioner.to_string().c_str()); return Ptr(); diff --git a/src/token_map.hpp b/src/token_map.hpp index e18ab9242..5a077584a 100644 --- a/src/token_map.hpp +++ b/src/token_map.hpp @@ -18,7 +18,6 @@ #define __CASS_TOKEN_MAP_HPP_INCLUDED__ #include "host.hpp" -#include "memory.hpp" #include "ref_counted.hpp" #include "string.hpp" diff --git a/src/token_map_impl.hpp b/src/token_map_impl.hpp index bf0c2293e..0690229c6 100644 --- a/src/token_map_impl.hpp +++ b/src/token_map_impl.hpp @@ -24,7 +24,6 @@ #include "deque.hpp" #include "json.hpp" #include "map_iterator.hpp" -#include "memory.hpp" #include "result_iterator.hpp" #include "result_response.hpp" #include "row.hpp" @@ -141,8 +140,8 @@ class ByteOrderedPartitioner { class HostSet : public DenseHashSet { public: HostSet() { - set_empty_key(Host::Ptr(Memory::allocate(Address::EMPTY_KEY))); - set_deleted_key(Host::Ptr(Memory::allocate(Address::DELETED_KEY))); + set_empty_key(Host::Ptr(new Host(Address::EMPTY_KEY))); + set_deleted_key(Host::Ptr(new Host(Address::DELETED_KEY))); } }; @@ -402,7 +401,7 @@ void ReplicationStrategy::build_replicas_network_topology(const Tok Token token = i->first; typename TokenHostVec::const_iterator token_it = i; - CopyOnWriteHostVec replicas(Memory::allocate()); + CopyOnWriteHostVec replicas(new HostVec()); replicas->reserve(num_replicas); // Clear datacenter and rack information for the next token @@ -484,7 +483,7 @@ void ReplicationStrategy::build_replicas_simple(const TokenHostVec& size_t num_replicas = std::min(it->second.count, tokens.size()); for (typename TokenHostVec::const_iterator i = tokens.begin(), end = tokens.end(); i != end; ++i) { - CopyOnWriteHostVec replicas(Memory::allocate()); + CopyOnWriteHostVec replicas(new HostVec()); typename TokenHostVec::const_iterator token_it = i; do { replicas->push_back(Host::Ptr(token_it->second)); @@ -501,7 +500,7 @@ template void ReplicationStrategy::build_replicas_non_replicated(const TokenHostVec& tokens, const DatacenterMap& not_used, TokenReplicasVec& result) const { for (typename TokenHostVec::const_iterator i = tokens.begin(); i != tokens.end(); ++i) { - CopyOnWriteHostVec replicas(Memory::allocate(1, Host::Ptr(i->second))); + CopyOnWriteHostVec replicas(new HostVec(1, Host::Ptr(i->second))); result.push_back(TokenReplicas(i->first, replicas)); } } @@ -697,7 +696,7 @@ void TokenMapImpl::build() { template TokenMap::Ptr TokenMapImpl::copy() const { - return Ptr(Memory::allocate >(*this)); + return Ptr(new TokenMapImpl(*this)); } template diff --git a/src/tracing_data_handler.cpp b/src/tracing_data_handler.cpp index d0f0e27cb..517c7236f 100644 --- a/src/tracing_data_handler.cpp +++ b/src/tracing_data_handler.cpp @@ -34,7 +34,7 @@ TracingDataHandler::TracingDataHandler(const RequestHandler::Ptr& request_handle ChainedRequestCallback::Ptr TracingDataHandler::callback() { WaitforRequestVec requests; - QueryRequest::Ptr request(Memory::allocate(SELECT_TRACES_SESSION, 1)); + QueryRequest::Ptr request(new QueryRequest(SELECT_TRACES_SESSION, 1)); request->set_request_timeout_ms(request_timeout_ms()); request->set_consistency(consistency_); request->set(0, response()->tracing_id()); diff --git a/src/tuple.cpp b/src/tuple.cpp index 3c1daac72..9b2ea37f4 100644 --- a/src/tuple.cpp +++ b/src/tuple.cpp @@ -28,7 +28,7 @@ extern "C" { CassTuple* cass_tuple_new(size_t item_count) { - return CassTuple::to(cass::Memory::allocate(item_count)); + return CassTuple::to(new cass::Tuple(item_count)); } CassTuple* cass_tuple_new_from_data_type(const CassDataType* data_type) { @@ -36,12 +36,12 @@ CassTuple* cass_tuple_new_from_data_type(const CassDataType* data_type) { return NULL; } return CassTuple::to( - cass::Memory::allocate( + new cass::Tuple( cass::DataType::ConstPtr(data_type))); } void cass_tuple_free(CassTuple* tuple) { - cass::Memory::deallocate(tuple->from()); + delete tuple->from(); } const CassDataType* cass_tuple_data_type(const CassTuple* tuple) { diff --git a/src/tuple.hpp b/src/tuple.hpp index 2db1f5858..943644f5c 100644 --- a/src/tuple.hpp +++ b/src/tuple.hpp @@ -17,12 +17,12 @@ #ifndef __CASS_TUPLE_HPP_INCLUDED__ #define __CASS_TUPLE_HPP_INCLUDED__ +#include "allocated.hpp" #include "buffer.hpp" #include "cassandra.h" #include "data_type.hpp" #include "encode.hpp" #include "external.hpp" -#include "memory.hpp" #include "ref_counted.hpp" #include "types.hpp" @@ -36,10 +36,10 @@ namespace cass { class Collection; class UserTypeValue; -class Tuple { +class Tuple : public Allocated { public: explicit Tuple(size_t item_count) - : data_type_(Memory::allocate(false)) + : data_type_(new TupleType(false)) , items_(item_count) { } explicit Tuple(const DataType::ConstPtr& data_type) diff --git a/src/user_type_value.cpp b/src/user_type_value.cpp index f46485834..e42ecd640 100644 --- a/src/user_type_value.cpp +++ b/src/user_type_value.cpp @@ -31,12 +31,12 @@ CassUserType* cass_user_type_new_from_data_type(const CassDataType* data_type) { return NULL; } return CassUserType::to( - cass::Memory::allocate( + new cass::UserTypeValue( cass::DataType::ConstPtr(data_type))); } void cass_user_type_free(CassUserType* user_type) { - cass::Memory::deallocate(user_type->from()); + delete user_type->from(); } const CassDataType* cass_user_type_data_type(const CassUserType* user_type) { diff --git a/src/user_type_value.hpp b/src/user_type_value.hpp index fb134ef64..c7dd5c64d 100644 --- a/src/user_type_value.hpp +++ b/src/user_type_value.hpp @@ -21,7 +21,6 @@ #include "cassandra.h" #include "data_type.hpp" #include "external.hpp" -#include "memory.hpp" #include "ref_counted.hpp" namespace cass { diff --git a/src/utils.cpp b/src/utils.cpp index 03e8a9070..425f8b8b3 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -89,6 +89,18 @@ void explode(const String& str, Vector& vec, const char delimiter /* = ' } } +String implode(const Vector& vec, const char delimiter /* = ' ' */) { + String str; + for (Vector::const_iterator it = vec.begin(), + end = vec.end(); it != end; ++it) { + if (!str.empty()) { + str.push_back(delimiter); + } + str.append(*it); + } + return str; +} + String& trim(String& str) { // Trim front str.erase(str.begin(), diff --git a/src/utils.hpp b/src/utils.hpp index dfd278fe2..1315b5ac5 100644 --- a/src/utils.hpp +++ b/src/utils.hpp @@ -69,6 +69,7 @@ String opcode_to_string(int opcode); String to_string(const CassUuid& uuid); void explode(const String& str, Vector& vec, const char delimiter = ','); +String implode(const Vector& vec, const char delimiter = ','); String& trim(String& str); diff --git a/src/uuids.cpp b/src/uuids.cpp index 5add2310a..f47dc51cd 100644 --- a/src/uuids.cpp +++ b/src/uuids.cpp @@ -46,15 +46,15 @@ static uint64_t set_version(uint64_t timestamp, uint8_t version) { extern "C" { CassUuidGen* cass_uuid_gen_new() { - return CassUuidGen::to(cass::Memory::allocate()); + return CassUuidGen::to(new cass::UuidGen()); } CassUuidGen* cass_uuid_gen_new_with_node(cass_uint64_t node) { - return CassUuidGen::to(cass::Memory::allocate(node)); + return CassUuidGen::to(new cass::UuidGen(node)); } void cass_uuid_gen_free(CassUuidGen* uuid_gen) { - cass::Memory::deallocate(uuid_gen->from()); + delete uuid_gen->from(); } void cass_uuid_gen_time(CassUuidGen* uuid_gen, CassUuid* output) { diff --git a/src/uuids.hpp b/src/uuids.hpp index f9c9246c5..b5f132ece 100644 --- a/src/uuids.hpp +++ b/src/uuids.hpp @@ -17,10 +17,10 @@ #ifndef __CASS_UUIDS_HPP_INCLUDED__ #define __CASS_UUIDS_HPP_INCLUDED__ +#include "allocated.hpp" #include "atomic.hpp" #include "cassandra.h" #include "external.hpp" -#include "memory.hpp" #include "random.hpp" #include @@ -29,7 +29,7 @@ namespace cass { -class UuidGen { +class UuidGen : public Allocated { public: UuidGen(); UuidGen(uint64_t node); diff --git a/src/vector.hpp b/src/vector.hpp index 8c590246f..e6fd2b14f 100644 --- a/src/vector.hpp +++ b/src/vector.hpp @@ -8,6 +8,7 @@ #ifndef __DSE_VECTOR_HPP_INCLUDED__ #define __DSE_VECTOR_HPP_INCLUDED__ +#include "allocated.hpp" #include "allocator.hpp" #include @@ -15,7 +16,9 @@ namespace cass { template -class Vector : public std::vector > { +class Vector + : public Allocated + , public std::vector > { public: typedef cass::Allocator Allocator; diff --git a/src/wait_for_handler.cpp b/src/wait_for_handler.cpp index eb263023c..5268b5088 100644 --- a/src/wait_for_handler.cpp +++ b/src/wait_for_handler.cpp @@ -74,7 +74,7 @@ ChainedRequestCallback::Ptr WaitForHandler::callback(const WaitforRequestVec& re for (WaitforRequestVec::const_iterator it = requests.begin(), end = requests.end(); it != end; ++it) { if (!chain) { - chain.reset(Memory::allocate(it->first, it->second, Ptr(this))); + chain.reset(new WaitForCallback(it->first, it->second, Ptr(this))); } else { chain = chain->chain(it->first, it->second); } @@ -83,7 +83,7 @@ ChainedRequestCallback::Ptr WaitForHandler::callback(const WaitforRequestVec& re } WaitForHandler::WaitForRequest WaitForHandler::make_request(const String& key, const String& query) { - QueryRequest::Ptr request(Memory::allocate(query)); + QueryRequest::Ptr request(new QueryRequest(query)); request->set_request_timeout_ms(request_timeout_ms()); return WaitForRequest(key, request); } diff --git a/src/whitelist_dc_policy.hpp b/src/whitelist_dc_policy.hpp index 8d6ac96aa..b31f61c3b 100644 --- a/src/whitelist_dc_policy.hpp +++ b/src/whitelist_dc_policy.hpp @@ -34,7 +34,7 @@ class WhitelistDCPolicy : public ListPolicy { virtual ~WhitelistDCPolicy() {} WhitelistDCPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), dcs_); + return new WhitelistDCPolicy(child_policy_->new_instance(), dcs_); } private: diff --git a/src/whitelist_policy.hpp b/src/whitelist_policy.hpp index 1eb7ea985..7f1a68d1d 100644 --- a/src/whitelist_policy.hpp +++ b/src/whitelist_policy.hpp @@ -34,7 +34,7 @@ class WhitelistPolicy : public ListPolicy { virtual ~WhitelistPolicy() {} WhitelistPolicy* new_instance() { - return Memory::allocate(child_policy_->new_instance(), hosts_); + return new WhitelistPolicy(child_policy_->new_instance(), hosts_); } private: diff --git a/test/ccm_bridge/src/bridge.cpp b/test/ccm_bridge/src/bridge.cpp index 9a32ad2ca..cf8718f8e 100644 --- a/test/ccm_bridge/src/bridge.cpp +++ b/test/ccm_bridge/src/bridge.cpp @@ -627,6 +627,9 @@ bool CCM::Bridge::create_cluster(std::vector data_center_nodes, // Generate the cluster update configuration command and execute execute_ccm_command(generate_create_updateconf_command(cassandra_version_)); + if (dse_version_ >= "6.7.0") { + update_cluster_configuration("user_defined_function_fail_micros", "5000000"); + } // Create the cluster populate command and execute std::string cluster_nodes = generate_cluster_nodes(data_center_nodes); @@ -800,15 +803,16 @@ bool CCM::Bridge::switch_cluster(const std::string& cluster_name) { if (active_cluster.compare(trim(cluster_name)) != 0) { // Ensure the cluster is in the list if (std::find(clusters.begin(), clusters.end(), cluster_name) != clusters.end()) { - // Kill and clear the data on the current active cluster - kill_cluster(); - clear_cluster_data(); + if (!active_cluster.empty()) { + kill_cluster(); + } - // Create the cluster switch command and execute + // Create the cluster switch command and clear the data std::vector switch_command; switch_command.push_back("switch"); switch_command.push_back(cluster_name); execute_ccm_command(switch_command); + clear_cluster_data(); return true; } } else { @@ -851,7 +855,7 @@ void CCM::Bridge::update_cluster_configuration_yaml(const std::string& yaml, boo std::vector updateconf_command; updateconf_command.push_back(is_dse ? "updatedseconf" : "updateconf"); updateconf_command.push_back("-y"); - updateconf_command.push_back("'" + yaml + "'"); + updateconf_command.push_back(yaml); execute_ccm_command(updateconf_command); } @@ -1064,7 +1068,7 @@ bool CCM::Bridge::start_node(unsigned int node, iterator != jvm_arguments.end(); ++iterator) { std::string jvm_argument = trim(*iterator); if (!jvm_argument.empty()) { - start_node_command.push_back("--jvm_arg=\"" + *iterator + "\""); + start_node_command.push_back("--jvm_arg=" + *iterator); } } execute_ccm_command(start_node_command); @@ -1335,7 +1339,11 @@ bool CCM::Bridge::is_node_decommissioned(unsigned int node) { return false; } -bool CCM::Bridge::is_node_down(unsigned int node) { +bool CCM::Bridge::is_node_down(unsigned int node, bool is_quick_check /*= false*/) { + if (is_quick_check) { + return !is_node_availabe(node); + } + unsigned int number_of_retries = 0; while (number_of_retries++ < CCM_RETRIES) { if (!is_node_availabe(node)) { @@ -1352,7 +1360,11 @@ bool CCM::Bridge::is_node_down(unsigned int node) { return false; } -bool CCM::Bridge::is_node_up(unsigned int node) { +bool CCM::Bridge::is_node_up(unsigned int node, bool is_quick_check /*= false*/) { + if (is_quick_check) { + return is_node_availabe(node); + } + unsigned int number_of_retries = 0; while (number_of_retries++ < CCM_RETRIES) { if (is_node_availabe(node)) { diff --git a/test/ccm_bridge/src/bridge.hpp b/test/ccm_bridge/src/bridge.hpp index fc09b38ab..662e22657 100644 --- a/test/ccm_bridge/src/bridge.hpp +++ b/test/ccm_bridge/src/bridge.hpp @@ -738,9 +738,11 @@ namespace CCM { * NOTE: This method may check the status of the node multiple times * * @param node Node to check `DOWN` status + * @param is_quick_check True if `DOWN` status is checked once; false + * otherwise (default: false) * @return True if node is no longer accepting connections; false otherwise */ - bool is_node_down(unsigned int node); + bool is_node_down(unsigned int node, bool is_quick_check = false); /** * Check to see if a node is ready to accept connections @@ -748,9 +750,11 @@ namespace CCM { * NOTE: This method may check the status of the node multiple times * * @param node Node to check `UP` status + * @param is_quick_check True if `UP` status is checked once; false + * otherwise (default: false) * @return True if node is ready to accept connections; false otherwise */ - bool is_node_up(unsigned int node); + bool is_node_up(unsigned int node, bool is_quick_check = false); private: /** diff --git a/test/ccm_bridge/src/cass_version.hpp b/test/ccm_bridge/src/cass_version.hpp index 1a04b6fb6..ecd94d4cc 100644 --- a/test/ccm_bridge/src/cass_version.hpp +++ b/test/ccm_bridge/src/cass_version.hpp @@ -467,13 +467,15 @@ namespace CCM { return CassVersion("3.0.14-1862"); } else if (*this == "5.0.12" || *this == "5.0.13") { return CassVersion("3.0.15-2128"); - } else if (*this >= "5.0.14" && *this < "5.1.0") { - if (*this > "5.0.14") { + } else if (*this == "5.0.14") { + return CassVersion("3.0.15-2269"); + } else if (*this >= "5.0.15" && *this < "5.1.0") { + if (*this > "5.0.15") { std::cerr << "Cassandra Version is not Defined: " << "Add Cassandra version for DSE v" << this->to_string() << std::endl; } - return CassVersion("3.0.15-2128"); + return CassVersion("3.0.16-5015"); } else if (*this == "5.1.0") { return CassVersion("3.10.0-1652"); } else if (*this == "5.1.1") { @@ -492,13 +494,17 @@ namespace CCM { return CassVersion("3.11.1-2261"); } else if (*this == "5.1.10") { return CassVersion("3.11.1-2323"); - } else if (*this >= "5.1.11" && *this < "6.0.0") { - if (*this > "5.1.11") { + } else if (*this == "5.1.11") { + return CassVersion("3.11.2-5111"); + } else if (*this == "5.1.12") { + return CassVersion("3.11.2-5112"); + } else if (*this >= "5.1.13" && *this < "6.0.0") { + if (*this > "5.1.13") { std::cerr << "Cassandra Version is not Defined: " << "Add Cassandra version for DSE v" << this->to_string() << std::endl; } - return CassVersion("3.11.2-5111"); + return CassVersion("3.11.2-5113"); } else if (*this >= "6.0.0" && *this < "6.7.0") { return CassVersion("3.11.2-5111"); // Versions before DSE 6.7 erroneously return they support Cassandra 4.0.0 } else if (*this >= "6.7.0" && *this < "7.0.0") { diff --git a/test/ccm_bridge/src/process.cpp b/test/ccm_bridge/src/process.cpp index 0d56c5ca5..f789394e8 100644 --- a/test/ccm_bridge/src/process.cpp +++ b/test/ccm_bridge/src/process.cpp @@ -94,6 +94,9 @@ Process::Result Process::execute(const Args& command) { rc = uv_loop_close(&loop); if (rc != 0) { uv_print_all_handles(&loop, stderr); + if (!result.standard_error.empty()) { + std::cerr << result.standard_error << std::endl; + } assert(false && "Process loop still has pending handles"); } diff --git a/test/ccm_bridge/src/process.hpp b/test/ccm_bridge/src/process.hpp index 32b38b903..c400411ed 100644 --- a/test/ccm_bridge/src/process.hpp +++ b/test/ccm_bridge/src/process.hpp @@ -28,10 +28,14 @@ typedef struct uv_buf_t uv_buf_t; typedef struct uv_handle_s uv_handle_t; typedef struct uv_process_s uv_process_t; typedef struct uv_stream_s uv_stream_t; -#if defined(_MSC_VER) && !defined(_SSIZE_T_DEFINED) -#include -typedef SSIZE_T ssize_t; -# define _SSIZE_T_DEFINED +#ifdef _MSC_VER +# include +# ifndef _SSIZE_T_DEFINED + typedef SSIZE_T ssize_t; +# define _SSIZE_T_DEFINED +# endif +#else +# include #endif namespace utils { diff --git a/test/integration_tests/src/test_timestamps.cpp b/test/integration_tests/src/test_timestamps.cpp index b30c04c85..fec157f1e 100644 --- a/test/integration_tests/src/test_timestamps.cpp +++ b/test/integration_tests/src/test_timestamps.cpp @@ -185,7 +185,7 @@ BOOST_AUTO_TEST_CASE(generator) CCM::CassVersion version = test_utils::get_version(); if ((version.major_version >= 2 && version.minor_version >= 1) || version.major_version >= 3) { TimestampsTest tester; - cass::SharedRefPtr gen(cass::Memory::allocate(1234)); + cass::SharedRefPtr gen(new TestTimestampGenerator(1234)); cass_cluster_set_timestamp_gen(tester.cluster, CassTimestampGen::to(gen.get())); tester.create_session(); @@ -294,7 +294,7 @@ BOOST_AUTO_TEST_CASE(server_side) BOOST_AUTO_TEST_CASE(monotonic_generator) { TimestampsTest tester; - cass::SharedRefPtr gen(cass::Memory::allocate()); // mimics cass_timestamp_gen_monotonic_new()) + cass::SharedRefPtr gen(new TestMonotonicTimestampGenerator()); // mimics cass_timestamp_gen_monotonic_new()) cass_cluster_set_timestamp_gen(tester.cluster, CassTimestampGen::to(gen.get())); tester.create_session(); @@ -331,7 +331,7 @@ BOOST_AUTO_TEST_CASE(monotonic_generator) BOOST_AUTO_TEST_CASE(monotonic_generator_warnings) { TimestampsTest tester; - cass::SharedRefPtr gen(cass::Memory::allocate(1, 1000)); // mimics cass_timestamp_gen_monotonic_new_with_settings()) + cass::SharedRefPtr gen(new TestMonotonicTimestampGenerator(1, 1000)); // mimics cass_timestamp_gen_monotonic_new_with_settings()) cass_cluster_set_timestamp_gen(tester.cluster, CassTimestampGen::to(gen.get())); tester.create_session(); diff --git a/tools/alloc-linter-tool/.gitignore b/tools/alloc-linter-tool/.gitignore new file mode 100644 index 000000000..0d6591332 --- /dev/null +++ b/tools/alloc-linter-tool/.gitignore @@ -0,0 +1,2 @@ +build +*.creator.user diff --git a/tools/alloc-linter-tool/CMakeLists.txt b/tools/alloc-linter-tool/CMakeLists.txt new file mode 100644 index 000000000..2ac97e6c8 --- /dev/null +++ b/tools/alloc-linter-tool/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 3.10) + +set(_LIBCLANG_ROOT_HINTS ${LIBCLANG_ROOT_DIR} + ENV LIBCLANG_ROOT_DIR + ${_LIBCLANG_ROOT_HINTS}) + +set(_LIBCLANG_ROOT_HINTS_AND_PATHS + HINTS ${_LIBCLANG_ROOT_HINTS} + PATHS ${_LIBCLANG_ROOT_PATHS}) + +set(_LIBCLANG_INCLUDE_NAMES + clang/Config/config.h + llvm/Config/llvm-config.h) + +find_path(LIBCLANG_INCLUDE_DIR + NAMES ${_LIBCLANG_INCLUDE_NAMES} + ${_LIBCLANG_ROOT_HINTS_AND_PATHS} + PATH_SUFFIXES include + NO_DEFAULT_PATH) + +# Order matters here +set(_LIBCLANG_LIBRARY_NAMES + LLVM + clang + clangASTMatchers + clangTooling + clangDriver + clangFrontend + clangSerialization + clangParse + clangSema + clangEdit + clangAST + clangAnalysis + clangLex + clangBasic) + +foreach(NAME ${_LIBCLANG_LIBRARY_NAMES}) + find_library(LIBCLANG_${NAME} + NAMES ${NAME} + ${_LIBCLANG_ROOT_HINTS_AND_PATHS} + PATH_SUFFIXES lib lib/${CMAKE_LIBRARY_ARCHITECTURE} + NO_DEFAULT_PATH) + set(LIBCLANG_LIBRARIES ${LIBCLANG_LIBRARIES} ${LIBCLANG_${NAME}}) +endforeach() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Libclang + REQUIRED_VARS + LIBCLANG_LLVM + LIBCLANG_clang + LIBCLANG_clangASTMatchers + LIBCLANG_clangTooling + LIBCLANG_clangDriver + LIBCLANG_clangFrontend + LIBCLANG_clangSerialization + LIBCLANG_clangParse + LIBCLANG_clangSema + LIBCLANG_clangEdit + LIBCLANG_clangAST + LIBCLANG_clangAnalysis + LIBCLANG_clangLex + LIBCLANG_clangBasic + LIBCLANG_INCLUDE_DIR) + +add_executable(alloc-linter-tool alloc_linter_tool.cpp) + +target_include_directories(alloc-linter-tool + PRIVATE ${LIBCLANG_INCLUDE_DIR}) + +target_link_libraries(alloc-linter-tool + PRIVATE ${LIBCLANG_LIBRARIES}) diff --git a/tools/alloc-linter-tool/README.md b/tools/alloc-linter-tool/README.md new file mode 100644 index 000000000..6e1f997b3 --- /dev/null +++ b/tools/alloc-linter-tool/README.md @@ -0,0 +1,58 @@ +This is a tool that can be used to detect usage of the global or system versions +of `operator new()` and `operator delete()` (and their other allocating +variants). This tool is useful for finding and preventing calls that go around +a library's or application's custom allocator. + +# TODO + +* Support `malloc()` and `free()` +* Filtering for false positives +* Support `std::make_unique()`, `std::make_shared()`, and other allocating + library functions + +# To run + +``` +./alloc-linter-tool /path/to/source/cluster.cpp -- -I/some/include/directory +In file included from .../Code/cpp-driver/src/cluster.cpp:17: +In file included from .../Code/cpp-driver/src/cluster.hpp:20: +In file included from .../Code/cpp-driver/src/config.hpp:20: +In file included from .../Code/cpp-driver/src/auth.hpp:22: +In file included from .../Code/cpp-driver/src/host.hpp:22: +.../Code/cpp-driver/src/copy_on_write_ptr.hpp:85:7: error: Using `operator delete()` from /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/new:124:6 + delete ref; + ^ +.../Code/cpp-driver/src/copy_on_write_ptr.hpp:74:54: error: Using `operator new()` from /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/new:120:7 + ptr_ = SharedRefPtr(new Referenced(new T(*(temp->ref)))); + ^ +.../Code/cpp-driver/src/copy_on_write_ptr.hpp:85:7: error: Using `operator delete()` from /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/new:124:6 + delete ref; +``` + +*Note:* Includes and other compiler flags can be specified after `--` + +# To run in a cmake project + +``` +mkdir build && cd build +cmake -DCMAKE_CXX_CLANG_TIDY=/path/to/tool/alloc-linter-tool .. +make +``` + +# Dependencies + +Requires LLVM and clang (w/ clang's libtooling) + +## On Ubuntu + +``` +sudo apt install libclang-6.0-dev +``` + +# To build + +``` +mkdir build && cd build +LIBCLANG_ROOT_DIR=/path/to/llvm/clang cmake .. +make +``` diff --git a/tools/alloc-linter-tool/alloc_linter_tool.cpp b/tools/alloc-linter-tool/alloc_linter_tool.cpp new file mode 100644 index 000000000..8ab552099 --- /dev/null +++ b/tools/alloc-linter-tool/alloc_linter_tool.cpp @@ -0,0 +1,105 @@ +/* + Copyright (c) DataStax, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Frontend/FrontendActions.h" +#include "clang/Tooling/CommonOptionsParser.h" +#include "clang/Tooling/Tooling.h" +#include "llvm/Support/CommandLine.h" + +using namespace clang::tooling; +using namespace llvm; + +using namespace clang; +using namespace clang::ast_matchers; + +namespace { +StatementMatcher CXXNewMatcher = cxxNewExpr().bind("useNew"); +StatementMatcher CXXDeleteMatcher = cxxDeleteExpr().bind("useDelete"); +} // namespace + +class AllocLinter : public MatchFinder::MatchCallback { +public: + virtual void run(const MatchFinder::MatchResult &Result) { + auto& Context = *Result.Context; + auto& DiagnosticsEngine = Context.getDiagnostics(); + auto& SourceManager = Context.getSourceManager(); + + const auto *NewExpr = Result.Nodes.getNodeAs("useNew"); + if (NewExpr && + !SourceManager.isInSystemHeader(NewExpr->getLocStart()) && // Not in system headers + NewExpr->getNumPlacementArgs() == 0) { // Not placement new + FunctionDecl* NewFuncDecl = NewExpr->getOperatorNew(); + if (NewExpr->isGlobalNew()) { + diag(NewExpr->getLocStart(), "Using global `::operator new%0()`", DiagnosticsEngine) + << (NewExpr->isArray() ? "[]" : ""); + } else if(NewFuncDecl && + SourceManager.isInSystemHeader(NewFuncDecl->getLocation())) { + diag(NewExpr->getLocStart(), "Using `operator new%0()` from %1", DiagnosticsEngine) + << (NewExpr->isArray() ? "[]" : "") + << NewFuncDecl->getLocation().printToString(SourceManager); + } + } + + const auto *DeleteExpr = Result.Nodes.getNodeAs("useDelete"); + if (DeleteExpr && + !DeleteExpr->getDestroyedType().isNull() && + !DeleteExpr->getDestroyedType()->isVoidType() && + !SourceManager.isInSystemHeader(DeleteExpr->getLocStart())) { // Not in system headers + FunctionDecl* DeleteFuncDecl = DeleteExpr->getOperatorDelete(); + if (DeleteExpr->isGlobalDelete()) { + diag(DeleteExpr->getLocStart(), "Using global `::operator delete%0()`", DiagnosticsEngine) + << (DeleteExpr->isArrayForm() ? "[]" : ""); + } else if(DeleteFuncDecl && + SourceManager.isInSystemHeader(DeleteFuncDecl->getLocation())) { + diag(DeleteExpr->getLocStart(), "Using `operator delete%0()` from %1", DiagnosticsEngine) + << (DeleteExpr->isArrayForm()? "[]" : "") + << DeleteFuncDecl->getLocation().printToString(SourceManager); + } + } + } + + DiagnosticBuilder diag(SourceLocation Loc, + StringRef Description, + DiagnosticsEngine& DiagnosticsEngine) { + auto ID = DiagnosticsEngine.getDiagnosticIDs()->getCustomDiagID(clang::DiagnosticIDs::Error, + Description); + return DiagnosticsEngine.Report(Loc, ID); + } +}; + +static llvm::cl::OptionCategory AllocLinterToolCategory("alloc-linter options"); + +static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); + +static cl::extrahelp MoreHelp("\nThis is a tool for finding global " + "use of operator new/delete (from either global\n" + "or from the standard library) and other forms " + "of global allocation.\n"); + +int main(int argc, const char **argv) { + CommonOptionsParser OptionsParser(argc, argv, AllocLinterToolCategory); + ClangTool Tool(OptionsParser.getCompilations(), + OptionsParser.getSourcePathList()); + + AllocLinter Linter; + MatchFinder Finder; + Finder.addMatcher(CXXNewMatcher, &Linter); + Finder.addMatcher(CXXDeleteMatcher, &Linter); + + return Tool.run(newFrontendActionFactory(&Finder).get()); +}