diff --git a/cppcache/integration-test/BBNamingContext.cpp b/cppcache/integration-test/BBNamingContext.cpp deleted file mode 100644 index 8a8001a290..0000000000 --- a/cppcache/integration-test/BBNamingContext.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 _WIN32 - -#include "BBNamingContext.hpp" - -#include -#include "fwklib/FwkBBServer.hpp" -#include "fwklib/FwkBBClient.hpp" -#include "fwklib/FwkStrCvt.hpp" -#include - -#define ERR_MAX 10 - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -static int hashcode(char *str) { - if (str == nullptr) { - return 0; - } - int localHash = 0; - - int prime = 31; - char *data = str; - for (int i = 0; i < 50 && (data[i] != '\0'); i++) { - localHash = prime * localHash + data[i]; - } - if (localHash > 0) return localHash; - return -1 * localHash; -} - -static int getRandomNum() { - char *testName = std::getenv("TESTNAME"); - - int seed = hashcode(testName) + 11; - - printf("seed for BBPort process %d\n", seed); - // The integration tests rely on the pseudo-random - // number generator being seeded with a very particular - // value specific to the test by way of the test name. - // Whilst this approach is pessimal, it can not be - // remedied as the test depend upon it. - std::srand(seed); - // NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.rand) - return (std::rand() % 49999) + 14000; -} - -static int G_BBPORT = getRandomNum(); - -class BBNamingContextClientImpl { - FwkBBClient *m_bbc; - uint32_t m_errCount; - bool checkValue(const std::string &k, const std::string &k1, - const std::string &value); - - public: - BBNamingContextClientImpl(); - ~BBNamingContextClientImpl(); - void open(); - void close(); - void dump(); - int rebind(const char *key, const char *value, char *type); - int resolve(const std::string &key, std::string &value, char *); -}; - -class BBNamingContextServerImpl { - FwkBBServer *m_bbServer; - UDPMessageQueues *m_shared; - STReceiver *m_recv; - BBProcessor *m_serv; - Responder *m_resp; - Service *m_farm; - - public: - BBNamingContextServerImpl(); - ~BBNamingContextServerImpl(); -}; -// -// Impls: -// -BBNamingContextClientImpl::BBNamingContextClientImpl() - : m_bbc(nullptr), m_errCount(0) {} -BBNamingContextClientImpl::~BBNamingContextClientImpl() { close(); } -void BBNamingContextClientImpl::open() { - try { - // char * bbPort = std::getenv( "BB_PORT" ); - std::string endpoint = "localhost:" + std::to_string(G_BBPORT); - fprintf(stdout, "Blackboard client is talking on %s\n", endpoint.c_str()); - fflush(stdout); - m_bbc = new FwkBBClient(endpoint); - } catch (FwkException &e) { - FWKEXCEPTION("create bb client encounted Exception: " << e.what()); - } catch (...) { - FWKEXCEPTION("create bb client unknow exception\n"); - } -} -void BBNamingContextClientImpl::close() { - if (m_bbc != nullptr) { - delete m_bbc; - m_bbc = nullptr; - } -} -int BBNamingContextClientImpl::rebind(const char *key, const char *value, - char *) { - // fprintf(stdout, "bind: key=%s, value=%s\n", key, value); - if (m_bbc == nullptr) { - return -1; - } - if (m_errCount > ERR_MAX) { - close(); - return -1; - } - - try { - std::string k(key); - std::string k1("1"); - std::string v(value); - m_bbc->set(k, k1, v); - if (false == checkValue(k, k1, value)) { - m_errCount++; - } else { - if (m_errCount > 0) { - m_errCount = 0; - } - return 0; - } - } catch (FwkException &e) { - m_errCount++; - FWKEXCEPTION(" rebind encounted Exception: " << e.what()); - } catch (...) { - m_errCount++; - FWKEXCEPTION("rebind unknown exception\n"); - } - return -1; -} -void BBNamingContextClientImpl::dump() { - if (m_bbc == nullptr) { - return; - } - if (m_errCount > ERR_MAX) { - close(); - return; - } - try { - std::string bb = m_bbc->dump(); - FWKINFO("Dump Blackboard " << bb); - if (m_errCount > 0) { - m_errCount = 0; - } - } catch (FwkException &e) { - m_errCount++; - FWKEXCEPTION("create dump encounted Exception: " << e.what()); - } catch (...) { - m_errCount++; - FWKEXCEPTION("dump unknown exception\n"); - } -} -int BBNamingContextClientImpl::resolve(const std::string &key, - std::string &value, char *) { - if (m_bbc == nullptr) { - return -1; - } - if (m_errCount > ERR_MAX) { - close(); - return -1; - } - try { - value = m_bbc->getString(key, "1"); - if (m_errCount > 0) { - m_errCount = 0; - } - return value.length() == 0 ? -1 : 0; - } catch (FwkException &e) { - m_errCount++; - FWKEXCEPTION("create resolve encounted Exception: " << e.what()); - } catch (...) { - m_errCount++; - FWKEXCEPTION("resolve unknown exception\n"); - } -} - -bool BBNamingContextClientImpl::checkValue(const std::string &k, - const std::string &k1, - const std::string &value) { - bool valid = false; - try { - std::string v = m_bbc->getString(k, k1); - if (value == v) valid = true; - } catch (FwkException &e) { - FWKEXCEPTION("create resolve encounted Exception: " << e.what()); - } catch (...) { - FWKEXCEPTION("resolve unknown exception\n"); - } - return valid; -} - -BBNamingContextServerImpl::BBNamingContextServerImpl() { - try { - // char * bbPort = std::getenv( "BB_PORT" ); - - std::string port = std::to_string(G_BBPORT); - FwkStrCvt bPort(port); - uint32_t prt = bPort.toUInt32(); - fprintf(stdout, "Blackboard server is on port:%u\n", prt); - fflush(stdout); - m_bbServer = new FwkBBServer(); - m_shared = new UDPMessageQueues("BBQueues"); - m_recv = new STReceiver(m_shared, prt); - m_serv = new BBProcessor(m_shared, m_bbServer); - m_resp = new Responder(m_shared, prt); - m_farm = new Service(3); - m_farm->runThreaded(m_recv, 1); - m_farm->runThreaded(m_serv, 1); - m_farm->runThreaded(m_resp, 1); - } catch (FwkException &e) { - FWKEXCEPTION("create bb server encounted Exception: " << e.what()); - } catch (...) { - FWKSEVERE("create bb server unknown exception\n"); - } -} - -BBNamingContextServerImpl::~BBNamingContextServerImpl() { - delete m_farm; - delete m_bbServer; - delete m_shared; - delete m_recv; - delete m_serv; - delete m_resp; -} -// -// client -// -BBNamingContextClient::BBNamingContextClient() { - m_impl = new BBNamingContextClientImpl(); -} -BBNamingContextClient::~BBNamingContextClient() { - if (m_impl) { - delete m_impl; - m_impl = nullptr; - } -} -void BBNamingContextClient::open() { m_impl->open(); } -void BBNamingContextClient::close() { m_impl->close(); } -void BBNamingContextClient::dump() { m_impl->dump(); } -int BBNamingContextClient::rebind(const char *key, const char *value, - char *type) { - return m_impl->rebind(key, value, type); -} -int BBNamingContextClient::resolve(const std::string &key, std::string &value, - char *type) { - return m_impl->resolve(key, value, type); -} -// -// server -// -BBNamingContextServer::BBNamingContextServer() { - m_impl = new BBNamingContextServerImpl(); -} -BBNamingContextServer::~BBNamingContextServer() { - // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): ACE - if (m_impl != nullptr) { - delete m_impl; - m_impl = nullptr; - } -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif diff --git a/cppcache/integration-test/BBNamingContext.hpp b/cppcache/integration-test/BBNamingContext.hpp deleted file mode 100644 index c00ebfb98f..0000000000 --- a/cppcache/integration-test/BBNamingContext.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -#pragma once - -#ifndef GEODE_INTEGRATION_TEST_BBNAMINGCONTEXT_H_ -#define GEODE_INTEGRATION_TEST_BBNAMINGCONTEXT_H_ - -// This these classes should have been in the framework libary. If we ever use -// these, instead of the ACE context, onto windows and Linux then we should -// move them there. -// This will avoid pulling in a lot of framework headers to cause compilation -// grieve, especially with the stl stuff. -#include -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -class BBNamingContextClientImpl; -class BBNamingContextClient { - BBNamingContextClientImpl* m_impl; - - public: - BBNamingContextClient(); - ~BBNamingContextClient(); - void open(); - void close(); - int rebind(const char* key, const char* value, char* type = nullptr); - void dump(); - int resolve(const std::string& key, std::string& value, char* type = nullptr); -}; -class BBNamingContextServerImpl; -class BBNamingContextServer { - public: - BBNamingContextServerImpl* m_impl; - BBNamingContextServer(); - ~BBNamingContextServer(); -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_INTEGRATION_TEST_BBNAMINGCONTEXT_H_ diff --git a/cppcache/integration-test/CMakeLists.txt b/cppcache/integration-test/CMakeLists.txt index bb5f3d12cb..66c8887377 100644 --- a/cppcache/integration-test/CMakeLists.txt +++ b/cppcache/integration-test/CMakeLists.txt @@ -18,7 +18,6 @@ project(nativeclient.tests.cppcache LANGUAGES CXX) add_library(test-cppcache-utils STATIC fw_dunit.cpp - BBNamingContext.cpp CacheHelper.cpp CacheableWrapper.cpp ) diff --git a/cppcache/integration-test/fw_dunit.cpp b/cppcache/integration-test/fw_dunit.cpp index 5589a8ca62..17beb1ef16 100644 --- a/cppcache/integration-test/fw_dunit.cpp +++ b/cppcache/integration-test/fw_dunit.cpp @@ -16,59 +16,35 @@ * limitations under the License. */ -#ifdef WIN32 -// ace.dll was built with FD_SETSIZE of 1024, so ensure it stays that way. -#undef FD_SETSIZE -#define FD_SETSIZE 1024 -#if WINVER == 0x0500 -#undef _WINSOCKAPI_ -#define NOMINMAX -#include -#endif -#endif - #ifdef USE_SMARTHEAP #include #endif #include +#include #include #include +#include + #include #include +#include -// SW: Switching to framework BB on linux also since it is much faster. -#ifndef _WIN32 -// On solaris, when ACE_Naming_Context maps file to memory using fixed mode, it -// interfere with malloc/brk system calls later cause failure. For now, we use -// the Black Board from the regression test framework. When the ACE problem is -// fixed in a new release we'll go back to original code by undefining -// SOLARIS_USE_BB -#define SOLARIS_USE_BB 1 -#endif - -#define VALUE_MAX 128 - -#ifdef SOLARIS_USE_BB -#include "BBNamingContext.hpp" -using apache::geode::client::testframework::BBNamingContextClient; -using apache::geode::client::testframework::BBNamingContextServer; +#ifdef _WIN32 +#include #else -#include +#include #endif -#include -#include -#include -#include - #include "fw_spawn.hpp" #include "fwklib/FwkException.hpp" #define __DUNIT_NO_MAIN__ #include "fw_dunit.hpp" +namespace bip = boost::interprocess; + static std::string g_programName; static uint32_t g_coordinatorPid = 0; @@ -76,14 +52,6 @@ ClientCleanup gClientCleanup; namespace dunit { -void HostWaitForDebugger() { - int done = 0; - LOG("host wait for debugger."); - while (!done) { - sleep(1); - } -} - void setupCRTOutput() { #ifdef _WIN32 #ifdef DEBUG @@ -116,174 +84,6 @@ void getTimeStr(char *bufPtr, size_t sizeOfBuf) { void log(std::string s, int lineno, const char *filename); -/** Naming service for sharing data between processes. */ -class NamingContextImpl : virtual public NamingContext { - private: -#ifdef SOLARIS_USE_BB - BBNamingContextClient -#else - ACE_Naming_Context -#endif - - m_context; - - void millisleep(int msec) { - std::this_thread::sleep_for(std::chrono::milliseconds{msec}); - } - - int checkResult(int result, const char *func) { - if (result == -1) { - LOGCOORDINATOR("NamingCtx operation failed for:"); - LOGCOORDINATOR(func); - LOGCOORDINATOR("Dump follows:"); - dump(); - throw -1; - } - return result; - } - - public: - NamingContextImpl() : m_context() { - open(); - LOGCOORDINATOR("Naming context ready."); - } - - ~NamingContextImpl() noexcept override { - m_context.close(); - std::remove(std::getenv("TESTNAME")); - } - - /** - * Share a string value, return -1 if there is a failure to store value, - * otherwise returns 0. - */ - int rebind(const char *key, const char *value) override { - int res = -1; - int attempts = 10; - while ((res = m_context.rebind(key, value, const_cast(""))) == -1 && - attempts--) { - millisleep(10); - } - return checkResult(res, "rebind"); - } - - /** - * Share an int value, return -1 if there is a failure to store value, - * otherwise returns 0. - */ - int rebind(const char *key, int value) override { - return rebind(key, std::to_string(value).c_str()); - } - - /** - * retreive a value by key, storing the result in the users buf. If the key - * is not found, the buf will contain the empty string "". - */ - std::string getValue(const std::string &key) override { -#ifdef SOLARIS_USE_BB - std::string value; - char type[VALUE_MAX] = {0}; -#else - char *type = nullptr; - char *value = nullptr; -#endif - - int attempts = 3; - while (m_context.resolve(key.c_str(), value, type) != 0 && attempts--) { - // we should not increase sleep to avoid increasing test run times. - millisleep(5); - } - -#ifndef SOLARIS_USE_BB - if (value == nullptr) { - return {}; - } -#endif - - return value; - } - - /** - * return the value by key, as an int using the string to int conversion - * rules of atoi. - */ - int getIntValue(const std::string &key) override { - auto val = getValue(key); - return val.empty() ? 0 : std::stoi(val); - } - - void open() { -#ifdef SOLARIS_USE_BB - m_context.open(); -#else - ACE_Name_Options *name_options = m_context.name_options(); - name_options->process_name(getContextName().c_str()); - name_options->namespace_dir("."); - name_options->context(ACE_Naming_Context::PROC_LOCAL); - name_options->database(std::getenv("TESTNAME")); - checkResult(m_context.open(name_options->context(), 0), "open"); -#endif - LOGCOORDINATOR("Naming context opened."); - } - - std::string getContextName() { - return "dunit.context." + - boost::filesystem::path{g_programName}.filename().stem().string() + - std::to_string(g_coordinatorPid); - } - - std::string getMutexName() { - return "dunit.mutex." + - boost::filesystem::path{g_programName}.filename().stem().string() + - std::to_string(g_coordinatorPid); - } - - /** print out all the entries' keys and values in the naming context. */ - void dump() override { -#ifdef SOLARIS_USE_BB - m_context.dump(); -#else - ACE_BINDING_SET set; - if (this->m_context.list_name_entries(set, "") != 0) { - char buf[1000] = {0}; - ::sprintf(buf, "There is nothing in the naming context."); - LOGCOORDINATOR(buf); - } else { - ACE_BINDING_ITERATOR set_iterator(set); - for (ACE_Name_Binding *entry = 0; set_iterator.next(entry) != 0; - set_iterator.advance()) { - ACE_Name_Binding binding(*entry); - char buf[1000] = {0}; - ::sprintf(buf, "%s => %s", binding.name_.char_rep(), - binding.value_.char_rep()); - LOGCOORDINATOR(buf); - } - } -#endif - } - - void resetContext() { - char buf[30] = {0}; - sprintf(buf, "%d", boost::this_process::get_id()); - - int res1 = -1; - int attempts1 = 10; - while ((res1 = m_context.rebind("Driver", buf)) == -1 && attempts1--) { - millisleep(10); - } - checkResult(res1, "rebind1"); - - int res2 = -1; - int attempts2 = 10; - while ((res2 = m_context.rebind("WorkerId", "0")) == -1 && attempts2--) { - millisleep(10); - } - checkResult(res2, "rebind2"); - - LOGCOORDINATOR("Naming context reset."); - } -}; - /** uniquely represent each different worker. */ class WorkerId { private: @@ -293,7 +93,7 @@ class WorkerId { public: explicit WorkerId(uint32_t id) { m_id = id; } - int getId() { return m_id; } + int getId() const { return m_id; } const char *getIdName() { return m_idNames[m_id]; } @@ -383,34 +183,119 @@ void Task::init(int sId, bool isHeapAllocated) { TaskQueues::addTask(WorkerId(sId), this); } +class TestState { + public: + static const auto WORKER_COUNT = 4U; + + void reset(); + + void setWorkerTimeout(int id, int seconds); + + int getWorkerTimeout(int id) const; + + void setWorkerState(int id, uint8_t state); + + int getWorkerState(int id) const; + + void setNextWorker(int id); + + int getNextWorker(); + + void fail(); + + bool failed() const; + + void terminate(); + + bool terminated() const; + + private: + bool failure_; + bool terminate_; + int next_worker_; + int worker_timeout_[WORKER_COUNT]; + uint8_t worker_state_[WORKER_COUNT]; +}; + /** main framework entry */ class Dunit { private: - NamingContextImpl m_globals; + static const auto MANAGED_STATE_SIZE = 1UL << 17UL; static Dunit *singleton; - bool m_close_down; - Dunit() : m_globals(), m_close_down(false) {} + bool coordinator_; + bip::mapped_region globals_region_; +#ifdef _WIN32 + bip::windows_shared_memory globals_shm_; +#else + bip::shared_memory_object globals_shm_; +#endif + bip::managed_shared_memory managed_state_; - void resetContext() { - m_close_down = true; - m_globals.resetContext(); - } + explicit Dunit(bool coordinator) : coordinator_(coordinator) { + if (coordinator) { + removeStates(); - public: - /** call this once just inside main... */ - static void init(bool initContext = false) { - if (initContext) { - std::remove("localnames"); - std::remove("name_space_localnames"); - std::remove("backing_store_localnames"); +#ifdef _WIN32 + globals_shm_ = + bip::windows_shared_memory{bip::create_only, getSharedName(), + bip::read_write, sizeof(TestState)}; +#else + globals_shm_ = bip::shared_memory_object{ + bip::create_only, getSharedName(), bip::read_write}; + globals_shm_.truncate(sizeof(TestState)); +#endif + + managed_state_ = bip::managed_shared_memory{ + bip::create_only, getManagedStateName(), MANAGED_STATE_SIZE}; + } else { + using shared_memory = +#ifdef _WIN32 + bip::windows_shared_memory; +#else + bip::shared_memory_object; +#endif + + globals_shm_ = + shared_memory{bip::open_only, getSharedName(), bip::read_write}; + managed_state_ = + bip::managed_shared_memory{bip::open_only, getManagedStateName()}; } - singleton = new Dunit(); - if (initContext) { - singleton->resetContext(); + + globals_region_ = bip::mapped_region{globals_shm_, bip::read_write}; + + if (coordinator) { + getState()->reset(); + } + } + + ~Dunit() { + if (coordinator_) { + removeStates(); } } + static void removeStates() { + bip::shared_memory_object::remove(getSharedName()); + bip::shared_memory_object::remove(getManagedStateName()); + } + + static const char *getSharedName() { + static std::string name = std::string{std::getenv("TESTNAME")} + '.' + + std::to_string(g_coordinatorPid); + return name.c_str(); + } + + static const char *getManagedStateName() { + static std::string name = std::string{std::getenv("TESTNAME")} + + ".managed." + std::to_string(g_coordinatorPid); + return name.c_str(); + } + + public: + /** call this once just inside main... */ + static void init(bool coordinator) { singleton = new Dunit(coordinator); } + /** return the already initialized singleton Dunit instance. */ static Dunit *getSingleton() { ASSERT(singleton != nullptr, "singleton not created yet."); @@ -424,60 +309,60 @@ class Dunit { delete tmp; } - /** set the next worker id */ - void setNextWorker(WorkerId &sId) { - m_globals.rebind("WorkerId", sId.getId()); + TestState *getState() { + return reinterpret_cast(globals_region_.get_address()); } - /** get the next worker id */ - int getNextWorker() { return m_globals.getIntValue("WorkerId"); } - - /** return true if all workers are to terminate. */ - bool mustQuit() { - return m_globals.getIntValue("TerminateAllWorkers") ? true : false; - } + bip::managed_shared_memory &getManagedState() { return managed_state_; } +}; - /** signal all workers to terminate. */ - void setMustQuit() { m_globals.rebind("TerminateAllWorkers", 1); } +#define DUNIT dunit::Dunit::getSingleton() - /** signal to test driver that an error occurred. */ - void setFailed() { m_globals.rebind("Failure", 1); } +Dunit *Dunit::singleton = nullptr; - bool getFailed() { return m_globals.getIntValue("Failure") ? true : false; } +void TestState::reset() { + next_worker_ = 0; + failure_ = false; + terminate_ = false; - void setWorkerState(WorkerId sId, int state) { - m_globals.rebind(("ReadyWorker" + std::to_string(sId.getId())).c_str(), - state); + for (auto i = 0U; i < WORKER_COUNT; ++i) { + worker_state_[i] = 0; + worker_timeout_[i] = -1; } +} - int getWorkerState(WorkerId sId) { - return m_globals.getIntValue("ReadyWorker" + std::to_string(sId.getId())); - } +void TestState::setWorkerTimeout(int id, int seconds) { + worker_timeout_[id - 1] = seconds; +} - void setWorkerTimeout(WorkerId sId, int seconds) { - m_globals.rebind(("TimeoutWorker" + std::to_string(sId.getId())).c_str(), - seconds); - } +int TestState::getWorkerTimeout(int id) const { + return worker_timeout_[id - 1]; +} - int getWorkerTimeout(WorkerId sId) { - return m_globals.getIntValue("TimeoutWorker" + std::to_string(sId.getId())); - } +void TestState::setWorkerState(int id, uint8_t state) { + worker_state_[id - 1] = state; +} - /** return the NamingContext for global (amongst all processes) values. */ - NamingContext *globals() { return &m_globals; } +int TestState::getWorkerState(int id) const { return worker_state_[id - 1]; } - ~Dunit() {} -}; +void TestState::setNextWorker(int id) { next_worker_ = id; } -#define DUNIT dunit::Dunit::getSingleton() +int TestState::getNextWorker() { return next_worker_; } -Dunit *Dunit::singleton = nullptr; +void TestState::fail() { failure_ = true; } + +bool TestState::failed() const { return failure_; } + +void TestState::terminate() { terminate_ = true; } + +bool TestState::terminated() const { return terminate_; } void Task::setTimeout(int seconds) { + auto state = DUNIT->getState(); if (seconds > 0) { - DUNIT->setWorkerTimeout(WorkerId(m_id), seconds); + state->setWorkerTimeout(m_id, seconds); } else { - DUNIT->setWorkerTimeout(WorkerId(m_id), TASK_TIMEOUT); + state->setWorkerTimeout(m_id, TASK_TIMEOUT); } } @@ -503,19 +388,9 @@ class TestProcess : virtual public dunit::Manager { class TestDriver { private: TestProcess *m_workers[4]; -#ifdef SOLARIS_USE_BB - BBNamingContextServer *m_bbNamingContextServer; -#endif public: TestDriver() { -#ifdef SOLARIS_USE_BB - m_bbNamingContextServer = new BBNamingContextServer(); - std::this_thread::sleep_for(std::chrono::seconds(5)); - fprintf(stdout, "Blackboard started\n"); - fflush(stdout); -#endif - dunit::Dunit::init(true); fprintf(stdout, "Coordinator starting workers.\n"); for (uint32_t i = 1; i < 5; i++) { @@ -551,16 +426,13 @@ class TestDriver { ~TestDriver() { // kill off any children that have not yet terminated. - for (uint32_t i = 1; i < 5; i++) { - if (m_workers[i - 1]->running() == 1) { - delete m_workers[i - 1]; // worker destructor should terminate process. + for (uint32_t i = 0; i < TestState::WORKER_COUNT;) { + auto worker = m_workers[i++]; + if (worker->running() == 1) { + delete worker; // worker destructor should terminate process. } } dunit::Dunit::close(); -#ifdef SOLARIS_USE_BB - delete m_bbNamingContextServer; - m_bbNamingContextServer = nullptr; -#endif } int begin() { @@ -571,39 +443,50 @@ class TestDriver { // dispatch task... int nextWorker; + auto state = DUNIT->getState(); while ((nextWorker = TaskQueues::getWorkerId()) != 0) { WorkerId sId(nextWorker); - DUNIT->setWorkerState(sId, WORKER_STATE_SCHEDULED); + state->setWorkerState(nextWorker, WORKER_STATE_SCHEDULED); fprintf(stdout, "Set next process to %s\n", sId.getIdName()); fflush(stdout); - DUNIT->setNextWorker(sId); + + state->setNextWorker(nextWorker); waitForCompletion(sId); // check special conditions. - if (DUNIT->getFailed()) { - DUNIT->setMustQuit(); + if (state->failed()) { + state->terminate(); waitForDone(); return 1; } } // end all work.. - DUNIT->setMustQuit(); + state->terminate(); waitForDone(); return 0; } /** wait for an individual worker to finish a task. */ void waitForCompletion(WorkerId &sId) { - int secs = DUNIT->getWorkerTimeout(sId); - DUNIT->setWorkerTimeout(sId, TASK_TIMEOUT); - if (secs <= 0) secs = TASK_TIMEOUT; + auto id = sId.getId(); + auto state = DUNIT->getState(); + + int secs = state->getWorkerTimeout(id); + state->setWorkerTimeout(id, TASK_TIMEOUT); + if (secs <= 0) { + secs = TASK_TIMEOUT; + } + fprintf(stdout, "Waiting %d seconds for %s to finish task.\n", secs, sId.getIdName()); fflush(stdout); auto end = std::chrono::steady_clock::now() + std::chrono::seconds{secs}; - while (DUNIT->getWorkerState(sId) != WORKER_STATE_TASK_COMPLETE) { + while (state->getWorkerState(id) != WORKER_STATE_TASK_COMPLETE) { // sleep a bit.. - if (DUNIT->getFailed()) return; + if (state->failed()) { + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds{100}); checkWorkerDeath(); auto now = std::chrono::steady_clock::now(); @@ -617,31 +500,39 @@ class TestDriver { void handleTimeout() { fprintf(stdout, "Error: Timed out waiting for all workers to be ready.\n"); fflush(stdout); - DUNIT->setMustQuit(); - DUNIT->setFailed(); + + auto state = DUNIT->getState(); + state->terminate(); + state->fail(); } void handleTimeout(WorkerId &sId) { fprintf(stdout, "Error: Timed out waiting for %s to finish task.\n", sId.getIdName()); fflush(stdout); - DUNIT->setMustQuit(); - DUNIT->setFailed(); + + auto state = DUNIT->getState(); + state->terminate(); + state->fail(); } - /** wait for all workers to be done initializing. */ + /** wait for all workers + * to be done initializing. */ void waitForReady() { + auto state = DUNIT->getState(); fprintf(stdout, "Waiting %d seconds for all workers to be ready.\n", TASK_TIMEOUT); fflush(stdout); + auto end = std::chrono::steady_clock::now() + std::chrono::seconds{TASK_TIMEOUT}; + uint32_t readyCount = 0; - while (readyCount < 4) { + while (readyCount < TestState::WORKER_COUNT) { fprintf(stdout, "Ready Count: %d\n", readyCount); fflush(stdout); - if (DUNIT->getFailed()) { + if (state->failed()) { return; } @@ -649,11 +540,12 @@ class TestDriver { readyCount = 0; for (uint32_t i = 1; i < 5; i++) { - int state = DUNIT->getWorkerState(WorkerId(i)); - if (state == WORKER_STATE_READY) { - readyCount++; + int status = state->getWorkerState(i); + if (status == WORKER_STATE_READY) { + ++readyCount; } } + checkWorkerDeath(); auto now = std::chrono::steady_clock::now(); if (now >= end) { @@ -665,6 +557,7 @@ class TestDriver { /** wait for all workers to be destroyed. */ void waitForDone() { + auto state = DUNIT->getState(); fprintf(stdout, "Waiting %d seconds for all workers to complete.\n", TASK_TIMEOUT); fflush(stdout); @@ -673,15 +566,15 @@ class TestDriver { auto end = std::chrono::steady_clock::now() + std::chrono::seconds{TASK_TIMEOUT}; - while (doneCount < 4) { + while (doneCount < TestState::WORKER_COUNT) { // if ( DUNIT->getFailed() ) return; // sleep a bit.. std::this_thread::sleep_for(std::chrono::milliseconds{100}); doneCount = 0; for (uint32_t i = 1; i < 5; i++) { - int state = DUNIT->getWorkerState(WorkerId(i)); - if (state == WORKER_STATE_DONE) { - doneCount++; + int status = state->getWorkerState(i); + if (status == WORKER_STATE_DONE) { + ++doneCount; } } auto now = std::chrono::steady_clock::now(); @@ -695,14 +588,16 @@ class TestDriver { /** test to see that all the worker processes are still around, or throw a TestException so the driver doesn't get hung. */ void checkWorkerDeath() { - for (uint32_t i = 0; i < 4; i++) { + auto state = DUNIT->getState(); + for (uint32_t i = 0; i < TestState::WORKER_COUNT; i++) { if (!m_workers[i]->running()) { char msg[1000] = {0}; sprintf(msg, "Error: Worker %s terminated prematurely.", m_workers[i]->getWorkerId().getIdName()); LOG(msg); - DUNIT->setFailed(); - DUNIT->setMustQuit(); + + state->fail(); + state->terminate(); FAIL(msg); } } @@ -718,38 +613,39 @@ class TestWorker { explicit TestWorker(int id) : m_sId(id) { procWorkerId = new WorkerId(id); - dunit::Dunit::init(); - DUNIT->setWorkerState(m_sId, WORKER_STATE_READY); + dunit::Dunit::init(false); + DUNIT->getState()->setWorkerState(m_sId.getId(), WORKER_STATE_READY); + std::clog << "Started worker " << id << std::endl; } ~TestWorker() { - DUNIT->setWorkerState(m_sId, WORKER_STATE_DONE); + DUNIT->getState()->setWorkerState(m_sId.getId(), WORKER_STATE_DONE); dunit::Dunit::close(); } void begin() { + auto state = DUNIT->getState(); fprintf(stdout, "Worker %s started with pid %d\n", m_sId.getIdName(), boost::this_process::get_id()); fflush(stdout); - WorkerId workerZero(0); // consume tasks of this workers queue, only when it is his turn.. - while (!DUNIT->mustQuit()) { - if (DUNIT->getNextWorker() == m_sId.getId()) { + while (!state->terminated()) { + if (state->getNextWorker() == m_sId.getId()) { // set next worker to zero so I don't accidently run twice. - DUNIT->setNextWorker(workerZero); + state->setNextWorker(0); // do next task... Task *task = TaskQueues::getTask(m_sId); // perform task. if (task != nullptr) { - DUNIT->setWorkerState(m_sId, WORKER_STATE_TASK_ACTIVE); + state->setWorkerState(m_sId.getId(), WORKER_STATE_TASK_ACTIVE); try { task->doTask(); if (task->m_isHeapAllocated) { delete task; } fflush(stdout); - DUNIT->setWorkerState(m_sId, WORKER_STATE_TASK_COMPLETE); + state->setWorkerState(m_sId.getId(), WORKER_STATE_TASK_COMPLETE); } catch (TestException te) { if (task->m_isHeapAllocated) { delete task; @@ -773,9 +669,11 @@ class TestWorker { } void handleError() { - DUNIT->setFailed(); - DUNIT->setMustQuit(); - DUNIT->setWorkerState(m_sId, WORKER_STATE_TASK_COMPLETE); + auto state = DUNIT->getState(); + + state->fail(); + state->terminate(); + state->setWorkerState(m_sId.getId(), WORKER_STATE_TASK_COMPLETE); } }; @@ -859,27 +757,6 @@ int dmain(int argc, char *argv[]) { } } - // perf::NamingServiceThread nsvc( 12045 ); - // nsvc.activate( THR_NEW_LWP | THR_DETACHED | THR_DAEMON, 1 ); - // dunit::Dunit::init( true ); - // - // for ( int i = cmd_opts.opt_ind(); i < argc; i++ ) { - // char buf[1024], * name, * value; - // strcpy( buf, argv[i] ); - // name = &buf[0]; - // value = strchr( name, '=' ); - // if ( value != 0 ) { - // *value = '\0'; - // value++; - // // add to context - // dunit::globals()->rebind( name, value ); - // } - // } - - // record the coordinator pid if it wasn't passed to us on the command line. - // the TestDriver will pass this to the child processes. - // currently this is used for giving a unique per run id to shared - // resources. if (g_coordinatorPid == 0) { g_coordinatorPid = boost::this_process::get_id(); } @@ -922,249 +799,6 @@ int dmain(int argc, char *argv[]) { } /** entry point for test code modules to access the naming service. */ -NamingContext *globals() { return DUNIT->globals(); } +bip::managed_shared_memory &globals() { return DUNIT->getManagedState(); } } // namespace dunit - -namespace perf { - -TimeStamp::TimeStamp(int64_t msec) : m_msec(msec) {} - -TimeStamp::TimeStamp() { - m_msec = std::chrono::time_point_cast( - std::chrono::system_clock::now()) - .time_since_epoch() - .count(); -} - -TimeStamp::TimeStamp(const TimeStamp &other) : m_msec(other.m_msec) {} - -TimeStamp &TimeStamp::operator=(const TimeStamp &other) { - m_msec = other.m_msec; - return *this; -} - -TimeStamp::~TimeStamp() {} - -int64_t TimeStamp::msec() const { return m_msec; } - -void TimeStamp::msec(int64_t t) { m_msec = t; } - -Record::Record(std::string testName, int64_t ops, const TimeStamp &start, - const TimeStamp &stop) - : m_testName(testName), - m_operations(ops), - m_startTime(start), - m_stopTime(stop) {} - -Record::Record() - : m_testName(""), m_operations(0), m_startTime(0), m_stopTime(0) {} - -Record::Record(const Record &other) - : m_testName(other.m_testName), - m_operations(other.m_operations), - m_startTime(other.m_startTime), - m_stopTime(other.m_stopTime) {} - -Record &Record::operator=(const Record &other) { - m_testName = other.m_testName; - m_operations = other.m_operations; - m_startTime = other.m_startTime; - m_stopTime = other.m_stopTime; - return *this; -} - -void Record::write(apache::geode::client::DataOutput &output) { - output.writeString(m_testName); - output.writeInt(m_operations); - output.writeInt(m_startTime.msec()); - output.writeInt(m_stopTime.msec()); -} - -void Record::read(apache::geode::client::DataInput &input) { - m_testName = input.readString(); - m_operations = input.readInt64(); - m_startTime.msec(input.readInt64()); - m_stopTime.msec(input.readInt64()); -} - -Record::~Record() {} - -int Record::elapsed() { - return static_cast(m_stopTime.msec() - m_startTime.msec()); -} - -int Record::perSec() { - return static_cast(((static_cast(1000) * m_operations) / - static_cast(elapsed())) + - 0.5); -} - -std::string Record::asString() { - std::string tmp = m_testName; - char *buf = new char[1000]; - sprintf(buf, " -- %d ops/sec, ", perSec()); - tmp += buf; - sprintf(buf, "%d ops, ", static_cast(m_operations)); - tmp += buf; - sprintf(buf, "%d millis", elapsed()); - tmp += buf; - return tmp; -} - -PerfSuite::PerfSuite(const char *suiteName) : m_suiteName(suiteName) {} - -void PerfSuite::addRecord(std::string testName, int64_t ops, - const TimeStamp &start, const TimeStamp &stop) { - Record tmp(testName, ops, start, stop); - fprintf(stdout, "[PerfSuite] %s\n", tmp.asString().c_str()); - fflush(stdout); -} - -/** create a file in cwd, named "_results." */ -void PerfSuite::save() { - /* Currently having trouble with windows... not useful until the compare - function is written anyway... - - apache::geode::client::DataOutput output; - output.writeASCII( m_suiteName.c_str(), m_suiteName.length() ); - - char hname[100]; - ACE_OS::hostname( hname, 100 ); - std::string fname = m_suiteName + "_results." + hname; - - output.writeASCII( hname ); - - for( RecordMap::iterator iter = m_records.begin(); iter != m_records.end(); - iter++ ) { - Record record = (*iter).second; - record.write( output ); - } - fprintf( stdout, "[PerfSuite] finished serializing results.\n" ); - fflush( stdout ); - - fprintf( stdout, "[PerfSuite] writing results to %s\n", fname.c_str() ); - FILE* of = ACE_OS::fopen( fname.c_str(), "a+" ); - if ( of == 0 ) { - FAIL( "failed to open result file handle for perfSuite." ); - } - LOG( "opened perf output file for a+" ); - uint32_t len = 0; - char* buf = (char*) output.getBuffer( &len ); - LOG( "got buffer." ); - ACE_OS::fwrite( buf, len, 1, of ); - LOG( "wrote buffer" ); - ACE_OS::fflush( of ); - LOG( "flushed of" ); - ACE_OS::fclose( of ); - LOG( "closed of" ); - fprintf( stdout, "[PerfSuite] finished saving results file %s\n", - fname.c_str() ); - fflush( stdout ); - */ -} - -/** load data saved in $ENV{'baselines'} named "_baseline." */ -void PerfSuite::compare() { - /* - char hname[100] = {0}; - ACE_OS::hostname(hname, 100); - std::string fname = m_suiteName + "_baseline." + hname; - */ -} - -ThreadLauncher::ThreadLauncher(int thrCount, Thread &thr) - : m_thrCount(thrCount), - m_initSemaphore((-1 * thrCount) + 1), - m_startSemaphore(0), - m_stopSemaphore((-1 * thrCount) + 1), - m_cleanSemaphore(0), - m_termSemaphore((-1 * thrCount) + 1), - m_startTime(nullptr), - m_stopTime(nullptr), - m_threadDef(thr) { - m_threadDef.init(this); -} - -void ThreadLauncher::go() { -#ifdef WIN32 - int thrAttrs = THR_NEW_LWP | THR_JOINABLE; -#else - int thrAttrs = THR_NEW_LWP | THR_JOINABLE | THR_INHERIT_SCHED; -#endif - int res = m_threadDef.activate(thrAttrs, m_thrCount); - ASSERT(res == 0, "Failed to start threads properly"); - m_initSemaphore.acquire(); - LOG("[ThreadLauncher] all threads ready."); - m_startTime = new TimeStamp(); - m_startSemaphore.release(m_thrCount); - m_stopSemaphore.acquire(); - m_stopTime = new TimeStamp(); - m_cleanSemaphore.release(m_thrCount); - m_termSemaphore.acquire(); - LOG("[ThreadLauncher] joining threads."); - m_threadDef.wait(); - LOG("[ThreadLauncher] all threads stopped."); -} - -ThreadLauncher::~ThreadLauncher() { - if (m_startTime) { - delete m_startTime; - } - if (m_stopTime) { - delete m_stopTime; - } -} - -int Thread::svc() { - m_used = true; - int res = 0; - try { - setup(); // do per thread setup - } catch (...) { - LOG("[Thread] unknown exception thrown in setup()."); - res = 1; - } - m_launcher->initSemaphore().release(); - m_launcher->startSemaphore().acquire(); - try { - perftask(); // do measured iterations - } catch (...) { - LOG("[Thread] unknown exception thrown in perftask()."); - res = 2; - } - m_launcher->stopSemaphore().release(); - m_launcher->cleanSemaphore().acquire(); - try { - cleanup(); // cleanup after thread. - } catch (...) { - LOG("[Thread] unknown exception thrown in cleanup()"); - res = 3; - } - m_launcher->termSemaphore().release(); - return res; -} - -Semaphore::Semaphore(int count) : m_mutex(), m_cond(m_mutex), m_count(count) {} - -Semaphore::~Semaphore() {} - -void Semaphore::acquire(int t) { - ACE_Guard _guard(m_mutex); - - while (m_count < t) { - m_cond.wait(); - } - m_count -= t; -} - -void Semaphore::release(int t) { - ACE_Guard _guard(m_mutex); - - m_count += t; - if (m_count > 0) { - m_cond.broadcast(); - } -} - -} // namespace perf diff --git a/cppcache/integration-test/fw_dunit.hpp b/cppcache/integration-test/fw_dunit.hpp index aef17249e3..4eec804bba 100644 --- a/cppcache/integration-test/fw_dunit.hpp +++ b/cppcache/integration-test/fw_dunit.hpp @@ -117,6 +117,8 @@ END_TASK(validate) #include +#include + #include #include "TimeBomb.hpp" @@ -294,47 +296,7 @@ class Task { std::string typeName(); }; -/** Shared naming context for storing ints and strings between processes. - * To acquire the naming context, use the globals() function which - * returns a pointer for the naming context. - */ -class NamingContext { - public: - /** - * Share a string value, return -1 if there is a failure to store value, - * otherwise returns 0. - */ - virtual int rebind(const char* key, const char* value) = 0; - - /** - * Share an int value, return -1 if there is a failure to store value, - * otherwise returns 0. - */ - virtual int rebind(const char* key, int value) = 0; - - /** - * retreive a value by key, storing the result in the users buf. If the key - * is not found, the buf will contain the empty string "". Make sure the - * buffer is big enough to hold whatever has have bound. - */ - virtual std::string getValue(const std::string& key) = 0; - - /** - * return the value by key, as an int using the string to int conversion - * rules of atoi. - */ - virtual int getIntValue(const std::string& key) = 0; - - /** dump the entire context in LOG messages. */ - virtual void dump() = 0; - - virtual ~NamingContext() noexcept = default; -}; - -extern "C" { - -NamingContext* globals(); -} +extern boost::interprocess::managed_shared_memory& globals(); /** * Exception type to use when test framework has trouble or if ASSERT and FAIL @@ -370,7 +332,5 @@ int main(int argc, char* argv[]) { return dunit::dmain(argc, argv); } #endif // __DUNIT_NO_MAIN__ -#include "fw_perf.hpp" - namespace test {} // namespace test #endif // GEODE_INTEGRATION_TEST_FW_DUNIT_H_ diff --git a/cppcache/integration-test/fw_perf.hpp b/cppcache/integration-test/fw_perf.hpp deleted file mode 100644 index a952301808..0000000000 --- a/cppcache/integration-test/fw_perf.hpp +++ /dev/null @@ -1,218 +0,0 @@ -#pragma once - -#ifndef GEODE_INTEGRATION_TEST_FW_PERF_H_ -#define GEODE_INTEGRATION_TEST_FW_PERF_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - -fw_perf.hpp provides framework macros for measuring performance, -archiving the results, and comparing against previous archives. - -Steps for a performance suite: - -perf::PerfSuite suite( "SuiteName" ); - -const char* name = "my operation type/test description"; -perf::TimeStamp starttime; -... perform n operations. -perf::TimeStamp stoptime; -suite.addRecord( name, opcount, starttime, stoptime ); - -suite.save( ); // will save current results to _results. -suite.compare( ); // will compare against the file named -_baseline. - -If no baseline file for the host is available, then an error will occur, -recommending -that the results be analyzed for acceptability, and checked in as the hosts -baseline. - -If a baseline is found, a comparison report is generated, if the deviation is -beyond -established limits, a TestException will be thrown. - -*/ - -#include -#include - -#include -#include - -#include -#include -#include -//#include "Name_Handler.h" - -namespace perf { - -class Semaphore { - private: - ACE_Thread_Mutex m_mutex; - ACE_Condition m_cond; - volatile int m_count; - - public: - Semaphore() = delete; - explicit Semaphore(int count); - ~Semaphore(); - Semaphore(const Semaphore& other) = delete; - Semaphore& operator=(const Semaphore& other) = delete; - - void acquire(int t = 1); - void release(int t = 1); -}; - -class TimeStamp { - private: - int64_t m_msec; - - public: - TimeStamp(); - TimeStamp(const TimeStamp& other); - explicit TimeStamp(int64_t msec); - TimeStamp& operator=(const TimeStamp& other); - - ~TimeStamp(); - - int64_t msec() const; - void msec(int64_t t); -}; - -class Record { - private: - std::string m_testName; - int64_t m_operations; - TimeStamp m_startTime; - TimeStamp m_stopTime; - - public: - Record(std::string testName, int64_t ops, const TimeStamp& start, - const TimeStamp& stop); - - Record(); - - Record(const Record& other); - - Record& operator=(const Record& other); - - void write(apache::geode::client::DataOutput& output); - - void read(apache::geode::client::DataInput& input); - - int elapsed(); - int perSec(); - std::string asString(); - - ~Record(); -}; - -class PerfSuite { - private: - std::string m_suiteName; - - public: - explicit PerfSuite(const char* suiteName); - - void addRecord(std::string testName, int64_t ops, const TimeStamp& start, - const TimeStamp& stop); - - /** create a file in cwd, named "_results." */ - void save(); - - /** load data saved in $ENV{'baselines'} named "_baseline." - * A non-favorable comparison will throw an TestException. - */ - void compare(); -}; - -class Thread; - -class ThreadLauncher { - private: - int m_thrCount; - Semaphore m_initSemaphore; - Semaphore m_startSemaphore; - Semaphore m_stopSemaphore; - Semaphore m_cleanSemaphore; - Semaphore m_termSemaphore; - TimeStamp* m_startTime; - TimeStamp* m_stopTime; - Thread& m_threadDef; - - public: - ThreadLauncher(int thrCount, Thread& thr); - - void go(); - - ~ThreadLauncher(); - - Semaphore& initSemaphore() { return m_initSemaphore; } - - Semaphore& startSemaphore() { return m_startSemaphore; } - - Semaphore& stopSemaphore() { return m_stopSemaphore; } - - Semaphore& cleanSemaphore() { return m_cleanSemaphore; } - - Semaphore& termSemaphore() { return m_termSemaphore; } - - TimeStamp startTime() { return *m_startTime; } - - TimeStamp stopTime() { return *m_stopTime; } - - private: - ThreadLauncher& operator=(const ThreadLauncher& other); - ThreadLauncher(const ThreadLauncher& other); -}; - -class Thread : public ACE_Task_Base { - private: - ThreadLauncher* m_launcher; - bool m_used; - - public: - Thread() : ACE_Task_Base(), m_launcher(nullptr), m_used(false) {} - - // Unhide function to prevent SunPro Warnings - using ACE_Shared_Object::init; - void init(ThreadLauncher* l) { - ASSERT(!m_used, "Cannot reliably reuse Thread."); - m_launcher = l; - } - - ~Thread() noexcept override = default; - - /** called before measurement begins. override to do per thread setup. */ - virtual void setup() {} - - /** run during measurement */ - virtual void perftask() = 0; - - /** called after measurement to clean up what might have been setup in setup.. - */ - virtual void cleanup() {} - - int svc() override; -}; - -} // namespace perf - -#endif // GEODE_INTEGRATION_TEST_FW_PERF_H_ diff --git a/cppcache/integration-test/testDunit.cpp b/cppcache/integration-test/testDunit.cpp index ea26cb3d77..6674af4318 100644 --- a/cppcache/integration-test/testDunit.cpp +++ b/cppcache/integration-test/testDunit.cpp @@ -20,18 +20,23 @@ #include "fw_dunit.hpp" int getWorkerTest() { - return dunit::globals()->getIntValue("test_alive_workers"); + auto expected = dunit::globals().find("test_alive_workers").first; + ASSERT(expected != nullptr, "test_alive_workers is nullptr"); + return *expected; } // while this itself isn't thread/process safe, there shouldn't be concurrency // in a dunit test anyway. void incrementWorkerTest() { - dunit::globals()->rebind("test_alive_workers", getWorkerTest() + 1); + auto value = dunit::globals().find("test_alive_workers").first; + ASSERT(value != nullptr, "test_alive_workers is nullptr"); + ++*value; } DUNIT_TASK(s1p1, One) { - dunit::globals()->rebind("from1", 100); + dunit::globals().construct("test_alive_workers")(0); + dunit::globals().construct("from1")(100); LOG("bound from1 = 100"); incrementWorkerTest(); } @@ -39,7 +44,9 @@ END_TASK(One) DUNIT_TASK(s1p2, Two) { - ASSERT(dunit::globals()->getIntValue("from1") == 100, "expected 100"); + auto expected = dunit::globals().find("from1").first; + ASSERT(expected != nullptr, "from1 is nullptr"); + ASSERT(*expected == 100, "expected 100"); LOG("looked up from1, found 100"); incrementWorkerTest(); } @@ -77,6 +84,5 @@ DUNIT_TASK(s1p1, TestA) std::cout << "WorkerTest = " << getWorkerTest() << std::endl; ASSERT(getWorkerTest() == 8, "a previous worker must have failed undetected."); - dunit::globals()->dump(); } END_TASK(TestA) diff --git a/cppcache/integration-test/testFwPerf.cpp b/cppcache/integration-test/testFwPerf.cpp deleted file mode 100644 index fa75d3d7f0..0000000000 --- a/cppcache/integration-test/testFwPerf.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "fw_dunit.hpp" - -perf::PerfSuite perfSuite("FwPerf"); - -class LocalPutTask : public perf::Thread { - private: - public: - LocalPutTask() : Thread() {} - - void setup() override { - fprintf(stdout, "performed my setup...\n"); - fflush(stdout); - } - - void perftask() override { - std::this_thread::sleep_for(std::chrono::seconds(1)); - fprintf(stdout, "perffunc done.\n"); - fflush(stdout); - } - - void cleanup() override { - fprintf(stdout, "performed my cleanup...\n"); - fflush(stdout); - } -}; - -// all creates, no map growth, no replaces. -DUNIT_TASK(s1p1, LocalPut) - { - int iters = 1; - int threads = 4; - - LocalPutTask taskDef; - perf::ThreadLauncher tl(threads, taskDef); - tl.go(); - - perfSuite.addRecord(fwtest_Name, iters * threads, tl.startTime(), - tl.stopTime()); - } -END_TASK(x) - -DUNIT_TASK(s1p1, Finish) - { perfSuite.save(); } -END_TASK(x) diff --git a/cppcache/integration-test/testSpinLock.cpp b/cppcache/integration-test/testSpinLock.cpp index e5fb1aee3c..14c4efedb4 100644 --- a/cppcache/integration-test/testSpinLock.cpp +++ b/cppcache/integration-test/testSpinLock.cpp @@ -18,6 +18,7 @@ #include "fw_dunit.hpp" #include +#include #include #include @@ -26,6 +27,33 @@ namespace { // NOLINT(google-build-namespaces) +class semaphore { + public: + explicit semaphore(bool released) : released_(released) {} + + void release() { + std::lock_guard lock(mutex_); + released_ = true; + cv_.notify_one(); + } + + void acquire() { + std::unique_lock lock(mutex_); + cv_.wait(lock, [this]() { return released_; }); + released_ = false; + } + + semaphore& operator=(const semaphore& other) { + released_ = other.released_; + return *this; + } + + protected: + bool released_; + std::mutex mutex_; + std::condition_variable cv_; +}; + using apache::geode::util::concurrent::spinlock_mutex; DUNIT_TASK(s1p1, Basic) @@ -35,9 +63,9 @@ DUNIT_TASK(s1p1, Basic) } END_TASK(Basic) -perf::Semaphore *triggerA; -perf::Semaphore *triggerB; -perf::Semaphore *triggerM; +semaphore triggerA{0}; +semaphore triggerB{0}; +semaphore triggerM{0}; spinlock_mutex lock; std::chrono::steady_clock::time_point btime; @@ -50,8 +78,8 @@ class ThreadA : public ACE_Task_Base { { std::lock_guard lk(lock); LOG("ThreadA: Acquired lock x."); - triggerM->release(); - triggerA->acquire(); + triggerM.release(); + triggerA.acquire(); } LOG("ThreadA: Released lock."); return 0; @@ -63,12 +91,12 @@ class ThreadB : public ACE_Task_Base { ThreadB() : ACE_Task_Base() {} int svc() override { - triggerB->acquire(); + triggerB.acquire(); { std::lock_guard lk(lock); btime = std::chrono::steady_clock::now(); LOG("ThreadB: Acquired lock."); - triggerM->release(); + triggerM.release(); } return 0; } @@ -76,26 +104,26 @@ class ThreadB : public ACE_Task_Base { DUNIT_TASK(s1p1, TwoThreads) { - triggerA = new perf::Semaphore(0); - triggerB = new perf::Semaphore(0); - triggerM = new perf::Semaphore(0); + triggerA = semaphore{0}; + triggerB = semaphore{0}; + triggerM = semaphore{0}; - ThreadA *threadA = new ThreadA(); - ThreadB *threadB = new ThreadB(); + ThreadA* threadA = new ThreadA(); + ThreadB* threadB = new ThreadB(); threadA->activate(); threadB->activate(); // A runs, locks the spinlock, and triggers me. B is idle. - triggerM->acquire(); + triggerM.acquire(); // A is now idle, but holds lock. Tell B to acquire the lock auto stime = std::chrono::steady_clock::now(); - triggerB->release(); + triggerB.release(); SLEEP(5000); // B will be stuck until we tell A to release it. - triggerA->release(); + triggerA.release(); // wait until B tells us it has acquired the lock. - triggerM->acquire(); + triggerM.acquire(); // Now diff btime (when B acquired the lock) and stime to see that it // took longer than the 5000 seconds before A released it. diff --git a/cppcache/integration-test/testThinClientBigValue.cpp b/cppcache/integration-test/testThinClientBigValue.cpp index 89e3ed2cfe..7a76b435e1 100644 --- a/cppcache/integration-test/testThinClientBigValue.cpp +++ b/cppcache/integration-test/testThinClientBigValue.cpp @@ -142,7 +142,8 @@ DUNIT_TASK(CLIENT1, puts) putSize(regPtr, keybuf, i); expectEntries++; } - dunit::globals()->rebind("entriesToExpect", expectEntries); + + dunit::globals().find_or_construct("entriesToExpect")(expectEntries); LOG("Finished putting entries."); } END_TASK(puts) @@ -151,7 +152,6 @@ DUNIT_TASK(CLIENT2, VerifyPuts) { auto regPtr = getHelper()->getRegion(regionNames[0]); // region should already have n entries... - dunit::globals()->getIntValue("entriesToExpect"); for (int i = 0; i <= MAX_PAYLOAD; grow(&i)) { char keybuf[100]; @@ -184,7 +184,8 @@ DUNIT_TASK(CLIENT1, ManyPuts) regPtr->put(keybuf, valbuf); expectEntries++; } - dunit::globals()->rebind("entriesToExpect", expectEntries); + + dunit::globals().find_or_construct("entriesToExpect")(expectEntries); LOG("Finished putting entries."); } END_TASK(ManyPuts) @@ -193,10 +194,11 @@ DUNIT_TASK(CLIENT2, VerifyManyPuts) { auto regPtr = getHelper()->getRegion(regionNames[0]); // region should already have n entries... - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); char keybuf[100]; - for (int index = 0; index < entriesExpected; ++index) { + for (int index = 0; index < *entriesExpected; ++index) { sprintf(keybuf, "keys1%010d", index); auto valPtr = std::dynamic_pointer_cast(regPtr->get(keybuf)); @@ -220,7 +222,8 @@ DUNIT_TASK(CLIENT1, UpdateManyPuts) regPtr->put(keybuf, valbuf); expectEntries++; } - dunit::globals()->rebind("entriesToExpect", expectEntries); + + dunit::globals().find_or_construct("entriesToExpect")(expectEntries); LOG("Finished putting entries."); } END_TASK(UpdateManyPuts) @@ -229,10 +232,11 @@ DUNIT_TASK(CLIENT2, VerifyOldManyPuts) { // region should given old entries from cache auto regPtr = getHelper()->getRegion(regionNames[0]); - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); char keybuf[100]; - for (int index = 0; index < entriesExpected; ++index) { + for (int index = 0; index < *entriesExpected; ++index) { sprintf(keybuf, "keys1%010d", index); auto valPtr = std::dynamic_pointer_cast(regPtr->get(keybuf)); @@ -248,12 +252,14 @@ DUNIT_TASK(CLIENT2, VerifyUpdatedManyPuts) { auto regPtr = getHelper()->getRegion(regionNames[0]); // region should already have n entries... - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); + // invalidate the region to force getting new values regPtr->localInvalidateRegion(); char keybuf[100]; - for (int index = 0; index < entriesExpected; ++index) { + for (int index = 0; index < *entriesExpected; ++index) { sprintf(keybuf, "keys1%010d", index); auto valPtr = std::dynamic_pointer_cast(regPtr->get(keybuf)); @@ -269,19 +275,21 @@ DUNIT_TASK(CLIENT2, VerifyUpdatedManyPutsGetAll) { auto regPtr = getHelper()->getRegion(regionNames[0]); // region should already have n entries... - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); + // invalidate the region to force getting new values regPtr->localInvalidateRegion(); std::vector> vec; char keybuf[100]; - for (int index = 0; index < entriesExpected; ++index) { + for (int index = 0; index < *entriesExpected; ++index) { sprintf(keybuf, "keys1%010d", index); vec.push_back(CacheableKey::create(keybuf)); } regPtr->getAll(vec); LOG("On client getAll for entries completed."); - for (int index = 0; index < entriesExpected; ++index) { + for (int index = 0; index < *entriesExpected; ++index) { sprintf(keybuf, "keys1%010d", index); auto valPtr = std::dynamic_pointer_cast(regPtr->get(keybuf)); @@ -305,7 +313,8 @@ DUNIT_TASK(CLIENT1, UpdateManyPutsInt64) regPtr->put(CacheableInt64::create(key), valbuf); expectEntries++; } - dunit::globals()->rebind("entriesToExpect", expectEntries); + + dunit::globals().find_or_construct("entriesToExpect")(expectEntries); LOG("Finished putting int64 entries."); } END_TASK(UpdateManyPutsInt64) @@ -313,9 +322,10 @@ END_TASK(UpdateManyPutsInt64) DUNIT_TASK(CLIENT2, VerifyManyPutsInt64) { auto regPtr = getHelper()->getRegion(regionNames[0]); - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); - for (int64_t index = 0; index < entriesExpected; ++index) { + for (int64_t index = 0; index < *entriesExpected; ++index) { int64_t key = index * index * index; // auto valPtr = // std::dynamic_pointer_cast(regPtr->get(key)); @@ -326,7 +336,7 @@ DUNIT_TASK(CLIENT2, VerifyManyPutsInt64) } LOG("On client Found all int64 entries with " "correct size via get."); - for (int64_t index = 0; index < entriesExpected; ++index) { + for (int64_t index = 0; index < *entriesExpected; ++index) { // auto key = // CacheableKey::create(CacheableInt64::create(index // * index * index)); @@ -347,19 +357,21 @@ DUNIT_TASK(CLIENT2, VerifyUpdatedManyPutsInt64GetAll) { auto regPtr = getHelper()->getRegion(regionNames[0]); // region should already have n entries... - int entriesExpected = dunit::globals()->getIntValue("entriesToExpect"); + auto entriesExpected = dunit::globals().find("entriesToExpect").first; + ASSERT(entriesExpected != nullptr, "entriesExpected is null"); + // invalidate the region to force getting new // values regPtr->localInvalidateRegion(); std::vector> vec; - for (int64_t index = 0; index < entriesExpected; ++index) { + for (int64_t index = 0; index < *entriesExpected; ++index) { int64_t key = index * index * index; vec.push_back(CacheableInt64::create(key)); } const auto valuesMap = regPtr->getAll(vec); LOG("On client getAll for int64 entries completed."); - for (int32_t index = 0; index < entriesExpected; ++index) { + for (int32_t index = 0; index < *entriesExpected; ++index) { auto key = vec[index]; ASSERT(regPtr->containsKey(key), "must contain key"); auto entry = regPtr->getEntry(key); diff --git a/tests/cpp/fwklib/CMakeLists.txt b/tests/cpp/fwklib/CMakeLists.txt index 783d38dad8..6a671b20a9 100644 --- a/tests/cpp/fwklib/CMakeLists.txt +++ b/tests/cpp/fwklib/CMakeLists.txt @@ -16,29 +16,8 @@ project(framework LANGUAGES CXX) add_library(framework STATIC - FwkBB.hpp - FwkBBClient.cpp - FwkBBClient.hpp - FwkBBServer.cpp - FwkBBServer.hpp - FwkException.hpp - FwkExport.hpp FwkLog.cpp - FwkLog.hpp - FwkStrCvt.cpp - FwkStrCvt.hpp GsRandom.cpp - GsRandom.hpp - IpcHandler.cpp - IpcHandler.hpp - Service.cpp - Service.hpp - TcpIpc.cpp - TcpIpc.hpp - TimeBomb.cpp - TimeBomb.hpp - UDPIpc.cpp - UDPIpc.hpp ) set_target_properties(framework PROPERTIES diff --git a/tests/cpp/fwklib/FwkBB.hpp b/tests/cpp/fwklib/FwkBB.hpp deleted file mode 100644 index b13eba3857..0000000000 --- a/tests/cpp/fwklib/FwkBB.hpp +++ /dev/null @@ -1,233 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_FWKBB_H_ -#define GEODE_FWKLIB_FWKBB_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @file FwkBB.hpp - * @since 1.0 - * @version 1.0 - * @see - */ - -#include -#include -#include -#include - -#include - -// ---------------------------------------------------------------------------- - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -// ---------------------------------------------------------------------------- - -// #define BB_START_TAG "" -#define BB_ID_TAG "" -#define BB_COMMAND_TAG "" -#define BB_PARAMETER_TAG "

" -#define BB_RESULT_TAG "" -// #define BB_END_TAG "" - -#define BB_CLEAR_COMMAND "C" //"clear" -#define BB_DUMP_COMMAND "d" //"dump" -#define BB_GET_COMMAND "g" //"get" -#define BB_SET_COMMAND "s" //"set" -#define BB_ADD_COMMAND "A" //"add" -#define BB_SUBTRACT_COMMAND "S" //"subtract" -#define BB_INCREMENT_COMMAND "I" //"increment" -#define BB_DECREMENT_COMMAND "D" //"decrement" -#define BB_ZERO_COMMAND "z" //"zero" -#define BB_SET_IF_GREATER_COMMAND "G" //"setIfGreater" -#define BB_SET_IF_LESS_COMMAND "L" //"setIfLess" -#define BB_SET_ACK_COMMAND "a" //"ack" - -// ---------------------------------------------------------------------------- - -/** @class FwkBBMessage - * @brief Framework BB message - * - * Message stream format - * @verbatim - IIIICCCC

PPPP

PPPP

PPPPRRRR - - start tag of message - id of operation - command value -

parameter value - result value - end tag of message - @endverbatim - */ -class FwkBBMessage { - public: - explicit FwkBBMessage(const char* cmd) : m_cmd(cmd) {} - FwkBBMessage() {} - virtual ~FwkBBMessage() {} - - /** @brief clear message data - */ - void clear() { - m_parameterVector.clear(); - m_id.clear(); - m_cmd.clear(); - m_result.clear(); - } - - /** @brief pass to data to parse onReceive message - * @param data string of data - * @retval true = Success, false = Failed - */ - void fromMessageStream(std::string data) { - // FWKINFO( "FwkBBMessage::fromMessageStream: " << data ); - char* str = const_cast(data.c_str()); - char* tag = strstr(str, BB_ID_TAG); - if (!tag) { - FWKEXCEPTION("Invalid BB message: " << data); - } - tag += 3; - int32_t len = static_cast(strcspn(tag, "<")); - std::string id(tag, len); - setId(id); - - tag = strstr(str, BB_COMMAND_TAG); - if (!tag) { - FWKEXCEPTION("Invalid BB message: " << data); - } - tag += 3; - len = static_cast(strcspn(tag, "<")); - std::string cmd(tag, len); - setCommand(cmd); - - tag = strstr(str, BB_RESULT_TAG); - if (tag) { - tag += 3; - len = static_cast(strcspn(tag, "<")); - std::string result(tag, len); - setResult(result); - } - - tag = strstr(str, BB_PARAMETER_TAG); - while (tag) { - tag += 3; - len = static_cast(strcspn(tag, "<")); - std::string param(tag, len); - addParameter(param); - tag = strstr(tag, BB_PARAMETER_TAG); - } - } - - /** @brief get data stream to send - * @retval true = Success, false = Failed - */ - std::string& toMessageStream() { - m_stream.clear(); - std::ostringstream osMessage; - if (m_id.empty()) { - FWKEXCEPTION("Invalid BB Message, id not set."); - } - if (m_cmd.empty()) { - FWKEXCEPTION("Invalid BB Message, command not set."); - } - - osMessage << BB_ID_TAG << m_id << BB_COMMAND_TAG << m_cmd; - if (m_parameterVector.size() > 0) { - std::vector::iterator it = m_parameterVector.begin(); - while (it != m_parameterVector.end()) { - osMessage << BB_PARAMETER_TAG << *it; - it++; - } - } - if (!m_result.empty()) osMessage << BB_RESULT_TAG << m_result; - - m_stream.append(osMessage.str()); - return m_stream; - } - - /** @brief set Id of message - * @param id id of message - */ - void setId(std::string id) { m_id = id; } - - /** @brief set command of message - * @param cmd command of message - */ - void setCommand(std::string cmd) { m_cmd = cmd; } - - /** @brief set result of message - * @param result result of message - */ - void setResult(std::string result) { m_result = result; } - - /** @brief add parameter value to message - * @param parameter parameter of message - */ - void addParameter(std::string parameter) { - m_parameterVector.push_back(parameter); - } - - /** @brief get id of message - * @retval id of message - */ - std::string getId() { return m_id; } - - /** @brief get command of message - * @retval command of message - */ - std::string getCommand() { return m_cmd; } - char getCmdChar() { return m_cmd.at(0); } - - /** @brief get result of message - * @retval result of message - */ - std::string getResult() { return m_result; } - - /** @brief get parameter of message - * @retval parameter of message - */ - std::string getParameter(size_t index) { - std::string value; - if (index < m_parameterVector.size()) value = m_parameterVector[index]; - - return value; - } - - private: - std::vector m_parameterVector; - std::string m_id; - std::string m_cmd; - std::string m_result; - std::string m_stream; -}; - -// ---------------------------------------------------------------------------- - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -// ---------------------------------------------------------------------------- - -#endif // GEODE_FWKLIB_FWKBB_H_ diff --git a/tests/cpp/fwklib/FwkBBClient.cpp b/tests/cpp/fwklib/FwkBBClient.cpp deleted file mode 100644 index 644cbdf349..0000000000 --- a/tests/cpp/fwklib/FwkBBClient.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @file FwkBBClient.cpp - * @since 1.0 - * @version 1.0 - * @see - */ - -#include "FwkBBClient.hpp" - -#include -#include - -#include "FwkLog.hpp" -#include "FwkStrCvt.hpp" - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -void FwkBBClient::sendToServer(FwkBBMessage& message) { - message.setId(FwkStrCvt(getNewMessageId()).toString()); - std::string msg = message.toMessageStream(); - if (msg.empty()) { - FWKEXCEPTION("Empty message in FwkBBClient::sendToServer"); - } - - int32_t tries = 5; - bool done = false; - ACE_Time_Value timeout(CLIENT_WAIT_TIME_FOR_REPLY); - int32_t sCnt = 0; - int32_t rCnt = 0; - int32_t nrCnt = 0; - int32_t eCnt = 0; - while (!done && (tries-- > 0)) { - try { - UDPMessage udpMsg(msg); - udpMsg.setSender(m_client.getServer()); - if (!udpMsg.send(m_client.getConn())) { - sCnt++; - FWKEXCEPTION("Send failed in FwkBBClient::sendToServer"); - } - if (!udpMsg.receiveFrom(m_client.getConn(), &timeout)) { - rCnt++; - FWKEXCEPTION("Receive failed in FwkBBClient::sendToServer"); - } - if (udpMsg.length() == 0) { - nrCnt++; - FWKEXCEPTION("No Reply from server in FwkBBClient::sendToServer"); - } - message.fromMessageStream(udpMsg.what()); - m_result.clear(); - m_result = message.getResult(); - done = true; - } catch (FwkException& /* ex */) { - eCnt++; - // FWKSEVERE( "Caught exception in FwkBBClient::sendToServer: " << - // ex.what() << ", tried to send: " << msg.substr( 0, 50 ) ); - } - } - if (!done) { - FWKSEVERE("FwkBBClient::sendToServer: FAILED, ( " - << eCnt << ", " << sCnt << ", " << rCnt << ", " << nrCnt - << " ) tried to send: " << msg.substr(0, 50)); - } -} - -// ---------------------------------------------------------------------------- - -std::string FwkBBClient::dump() { - FwkBBMessage message(BB_DUMP_COMMAND); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return m_result; -} - -// ---------------------------------------------------------------------------- - -std::string FwkBBClient::dump(const std::string& BBName) { - FwkBBMessage message(BB_DUMP_COMMAND); - message.addParameter(BBName); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return m_result; -} - -// ---------------------------------------------------------------------------- - -void FwkBBClient::clear(const std::string& BBName) { - FwkBBMessage message(BB_CLEAR_COMMAND); - message.addParameter(BBName); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } -} - -// ---------------------------------------------------------------------------- - -std::string FwkBBClient::getString(const std::string& BBName, - const std::string& Key) { - FwkBBMessage message(BB_GET_COMMAND); - message.addParameter("key"); - message.addParameter(BBName); - message.addParameter(Key); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return m_result; -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::get(const std::string& BBName, const std::string& Key) { - FwkBBMessage message(BB_GET_COMMAND); - message.addParameter("counter"); - message.addParameter(BBName); - message.addParameter(Key); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -void FwkBBClient::set(const std::string& BBName, const std::string& Key, - const std::string& Value) { - FwkBBMessage message(BB_SET_COMMAND); - message.addParameter("key"); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(Value); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } -} - -// ---------------------------------------------------------------------------- - -void FwkBBClient::set(const std::string& BBName, const std::string& Key, - const int64_t Value) { - FwkBBMessage message(BB_SET_COMMAND); - message.addParameter("counter"); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(FwkStrCvt(Value).toString()); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::add(const std::string& BBName, const std::string& Key, - const int64_t Value) { - FwkBBMessage message(BB_ADD_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(FwkStrCvt(Value).toString()); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::subtract(const std::string& BBName, const std::string& Key, - const int64_t Value) { - FwkBBMessage message(BB_SUBTRACT_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(FwkStrCvt(Value).toString()); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::increment(const std::string& BBName, - const std::string& Key) { - FwkBBMessage message(BB_INCREMENT_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::decrement(const std::string& BBName, - const std::string& Key) { - FwkBBMessage message(BB_DECREMENT_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -void FwkBBClient::zero(const std::string& BBName, const std::string& Key) { - FwkBBMessage message(BB_ZERO_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::setIfGreater(const std::string& BBName, - const std::string& Key, const int64_t Value) { - FwkBBMessage message(BB_SET_IF_GREATER_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(FwkStrCvt(Value).toString()); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBClient::setIfLess(const std::string& BBName, - const std::string& Key, const int64_t Value) { - FwkBBMessage message(BB_SET_IF_LESS_COMMAND); - message.addParameter(BBName); - message.addParameter(Key); - message.addParameter(FwkStrCvt(Value).toString()); - try { - sendToServer(message); - } catch (FwkException& ex) { - ex.what(); - } - return FwkStrCvt::toInt64(m_result.c_str()); -} - -// ---------------------------------------------------------------------------- - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/FwkBBClient.hpp b/tests/cpp/fwklib/FwkBBClient.hpp deleted file mode 100644 index 4084097b53..0000000000 --- a/tests/cpp/fwklib/FwkBBClient.hpp +++ /dev/null @@ -1,192 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_FWKBBCLIENT_H_ -#define GEODE_FWKLIB_FWKBBCLIENT_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @file FwkBBClient.hpp - * @since 1.0 - * @version 1.0 - * @see - */ - -#include - -#include "FwkBB.hpp" -#include "UDPIpc.hpp" - -// ---------------------------------------------------------------------------- -// Some widely used BBs and counters - -static std::string CLIENTBB("CLIENTBB"); -static std::string CLIENTCOUNT("ClientCount"); - -// ---------------------------------------------------------------------------- - -#define CLIENT_WAIT_TIME_FOR_REPLY 5 // seconds - -// ---------------------------------------------------------------------------- - -namespace apache { -namespace geode { -namespace client { -namespace testframework { -/** @class FwkBBClient - * @brief Framework BB client - */ -class FwkBBClient { - public: - explicit FwkBBClient(std::string serverAddr) - : m_client(serverAddr), m_messageId(0) {} - - ~FwkBBClient() {} - - /** @brief dump all data - * @retval result of dump - */ - std::string dump(); - - /** @brief dump BB data - * @param BBName name of BB - * @retval result of dump - */ - std::string dump(const std::string& BBName); - - /** @brief clear BB data - * @param BBName name of BB - */ - void clear(const std::string& BBName); - - /** @brief get BB key value - * @param BBName name of BB - * @param Key name of Key - * @retval value - */ - std::string getString(const std::string& BBName, const std::string& Key); - - /** @brief get BB counter value - * @param BBName name of BB - * @param Key name of counter - * @retval value of counter - */ - int64_t get(const std::string& BBName, const std::string& Key); - - /** @brief set BB key value - * @param BBName name of BB - * @param Key name of key - * @param Value value to set - */ - void set(const std::string& BBName, const std::string& Key, - const std::string& Value); - - /** @brief set BB counter value - * @param BBName name of BB - * @param Key name of counter - * @param Value value to add to counter - * @retval value of counter - */ - void set(const std::string& BBName, const std::string& Key, - const int64_t Value); - - /** @brief add BB counter value - * @param BBName name of BB - * @param Key name of counter - * @param Value value to add to counter - * @retval value after add - */ - int64_t add(const std::string& BBName, const std::string& Key, - const int64_t Value); - - /** @brief subtract BB counter value - * @param BBName name of BB - * @param Key name of counter - * @param Value value to subtract from counter - * @retval value after subtract - */ - int64_t subtract(const std::string& BBName, const std::string& Key, - const int64_t Value); - - /** @brief increment BB counter value by 1 - * @param BBName name of BB - * @param Key name of counter - * @retval value after increment - */ - int64_t increment(const std::string& BBName, const std::string& Key); - - /** @brief decrement BB counter value by 1 - * @param BBName name of BB - * @param Key name of counter - * @retval value after decrement - */ - int64_t decrement(const std::string& BBName, const std::string& Key); - - /** @brief zero BB counter value to 0 - * @param BBName name of BB - * @param Key name of counter - */ - void zero(const std::string& BBName, const std::string& Key); - - /** @brief setIfGreater BB counter value is greater - * @param BBName name of BB - * @param Key name of counter - * @param Value value to set - * @retval value after setIfGreater - */ - int64_t setIfGreater(const std::string& BBName, const std::string& Key, - const int64_t Value); - - /** @brief setIfLess BB counter value is less - * @param BBName name of BB - * @param Key name of counter - * @param Value value to set - * @retval value after setIfLess - */ - int64_t setIfLess(const std::string& BBName, const std::string& Key, - const int64_t Value); - - private: - /** @brief get new message id - */ - uint32_t getNewMessageId() { return ++m_messageId; } - - /** @brief get current message id - */ - uint32_t getCurrentMessageId() { return m_messageId; } - - /** @brief send a message to server - * @param message message to send - * @retval true = Success, false = Failed - */ - void sendToServer(FwkBBMessage& message); - - private: - UDPMessageClient m_client; - std::string m_result; - uint32_t m_messageId; -}; - -// ---------------------------------------------------------------------------- - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_FWKBBCLIENT_H_ diff --git a/tests/cpp/fwklib/FwkBBServer.cpp b/tests/cpp/fwklib/FwkBBServer.cpp deleted file mode 100644 index 0a7241b5a9..0000000000 --- a/tests/cpp/fwklib/FwkBBServer.cpp +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "FwkBBServer.hpp" - -#include - -#include "FwkLog.hpp" -#include "FwkStrCvt.hpp" -#include "UDPIpc.hpp" - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -FwkBBServer::~FwkBBServer() { - // stop(); - clear(); -} - -//// -///---------------------------------------------------------------------------- -// -// void FwkBBServer::stop() { -// m_farm->stopThreads(); -// clear(); -// delete m_farm; -//} -// -//// -///---------------------------------------------------------------------------- -// -// void FwkBBServer::start( uint32_t port ) { -// UDPMessageQueues * shared = new UDPMessageQueues( "BlackBoard" ); -// -// m_farm = new Service( 10 ); -// -// Receiver recv( shared, port ); -// BBProcessor serv( shared, this ); -// Responder resp( shared, port ); -// -// uint32_t thrds = m_farm->runThreaded( &recv, 5 ); -// thrds = m_farm->runThreaded( &resp, 4 ); -// thrds = m_farm->runThreaded( &serv, 1 ); -//} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::clear() { - m_nameKeyMap.clear(); - m_nameCounterMap.clear(); -} - -// ---------------------------------------------------------------------------- -// IIIIdump -// bool dump(std::string& result); -// IIIIdump

BBName -// bool dump(const char* BBName, std::string& result) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onDump(FwkBBMessage& message, FwkBBMessage& reply) { - std::string sParameter1 = message.getParameter(0); - - std::string response; - if (sParameter1.size()) { - dump(sParameter1, response); - } else { // dump all - dump(response); - } - reply.setResult(response); -} - -void FwkBBServer::onClearBB(FwkBBMessage& message) { - std::string sParameter1 = message.getParameter(0); - - if (sParameter1.size()) clearBB(sParameter1); -} - -// ---------------------------------------------------------------------------- -// IIIIget

key

BBName

Key -// bool get(const char* BBName, const char* Key, std::string& result) -// IIIIget

counter

BBName

Key -// bool get(const char* BBName, const char* Key, -// int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onGet(FwkBBMessage& message, FwkBBMessage& reply) { - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size()) { - if (sParameter1 == "key") { - reply.setResult(getString(sParameter2, sParameter3)); - } else if (sParameter1 == "counter") { - int64_t result = get(sParameter2, sParameter3); - reply.setResult(FwkStrCvt(result).toString()); - } - } -} - -// ---------------------------------------------------------------------------- -// IIIIset

key

BBName

Key

pszValue -// bool set(const char* BBName, const char* Key, const char* pszValue) -// IIIIset

counter

BBName

Key

Value -// bool set(const char* BBName, const char* Key, -// const int64_t Value) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onSet(FwkBBMessage& message) { - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - std::string sParameter4 = message.getParameter(3); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size() && - sParameter4.size()) { - if (sParameter1 == "key") { - set(sParameter2, sParameter3, sParameter4); - } else if (sParameter1 == "counter") { - int64_t Value = FwkStrCvt(sParameter4.c_str()).toInt64(); - set(sParameter2, sParameter3, Value); - } - } -} - -// ---------------------------------------------------------------------------- -// IIIIadd

BBName

Key

Value -// bool add(const char* BBName, const char* Key, -// const int64_t Value, int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onAdd(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size()) { - int64_t Value = FwkStrCvt(sParameter3).toInt64(); - result = add(sParameter1, sParameter2, Value); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- -// IIIIsubtract

BBName

Key

Value -// bool subtract(const char* BBName, const char* Key, -// const int64_t Value, int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onSubtract(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size()) { - int64_t Value = FwkStrCvt(sParameter3).toInt64(); - result = subtract(sParameter1, sParameter2, Value); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- -// IIIIincrement

BBName

Key

Value -// bool increment(const char* BBName, const char* Key, -// int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onIncrement(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - - if (sParameter1.size() && sParameter2.size()) { - result = increment(sParameter1, sParameter2); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- -// IIIIdecrement

BBName

Key

Value -// bool decrement(const char* BBName, const char* Key, -// int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onDecrement(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - - if (sParameter1.size() && sParameter2.size()) { - result = decrement(sParameter1, sParameter2); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- -// IIIIzero

BBName

Key -// bool zero(const char* BBName, const char* Key) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onZero(FwkBBMessage& message) { - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - - if (sParameter1.size() && sParameter2.size()) zero(sParameter1, sParameter2); -} - -// ---------------------------------------------------------------------------- -// IIIIsetIfGreater

BBName

Key

Value -// bool setIfGreater(const char* BBName, -// const char* Key, const int64_t Value, int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onSetIfGreater(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size()) { - int64_t Value = FwkStrCvt(sParameter3).toInt64(); - result = setIfGreater(sParameter1, sParameter2, Value); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- -// IIIIsetIfLess

BBName

Key

Value -// bool setIfLess(const char* BBName, -// const char* Key, const int64_t Value, int64_t* piResult) -// ---------------------------------------------------------------------------- - -void FwkBBServer::onSetIfLess(FwkBBMessage& message, FwkBBMessage& reply) { - int64_t result = 0; - std::string sParameter1 = message.getParameter(0); - std::string sParameter2 = message.getParameter(1); - std::string sParameter3 = message.getParameter(2); - - if (sParameter1.size() && sParameter2.size() && sParameter3.size()) { - int64_t Value = FwkStrCvt(sParameter3).toInt64(); - result = setIfLess(sParameter1, sParameter2, Value); - } - - reply.setResult(FwkStrCvt(result).toString()); -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::dump(std::string& result) { - // set of all bb's - std::set bbSet; - - // get all bbNames in nameKeyMap - NameKeyMap::iterator nameKeyIt = m_nameKeyMap.begin(); - while (nameKeyIt != m_nameKeyMap.end()) { - bbSet.insert(nameKeyIt->first.getName()); - nameKeyIt++; - } - - // get all bbnames in nameCounterMap - NameCounterMap::iterator nameCounterIt = m_nameCounterMap.begin(); - while (nameCounterIt != m_nameCounterMap.end()) { - bbSet.insert(nameCounterIt->first.getName()); - nameCounterIt++; - } - - // dump all bb's - std::set::iterator bbIt = bbSet.begin(); - while (bbIt != bbSet.end()) { - std::string bb(*bbIt); - std::string response; - dump(bb, response); - result += response; - bbIt++; - } -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::dump(const std::string& BBName, std::string& result) { - result = "\nBlack Board: "; - result += BBName; - result += "\n"; - - // get keys - NameKeyMap::iterator nameKeyIt = m_nameKeyMap.begin(); - - while (nameKeyIt != m_nameKeyMap.end()) { - if (nameKeyIt->first.getName() == BBName) { - result += " Key: "; - result += nameKeyIt->first.getKey(); - result += " Value: "; - result += nameKeyIt->second; - result += "\n"; - } - - nameKeyIt++; - } - - // get counters - NameCounterMap::iterator nameCounterIt = m_nameCounterMap.begin(); - - while (nameCounterIt != m_nameCounterMap.end()) { - if (nameCounterIt->first.getName() == BBName) { - result += " Counter: "; - result += nameCounterIt->first.getKey(); - result += " Value: "; - result += FwkStrCvt(nameCounterIt->second).toString(); - result += "\n"; - } - - nameCounterIt++; - } -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::clearBB(const std::string& BBName) { - NameKeyMap::iterator nameKeyIt = m_nameKeyMap.begin(); - NameKeyMap::iterator prevK = m_nameKeyMap.begin(); - while (nameKeyIt != m_nameKeyMap.end()) { - // FWKINFO( "Looking at: " << nameKeyIt->first.getName() << " Key: " << - // nameKeyIt->first.getKey() ); - if (nameKeyIt->first.getName() == BBName) { - // FWKINFO( "Calling erase." ); - m_nameKeyMap.erase(nameKeyIt); - nameKeyIt = prevK; - } else { - prevK = nameKeyIt; - } - nameKeyIt++; - } - - NameCounterMap::iterator nameCounterIt = m_nameCounterMap.begin(); - NameCounterMap::iterator prevC = m_nameCounterMap.begin(); - while (nameCounterIt != m_nameCounterMap.end()) { - // FWKINFO( "Looking at: " << nameCounterIt->first.getName() << " - // Counter: " << nameCounterIt->first.getKey() ); - if (nameCounterIt->first.getName() == BBName) { - // FWKINFO( "Calling erase." ); - m_nameCounterMap.erase(nameCounterIt); - nameCounterIt = prevC; - } else { - prevC = nameCounterIt; - } - nameCounterIt++; - } -} - -// ---------------------------------------------------------------------------- - -std::string FwkBBServer::getString(const std::string& BBName, - const std::string& Key) { - std::string result; - NameKeyPair nameKeyPair(BBName, Key); - - NameKeyMap::iterator it = m_nameKeyMap.find(nameKeyPair); - if (it != m_nameKeyMap.end()) { // if found - result = it->second; - } - - return result; -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::get(const std::string& BBName, const std::string& Key) { - int64_t result = 0; - NameKeyPair nameKeyPair(BBName, Key); - - NameCounterMap::iterator it = m_nameCounterMap.find(nameKeyPair); - if (it != m_nameCounterMap.end()) { // if found - result = it->second; - } else { // not found, set to Value; - m_nameCounterMap[nameKeyPair] = 0; - } - - return result; -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::set(const std::string& BBName, const std::string& Key, - const std::string& Value) { - NameKeyPair nameKeyPair(BBName, Key); - - NameKeyMap::iterator it = m_nameKeyMap.find(nameKeyPair); - if (it != m_nameKeyMap.end()) { // if found - it->second = std::string(Value); - } else { // not found, set to Value; - m_nameKeyMap[nameKeyPair] = std::string(Value); - } -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::set(const std::string& BBName, const std::string& Key, - const int64_t Value) { - NameKeyPair nameKeyPair(BBName, Key); - - NameCounterMap::iterator it = m_nameCounterMap.find(nameKeyPair); - if (it != m_nameCounterMap.end()) { // if found - it->second = Value; - } else { // not found, set to Value; - m_nameCounterMap[nameKeyPair] = Value; - } -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::add(const std::string& BBName, const std::string& Key, - const int64_t Value) { - int64_t result = Value; - NameKeyPair nameKeyPair(BBName, Key); - NameCounterMap::iterator it = m_nameCounterMap.find(nameKeyPair); - if (it != m_nameCounterMap.end()) { // if found - it->second = it->second + Value; - result = it->second; - } else { // not found, set to Value; - m_nameCounterMap[nameKeyPair] = Value; - } - - return result; -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::subtract(const std::string& BBName, const std::string& Key, - const int64_t Value) { - return add(BBName, Key, Value * -1); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::increment(const std::string& BBName, - const std::string& Key) { - return add(BBName, Key, 1); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::decrement(const std::string& BBName, - const std::string& Key) { - return add(BBName, Key, -1); -} - -// ---------------------------------------------------------------------------- - -void FwkBBServer::zero(const std::string& BBName, const std::string& Key) { - set(BBName, Key, 0ll); -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::setIfGreater(const std::string& BBName, - const std::string& Key, const int64_t Value) { - int64_t result = Value; - NameKeyPair nameKeyPair(BBName, Key); - - NameCounterMap::iterator it = m_nameCounterMap.find(nameKeyPair); - if (it != m_nameCounterMap.end()) { // if found - if (Value > it->second) it->second = Value; - result = it->second; - } else { // not found, set to Value; - m_nameCounterMap[nameKeyPair] = Value; - } - - return result; -} - -// ---------------------------------------------------------------------------- - -int64_t FwkBBServer::setIfLess(const std::string& BBName, - const std::string& Key, const int64_t Value) { - int64_t result = Value; - - NameKeyPair nameKeyPair(BBName, Key); - - NameCounterMap::iterator it = m_nameCounterMap.find(nameKeyPair); - if (it != m_nameCounterMap.end()) { // if found - if (Value < it->second) it->second = Value; - result = it->second; - } else { // not found, set to Value; - m_nameCounterMap[nameKeyPair] = Value; - } - - return result; -} - -// ---------------------------------------------------------------------------- - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/FwkBBServer.hpp b/tests/cpp/fwklib/FwkBBServer.hpp deleted file mode 100644 index 64bc845a30..0000000000 --- a/tests/cpp/fwklib/FwkBBServer.hpp +++ /dev/null @@ -1,226 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_FWKBBSERVER_H_ -#define GEODE_FWKLIB_FWKBBSERVER_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/** - * @file FwkBBServer.hpp - * @since 1.0 - * @version 1.0 - * @see - */ - -#include -#include - -#include - -#include "FwkBB.hpp" -#include "UDPIpc.hpp" - -// ---------------------------------------------------------------------------- - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -// ---------------------------------------------------------------------------- - -/** @class NameKeyPair - * @brief basic name/key pair - */ -class NameKeyPair { - public: - NameKeyPair(std::string sName, std::string sKey) - : m_name(sName), m_key(sKey) {} - - /** @brief get name */ - const std::string& getName() const { return m_name; } - - /** @brief get value */ - const std::string& getKey() const { return m_key; } - - private: - std::string m_name; - std::string m_key; -}; - -// ---------------------------------------------------------------------------- - -/** @class NameKeyCmp - * @brief name/key compare - */ -class NameKeyCmp { - public: - /** @brief Compares two NameKeyPair objects */ - bool operator()(const NameKeyPair& p1, const NameKeyPair& p2) const { - return ((p1.getName().compare(p2.getName()) * 2) + - p1.getKey().compare(p2.getKey())) < 0; - } -}; - -// ---------------------------------------------------------------------------- - -typedef std::map NameKeyMap; -typedef std::map NameCounterMap; - -// ---------------------------------------------------------------------------- - -/** @class FwkBBServer - * @brief Framework BB server - */ -class FwkBBServer { - public: - FwkBBServer() {} - ~FwkBBServer(); - - // void start( uint32_t port ); - // void stop(); - - /** @brief Clear all server data */ - void clear(); - - void onDump(FwkBBMessage& message, FwkBBMessage& reply); - void onClearBB(FwkBBMessage& message); - void onGet(FwkBBMessage& message, FwkBBMessage& reply); - void onSet(FwkBBMessage& message); - void onAdd(FwkBBMessage& message, FwkBBMessage& reply); - void onSubtract(FwkBBMessage& message, FwkBBMessage& reply); - void onIncrement(FwkBBMessage& message, FwkBBMessage& reply); - void onDecrement(FwkBBMessage& message, FwkBBMessage& reply); - void onZero(FwkBBMessage& message); - void onSetIfGreater(FwkBBMessage& message, FwkBBMessage& reply); - void onSetIfLess(FwkBBMessage& message, FwkBBMessage& reply); - - // ---------------------------------------------------------------------------- - - void dump(std::string& result); - void dump(const std::string& BBName, std::string& result); - void clearBB(const std::string& BBName); - std::string getString(const std::string& BBName, const std::string& Key); - int64_t get(const std::string& BBName, const std::string& Key); - void set(const std::string& BBName, const std::string& Key, - const std::string& Value); - void set(const std::string& BBName, const std::string& Key, - const int64_t Value); - int64_t add(const std::string& BBName, const std::string& Key, - const int64_t Value); - int64_t subtract(const std::string& BBName, const std::string& Key, - const int64_t Value); - int64_t increment(const std::string& BBName, const std::string& Key); - int64_t decrement(const std::string& BBName, const std::string& Key); - void zero(const std::string& BBName, const std::string& Key); - int64_t setIfGreater(const std::string& BBName, const std::string& Key, - const int64_t Value); - int64_t setIfLess(const std::string& BBName, const std::string& Key, - const int64_t Value); - - private: - NameKeyMap m_nameKeyMap; - NameCounterMap m_nameCounterMap; - - // Service * m_farm; -}; - -// ---------------------------------------------------------------------------- - -class BBProcessor : public ServiceTask { - private: - UDPMessageQueues* m_queues; - FwkBBServer* m_server; - - public: - BBProcessor(UDPMessageQueues* shared, FwkBBServer* server) - : ServiceTask(shared), m_queues(shared), m_server(server) {} - - ~BBProcessor() noexcept override = default; - - int doTask() override { - while (*m_run) { - try { - UDPMessage* msg = m_queues->getInbound(); - if (msg) { - // Construct the FwkBBMessage - FwkBBMessage message; - message.fromMessageStream(msg->what()); - // Construct the reply - FwkBBMessage reply(BB_SET_ACK_COMMAND); - reply.setId(message.getId()); - // Process the message - switch (message.getCmdChar()) { - case 'C': // BB_CLEAR_COMMAND - m_server->onClearBB(message); - break; - case 'd': // BB_DUMP_COMMAND - m_server->onDump(message, reply); - break; - case 'g': // BB_GET_COMMAND - m_server->onGet(message, reply); - break; - case 's': // BB_SET_COMMAND - m_server->onSet(message); - break; - case 'A': // BB_ADD_COMMAND - m_server->onAdd(message, reply); - break; - case 'S': // BB_SUBTRACT_COMMAND - m_server->onSubtract(message, reply); - break; - case 'I': // BB_INCREMENT_COMMAND - m_server->onIncrement(message, reply); - break; - case 'D': // BB_DECREMENT_COMMAND - m_server->onDecrement(message, reply); - break; - case 'z': // BB_ZERO_COMMAND - m_server->onZero(message); - break; - case 'G': // BB_SET_IF_GREATER_COMMAND - m_server->onSetIfGreater(message, reply); - break; - case 'L': // BB_SET_IF_LESS_COMMAND - m_server->onSetIfLess(message, reply); - break; - default: - break; - } - // Construct response - msg->setMessage(reply.toMessageStream()); - m_queues->putOutbound(msg); - } - } catch (FwkException& ex) { - FWKSEVERE("BBProcessor::doTask() caught exception: " << ex.what()); - } catch (...) { - FWKSEVERE("BBProcessor::doTask() caught unknown exception"); - } - } - return 0; - } - void initialize() override {} - void finalize() override {} -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_FWKBBSERVER_H_ diff --git a/tests/cpp/fwklib/FwkLog.cpp b/tests/cpp/fwklib/FwkLog.cpp index 4a3ad0df94..bd90a245c2 100644 --- a/tests/cpp/fwklib/FwkLog.cpp +++ b/tests/cpp/fwklib/FwkLog.cpp @@ -81,13 +81,6 @@ void plog(const char* l, const char* s, const char* filename, int32_t lineno) { hacks::aceThreadId(ACE_OS::thr_self()), fil, lineno, l, s); fflush(stdout); } - -void dumpStack() { - apache::geode::client::Exception trace("StackTrace "); - fprintf(stdout, "%s\n", trace.getStackTrace().c_str()); - fflush(stdout); -} - } // namespace testframework } // namespace client } // namespace geode diff --git a/tests/cpp/fwklib/FwkLog.hpp b/tests/cpp/fwklib/FwkLog.hpp index 1ceb490a05..d6bd605c0c 100644 --- a/tests/cpp/fwklib/FwkLog.hpp +++ b/tests/cpp/fwklib/FwkLog.hpp @@ -44,7 +44,6 @@ namespace testframework { const char* strnrchr(const char* str, const char tok, int32_t cnt); const char* dirAndFile(const char* str); void plog(const char* l, const char* s, const char* filename, int32_t lineno); -void dumpStack(); const char* getNodeName(); /* Macro for logging */ diff --git a/tests/cpp/fwklib/FwkStrCvt.cpp b/tests/cpp/fwklib/FwkStrCvt.cpp deleted file mode 100644 index cfb8b33573..0000000000 --- a/tests/cpp/fwklib/FwkStrCvt.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -// ---------------------------------------------------------------------------- - -char* FwkStrCvt::hexify(uint8_t* buff, int32_t len) { - char* obuff = new char[(len + 1) * 2]; - for (int32_t i = 0; i < len; i++) { - sprintf((obuff + (i * 2)), "%02x", buff[i]); - } - return obuff; -} - -// ---------------------------------------------------------------------------- - -std::string FwkStrCvt::toTimeString(int32_t seconds) { - std::string result; - const int32_t perMinute = 60; - const int32_t perHour = 3600; - const int32_t perDay = 86400; - - if (seconds <= 0) { - result += "No limit specified."; - return result; - } - - int32_t val = 0; - if (seconds > perDay) { - val = seconds / perDay; - if (val > 0) { - result += FwkStrCvt(val).toString(); - if (val == 1) { - result += " day "; - } else { - result += " days "; - } - } - seconds %= perDay; - } - if (seconds > perHour) { - val = seconds / perHour; - if (val > 0) { - result += FwkStrCvt(val).toString(); - if (val == 1) { - result += " hour "; - } else { - result += " hours "; - } - } - seconds %= perHour; - } - if (seconds > perMinute) { - val = seconds / perMinute; - if (val > 0) { - result += FwkStrCvt(val).toString(); - if (val == 1) { - result += " minute "; - } else { - result += " minutes "; - } - } - seconds %= perMinute; - } - if (seconds > 0) { - result += FwkStrCvt(seconds).toString(); - if (seconds == 1) { - result += " second "; - } else { - result += " seconds "; - } - } - return result; -} - -// This expects a string of the form: 12h23m43s -// and returns the time encoded in the string as -// the integer number of seconds it represents. -int32_t FwkStrCvt::toSeconds(const char* str) { - int32_t max = static_cast(ACE_OS::strspn(str, "0123456789hHmMsS")); - std::string tstr(str, max); - - int32_t seconds = 0, i1 = 0, i2 = 0, i3 = 0; - char c1 = 0, c2 = 0, c3 = 0; - - sscanf(tstr.c_str(), "%d%c%d%c%d%c", &i1, &c1, &i2, &c2, &i3, &c3); - if (i1 > 0) seconds += asSeconds(i1, c1); - if (i2 > 0) seconds += asSeconds(i2, c2); - if (i3 > 0) seconds += asSeconds(i3, c3); - return seconds; -} - -int32_t FwkStrCvt::asSeconds(int32_t val, char typ) { - int32_t ret = 0; - switch (typ) { - case 'm': - case 'M': - ret = val * 60; - break; - case 'h': - case 'H': - ret = val * 3600; - break; - default: - ret = val; - break; - } - return ret; -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/FwkStrCvt.hpp b/tests/cpp/fwklib/FwkStrCvt.hpp deleted file mode 100644 index 6fbc356250..0000000000 --- a/tests/cpp/fwklib/FwkStrCvt.hpp +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -#pragma once - -#ifndef GEODE_FWKLIB_FWKSTRCVT_H_ -#define GEODE_FWKLIB_FWKSTRCVT_H_ - -#include "config.h" - -#if defined(_MACOSX) -#include -#endif - -#include - -#include - -#include - -// ---------------------------------------------------------------------------- - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -// ---------------------------------------------------------------------------- - -#if defined(WIN32) -#define Int64_FMT "%I64d" -#define UInt64_FMT "%I64u" -#elif defined(_LINUX) -#define Int64_FMT "%jd" -#define UInt64_FMT "%ju" -#elif defined(_SOLARIS) -#define Int64_FMT "%lld" -#define UInt64_FMT "%llu" -#elif defined(_MACOSX) -#define Int64_FMT "%" PRId64 -#define UInt64_FMT "%" PRIu64 -#else -#error not implemented -#endif - -// ---------------------------------------------------------------------------- - -/** - * @class FwkStrCvt - * @brief basic string converting class - */ -class FwkStrCvt { - public: - static int64_t hton64(int64_t value); - static int64_t ntoh64(int64_t value); - static int32_t hton32(int32_t value); - static int32_t ntoh32(int32_t value); - static int16_t hton16(int16_t value); - static int16_t ntoh16(int16_t value); - static char* hexify(uint8_t* buff, int32_t len); - - /** @brief convert from string value */ - explicit FwkStrCvt(const std::string& text) { m_sText = text; } - /** @brief convert from string value */ - explicit FwkStrCvt(const char* pszText) { - if (pszText) m_sText = pszText; - } - /** @brief convert from double value */ - explicit FwkStrCvt(const double dValue) { - char szText[50]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, "%lf", dValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - /** @brief convert from float value */ - explicit FwkStrCvt(const float fValue) { - char szText[50]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, "%f", fValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - /** @brief convert from uint32_t value */ - explicit FwkStrCvt(const uint32_t uiValue) { - char szText[50]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, "%u", uiValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - /** @brief convert from int32_t value */ - explicit FwkStrCvt(const int32_t iValue) { - char szText[50]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, "%d", iValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - /** @brief convert from bool value */ - explicit FwkStrCvt(const bool bValue) { - m_sText = (bValue) ? "true" : "false"; - } - - /** @brief convert from uint64_t value */ - explicit FwkStrCvt(const uint64_t uiValue) { - char szText[100]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, UInt64_FMT, uiValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - - /** @brief convert from int64_t value */ - explicit FwkStrCvt(const int64_t iValue) { - char szText[100]; - if (ACE_OS::snprintf(szText, sizeof(szText) - 1, Int64_FMT, iValue)) { - m_sText = szText; - } else { - m_sText.clear(); - } - } - - /** @brief gets double value */ - double toDouble() { return ACE_OS::strtod(m_sText.c_str(), nullptr); } - - /** @brief gets float value */ - float toFloat() { - return static_cast(ACE_OS::strtod(m_sText.c_str(), nullptr)); - } - - /** @brief gets int32_t value */ - int32_t toInt() { return ACE_OS::atoi(m_sText.c_str()); } - - /** @brief gets uint32_t value */ - uint32_t toUint() { - return static_cast(ACE_OS::atoi(m_sText.c_str())); - } - - /** @brief gets int32_t value */ - // TODO: : why this returns in32_t? if so why different from toInt() - int32_t toLong() { return toInt(); } - - /** @brief gets uint32_t value */ - // TODO: : why this returns uin32_t? if so why different from toUInt() - uint32_t toUlong() { return toUint(); } - - /** @brief gets int32_t value */ - int32_t toInt32() { return toInt(); } - - /** @brief gets uint32_t value */ - uint32_t toUInt32() { return toUint(); } - - /** @brief gets uint64_t value */ - uint64_t toUInt64() { - uint64_t uiValue = 0; - sscanf(m_sText.c_str(), UInt64_FMT, &uiValue); - return uiValue; - } - - /** @brief gets int64_t value */ - int64_t toInt64() { - int64_t iValue = 0; - sscanf(m_sText.c_str(), Int64_FMT, &iValue); - return iValue; - } - - /** @brief gets bool value */ - bool toBool() { - bool bBool = false; - if (m_sText.size()) { - if ((m_sText.at(0) == 't') || (m_sText.at(0) == 'T')) bBool = true; - } - return bBool; - } - - /** @brief gets float value */ - static float toFloat(const char* value) { - if (!value) { - return 0.0; - } - return static_cast(ACE_OS::strtod(value, nullptr)); - } - - /** @brief gets float value */ - static float toFloat(const std::string& value) { - if (value.empty()) { - return -1.0; - } - return FwkStrCvt::toFloat(value.c_str()); - } - - /** @brief gets double value */ - static double toDouble(const char* value) { - if (!value) { - return 0.0; - } - return ACE_OS::strtod(value, nullptr); - } - - /** @brief gets double value */ - static double toDouble(const std::string& value) { - if (value.empty()) { - return -1.0; - } - return FwkStrCvt::toDouble(value.c_str()); - } - - /** @brief gets int32_t value */ - static int32_t toInt32(const char* value) { - if (!value) { - return 0; - } - return ACE_OS::atoi(value); - } - - /** @brief gets int32_t value */ - static int32_t toInt32(const std::string& value) { - if (value.empty()) { - return -1; - } - return ACE_OS::atoi(value.c_str()); - } - - /** @brief gets uint32_t value */ - static uint32_t toUInt32(const char* value) { - if (!value) return 0; - return static_cast(ACE_OS::atoi(value)); - } - - /** @brief gets uint32_t value */ - static uint32_t toUInt32(const std::string& value) { - if (value.empty()) { - return 0; - } - return static_cast(ACE_OS::atoi(value.c_str())); - } - - /** @brief gets uint64_t value */ - static uint64_t toUInt64(const std::string& value) { - if (value.empty()) { - return 0; - } - return toUInt64(value.c_str()); - } - - /** @brief gets uint64_t value */ - static uint64_t toUInt64(const char* value) { - uint64_t uiValue = 0; - if (!value) return uiValue; - sscanf(value, UInt64_FMT, &uiValue); - return uiValue; - } - - /** @brief gets int64_t value */ - static int64_t toInt64(const std::string& value) { - if (value.empty()) { - return 0; - } - return toInt64(value.c_str()); - } - - /** @brief gets int64_t value */ - static int64_t toInt64(const char* value) { - int64_t iValue = 0; - if (!value) { - return iValue; - } - sscanf(value, Int64_FMT, &iValue); - return iValue; - } - - /** @brief from int64_t value */ - static std::string toString(int64_t value) { - char text[100]; - ACE_OS::snprintf(text, 99, Int64_FMT, value); - return text; - } - - /** @brief from uint64_t value */ - static std::string toString(uint64_t value) { - char text[100]; - ACE_OS::snprintf(text, 99, UInt64_FMT, value); - return text; - } - - /** @brief gets bool value */ - static bool toBool(const std::string& value) { - if (value.empty()) { - return false; - } - return FwkStrCvt::toBool(value.c_str()); - } - - /** @brief gets bool value */ - static bool toBool(const char* value) { - if (value && ((*value == 't') || (*value == 'T'))) { - return true; - } - return false; - } - - static int32_t toSeconds(const std::string& str) { - if (str.empty()) { - return -1; - } - return toSeconds(str.c_str()); - } - - static std::string toTimeString(int32_t seconds); - - // This expects a string of the form: 12h23m43s - // and returns the time encoded in the string as - // the integer number of seconds it represents. - static int32_t toSeconds(const char* str); - - /** @brief gets string value */ - std::string& toString() { return m_sText; } - - /** @brief gets string value */ - const std::string& asString() { return m_sText; } - - /** @brief gets char * value */ - const char* asChar() { return m_sText.c_str(); } - - private: - static int32_t asSeconds(int32_t val, char typ); - - std::string m_sText; -}; - -// ---------------------------------------------------------------------------- - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_FWKSTRCVT_H_ diff --git a/tests/cpp/fwklib/IpcHandler.cpp b/tests/cpp/fwklib/IpcHandler.cpp deleted file mode 100644 index 54cb5bf894..0000000000 --- a/tests/cpp/fwklib/IpcHandler.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "IpcHandler.hpp" - -#include -#include - -#include - -#include -#include -#include -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -// This class is not thread safe, and its use in the test framework -// does not require it to be. -IpcHandler::IpcHandler(const ACE_INET_Addr &driver, int32_t waitSeconds) - : m_io(new ACE_SOCK_Stream()) { - ACE_OS::signal(SIGPIPE, SIG_IGN); // Ignore broken pipe - ACE_SOCK_Connector conn; - ACE_Time_Value wtime(waitSeconds, 1000); - int32_t retVal = conn.connect(*m_io, driver, &wtime); - if (retVal == -1) { -#ifdef WIN32 - errno = WSAGetLastError(); -#endif - FWKEXCEPTION("Attempt to connect failed, error: " << errno); - } -} - -IpcHandler::~IpcHandler() { - sendIpcMsg(IPC_EXITING); - close(); - checkBuffer(-12); -} - -void IpcHandler::close() { - if (m_io) { - m_io->close(); - delete m_io; - m_io = nullptr; - } -} - -bool IpcHandler::checkPipe() { - static ACE_Time_Value next; - if (!m_io) { - return false; - } - ACE_Time_Value now = ACE_OS::gettimeofday(); - if (next < now) { - ACE_Time_Value interval(60); - next = now + interval; - if (!sendIpcMsg(IPC_NULL)) return false; - } - return true; -} - -IpcMsg IpcHandler::readIpcMsg(int32_t waitSeconds) { - IpcMsg result = IPC_NULL; - int32_t red = readInt(waitSeconds); - if (red != -1) { - result = static_cast(red); - if (result == IPC_NULL) { - return readIpcMsg(waitSeconds); // skip past nulls - } - } - return result; -} - -int32_t IpcHandler::readInt(int32_t waitSeconds) { - int32_t result = -1; - if (!checkPipe()) { - FWKEXCEPTION("Connection failure, error: " << errno); - } - - auto wtime = new ACE_Time_Value(waitSeconds, 1000); - int32_t redInt = -1; - auto length = m_io->recv_n(&redInt, 4, 0, wtime); - delete wtime; - if (length == 4) { - result = ntohl(redInt); - // FWKDEBUG( "Received " << result ); - } else { - if (length == -1) { -#ifdef WIN32 - errno = WSAGetLastError(); -#endif - if ((errno > 0) && (errno != ETIME)) { - FWKEXCEPTION("Read failure, error: " << errno); - } - } - } - return result; -} - -char *IpcHandler::checkBuffer(int32_t len) { - static int32_t length = 512; - static char *buffer = nullptr; - - if (len == -12) { - delete[] buffer; - buffer = nullptr; - return buffer; - } - - if (length < len) { - length = len + 32; - if (buffer != nullptr) { - delete[] buffer; - buffer = nullptr; - } - } - - if (buffer == nullptr) { - buffer = new char[length]; - } - - memset(buffer, 0, length); - return buffer; -} - -std::string IpcHandler::readString(int32_t waitSeconds) { - int32_t length = readInt(waitSeconds); - if (length == -1) { - FWKEXCEPTION( - "Failed to read string, length not available, errno: " << errno); - } - - char *buffer = checkBuffer(length); - - ACE_Time_Value *wtime = new ACE_Time_Value(waitSeconds, 1000); - - auto readLength = m_io->recv(buffer, length, 0, wtime); - delete wtime; - if (readLength <= 0) { - if (readLength < 0) { -#ifdef WIN32 - errno = WSAGetLastError(); -#endif - } else { - errno = EWOULDBLOCK; - } - FWKEXCEPTION("Failed to read string from socket, errno: " << errno); - } - // FWKDEBUG( "Received " << buffer ); - return buffer; -} - -IpcMsg IpcHandler::getIpcMsg(int32_t waitSeconds, std::string &str) { - IpcMsg msg = readIpcMsg(waitSeconds); - switch (msg) { - case IPC_PING: - case IPC_NULL: // null should never be seen here - case IPC_ACK: - case IPC_EXITING: - break; // nothing required - case IPC_DONE: - case IPC_RUN: // Need to read the rest - str = readString(waitSeconds); - if (!str.empty()) sendIpcMsg(IPC_ACK); - break; - case IPC_ERROR: - case IPC_EXIT: - sendIpcMsg(IPC_ACK); - break; - } - return msg; -} - -IpcMsg IpcHandler::getIpcMsg(int32_t waitSeconds) { - IpcMsg msg = readIpcMsg(waitSeconds); - switch (msg) { - case IPC_PING: - case IPC_NULL: // null should never be seen here - case IPC_ACK: - case IPC_EXITING: - break; // nothing required - case IPC_DONE: - case IPC_RUN: // Need to read the rest - break; - case IPC_ERROR: - case IPC_EXIT: - sendIpcMsg(IPC_ACK); - break; - } - return msg; -} - -bool IpcHandler::sendIpcMsg(IpcMsg msg, int32_t waitSeconds) { - int32_t writeInt = htonl(msg); - // FWKDEBUG( "Sending " << ( int32_t )msg ); - ACE_Time_Value tv(waitSeconds, 1000); - auto wrote = m_io->send(&writeInt, 4, &tv); - if (wrote == -1) { -#ifdef WIN32 - errno = WSAGetLastError(); -#endif - if (errno > 0) { - FWKEXCEPTION("Send failure, error: " << errno); - } - } - if (wrote == 4) { - switch (msg) { - case IPC_NULL: - case IPC_ERROR: - case IPC_ACK: - case IPC_RUN: - case IPC_DONE: - return true; - case IPC_EXITING: - case IPC_PING: - case IPC_EXIT: - msg = getIpcMsg(60); - if (msg == IPC_ACK) return true; - break; - } - } - return false; -} - -bool IpcHandler::sendBuffer(IpcMsg msg, const char *str) { - auto length = static_cast(strlen(str)); - char *buffer = checkBuffer(length); - *reinterpret_cast(buffer) = static_cast(htonl(msg)); - *reinterpret_cast(buffer + 4) = htonl(length); - strncpy((buffer + 8), str, length - 8); - - // FWKDEBUG( "Sending " << ( int32_t )msg << " and string: " << str ); - length += 8; - auto wrote = m_io->send(buffer, length); - if (wrote == -1) { -#ifdef WIN32 - errno = WSAGetLastError(); -#endif - if (errno > 0) { - FWKEXCEPTION("Send failure, error: " << errno); - } - } - if (wrote == length) { - if (getIpcMsg(180) != IPC_ACK) { - FWKEXCEPTION("Send was not ACK'ed."); - } - return true; - } - FWKEXCEPTION("Tried to write " << length << " bytes, only wrote " << wrote); -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/IpcHandler.hpp b/tests/cpp/fwklib/IpcHandler.hpp deleted file mode 100644 index 33579fb047..0000000000 --- a/tests/cpp/fwklib/IpcHandler.hpp +++ /dev/null @@ -1,91 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_IPCHANDLER_H_ -#define GEODE_FWKLIB_IPCHANDLER_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include - -#include -#include - -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -enum IpcMsg { - IPC_NULL = 0xabc0, - IPC_EXITING = 0xabc1, // no response, client is exiting - IPC_ERROR = 0xabc2, // never sent - IPC_ACK = 0xabc3, // c<>d : single byte, no response - IPC_PING = 0xabc4, // d->c : single byte, no response - // IPC_STOP = 0xabc5, // d->c : single byte, expect ack - IPC_EXIT = 0xabc6, // d->c : single byte, expect ack - IPC_RUN = 0xabc7, // d->c : task id, expect ack - // IPC_SYNC = 0xabc8, // c->d : single byte, expect ack - // IPC_GO = 0xabc9, // d->c : single byte, expect ack - IPC_DONE = 0xabca // c->d : single byte, expect ack -}; - -class IpcHandler { - private: - ACE_SOCK_Stream *m_io; - - bool checkPipe(); - int32_t readInt(int32_t waitSeconds); - bool sendIpcMsg(IpcMsg msg, int32_t waitSeconds = 0); - bool sendBuffer(IpcMsg msg, const char *str); - std::string readString(int32_t waitSeconds); - IpcMsg readIpcMsg(int32_t waitSeconds); - - public: - explicit IpcHandler(const ACE_INET_Addr &driver, int32_t maxWaitSecs = 0); - - inline explicit IpcHandler(ACE_SOCK_Stream *io) : m_io(io) { - ACE_OS::signal(SIGPIPE, SIG_IGN); // Ignore broken pipe - } - - ~IpcHandler(); - - void close(); - - IpcMsg getIpcMsg(int32_t waitSeconds, std::string &result); - IpcMsg getIpcMsg(int32_t waitSeconds); - char *checkBuffer(int32_t size); - - bool sendTask(char *task) { return sendBuffer(IPC_RUN, task); } - - bool sendResult(char *result) { return sendBuffer(IPC_DONE, result); } - - inline bool sendExit() { - return sendIpcMsg(IPC_EXIT); - close(); - } -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_IPCHANDLER_H_ diff --git a/tests/cpp/fwklib/Service.cpp b/tests/cpp/fwklib/Service.cpp deleted file mode 100644 index 0cb6b4d7ab..0000000000 --- a/tests/cpp/fwklib/Service.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "Service.hpp" - -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -Service::Service(int32_t threadCnt) - : m_ThreadCount(threadCnt), m_run(true), m_Mutex() { - int32_t forceActive = 1; - - int32_t flags = - THR_NEW_LWP | THR_JOINABLE | THR_CANCEL_ENABLE | THR_CANCEL_ASYNCHRONOUS; - -#ifndef WIN32 - flags |= THR_INHERIT_SCHED; -#endif - - m_busy = 0; - activate(flags, threadCnt, forceActive); -} - -int32_t Service::svc() { - while (m_run) { - ServiceTask* task = getQ(); - if (task) { - try { - task->initialize(); - task->doTask(); - task->finalize(); - } catch (FwkException& ex) { - FWKERROR("Service: Caught exception in svc: " << ex.what()); - } catch (...) { - FWKERROR("Service: Caught exception in svc."); - } - m_busy--; - } - } - return 0; -} - -int32_t Service::runThreaded(ServiceTask* task, uint32_t threads) { - uint32_t avail = getIdleCount(); - if (threads > avail) { - threads = avail; - } - task->setRunFlag(&m_run); - putQ(task, threads); - - return threads; -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/Service.hpp b/tests/cpp/fwklib/Service.hpp deleted file mode 100644 index ecb0817f93..0000000000 --- a/tests/cpp/fwklib/Service.hpp +++ /dev/null @@ -1,165 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_SERVICE_H_ -#define GEODE_FWKLIB_SERVICE_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include -#include - -#include -#include - -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -class SharedTaskObject { - public: - SharedTaskObject() {} - - virtual ~SharedTaskObject() {} - - virtual void initialize() = 0; - virtual void finalize() = 0; -}; - -class ServiceTask { - protected: - volatile bool* m_run; - SharedTaskObject* m_shared; - - public: - explicit ServiceTask(SharedTaskObject* shared) - : m_run(nullptr), m_shared(shared) {} - - virtual ~ServiceTask() {} - - void setRunFlag(volatile bool* run) { m_run = run; } - virtual int32_t doTask() = 0; - virtual void initialize() = 0; - virtual void finalize() = 0; -}; - -class Service : public ACE_Task_Base { - private: - uint32_t m_ThreadCount; - volatile bool m_run; - std::atomic m_busy; - ACE_Thread_Mutex m_Mutex; - ACE_DLList m_TaskQueue; - - int32_t svc() override; - - inline void putQ(ServiceTask* task, uint32_t cnt = 1) { - ACE_Guard guard(m_Mutex); - m_busy += cnt; - for (uint32_t i = 0; i < cnt; i++) m_TaskQueue.insert_tail(task); - } - - inline ServiceTask* getQ() { - ACE_Guard guard(m_Mutex); - return m_TaskQueue.delete_head(); - } - - public: - explicit Service(int32_t threadCnt); - - ~Service() override { stopThreads(); } - - int32_t runThreaded(ServiceTask* task, uint32_t threads); - - inline uint32_t getBusyCount() { return m_busy; } - inline uint32_t getIdleCount() { return m_ThreadCount - m_busy; } - - inline void stopThreads() { - m_run = false; - wait(); - } -}; - -template -class SafeQueue { - ACE_Thread_Mutex m_mutex; - ACE_DLList m_queue; - ACE_Condition m_cond; - - public: - SafeQueue() : m_mutex(), m_cond(m_mutex) {} - ~SafeQueue() {} - - void enqueue(T* val) { - ACE_Guard guard(m_mutex); - m_queue.insert_tail(val); - m_cond.signal(); - } - - T* dequeue() { - ACE_Guard guard(m_mutex); - if (m_queue.size() == 0) { - ACE_Time_Value until(2); - until += ACE_OS::gettimeofday(); - auto res = m_cond.wait(&until); - if (res == -1) return nullptr; - } - return m_queue.delete_head(); - } - - bool isEmpty() { - ACE_Guard guard(m_mutex); - return m_queue.isEmpty(); - } - - uint32_t size() { - ACE_Guard guard(m_mutex); - return static_cast(m_queue.size()); - } -}; - -class IPCMessage { - protected: - std::string m_msg; - - public: - IPCMessage() {} - explicit IPCMessage(std::string content) { m_msg = content; } - - virtual ~IPCMessage() {} - - std::string& what() { return m_msg; } - - uint32_t length() { return static_cast(m_msg.size()); } - - const char* getContent() { return m_msg.c_str(); } - - void setMessage(std::string& content) { m_msg = content; } - - virtual void clear() { m_msg.clear(); } -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_SERVICE_H_ diff --git a/tests/cpp/fwklib/TcpIpc.cpp b/tests/cpp/fwklib/TcpIpc.cpp deleted file mode 100644 index aadaa988f2..0000000000 --- a/tests/cpp/fwklib/TcpIpc.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "TcpIpc.hpp" - -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "config.h" - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -void TcpIpc::clearNagle(ACE_HANDLE sock) { - int32_t val = 1; - char *param = reinterpret_cast(&val); - int32_t plen = sizeof(val); - - if (0 != ACE_OS::setsockopt(sock, IPPROTO_TCP, 1, param, plen)) { - FWKSEVERE("Failed to set NAGLE on socket. Errno: " << errno); - } -} - -int32_t TcpIpc::getSize(ACE_HANDLE sock, int32_t flag) { - int32_t val = 0; - auto *param = reinterpret_cast(&val); - int32_t plen = sizeof(val); - - if (0 != ACE_OS::getsockopt(sock, SOL_SOCKET, flag, param, &plen)) { - FWKSEVERE("Failed to get buff size for flag " - << flag << " on socket. Errno: " << errno); - } -#ifdef _LINUX - val /= 2; -#endif - return val; -} - -int32_t TcpIpc::setSize(ACE_HANDLE sock, int32_t flag, int32_t size) { - int32_t val = 0; - if (size <= 0) return 0; - - auto *param = reinterpret_cast(&val); - int32_t plen = sizeof(val); - - int32_t inc = 32120; - val = size - (3 * inc); - if (val < 0) val = 0; - int32_t red = 0; - int32_t lastRed = -1; - while (lastRed != red) { - lastRed = red; - val += inc; - ACE_OS::setsockopt(sock, SOL_SOCKET, flag, param, plen); - if (0 != ACE_OS::getsockopt(sock, SOL_SOCKET, flag, param, &plen)) { - FWKSEVERE("Failed to get buff size for flag " - << flag << " on socket. Errno: " << errno); - } -#ifdef _LINUX - val /= 2; -#endif - if (val < size) red = val; - } - return val; -} - -void TcpIpc::init(int32_t sockBufferSize) { - auto sock = ACE_OS::socket(AF_INET, SOCK_STREAM, 0); - if (sock < 0) { - FWKSEVERE("Failed to create socket. Errno: " << errno); - } - - if (sockBufferSize > 0) { - clearNagle(sock); - - setSize(sock, SO_SNDBUF, sockBufferSize); - setSize(sock, SO_RCVBUF, sockBufferSize); - } - m_io = new ACE_SOCK_Stream(sock); - ACE_OS::signal(SIGPIPE, SIG_IGN); // Ignore broken pipe -} - -bool TcpIpc::accept(ACE_SOCK_Acceptor *acceptor, int32_t waitSecs) { - if (acceptor->accept(*m_io, nullptr, new ACE_Time_Value(waitSecs)) != 0) { - FWKSEVERE("Accept failed with errno: " << errno); - return false; - } - return true; -} - -bool TcpIpc::connect(int32_t waitSecs) { - if (m_ipaddr.empty()) { - FWKSEVERE("Connect failed, address not set."); - return false; - } - ACE_INET_Addr driver(m_ipaddr.c_str()); - ACE_SOCK_Connector conn; - int32_t retVal = -1; - while ((retVal == -1) && (waitSecs-- > 0)) { - std::this_thread::sleep_for(std::chrono::seconds(1)); - errno = 0; - retVal = conn.connect(*m_io, driver); - } - if (retVal == -1) { - FWKSEVERE("Attempt to connect failed, errno: " << errno); - return false; - } - return true; -} - -TcpIpc::~TcpIpc() { close(); } - -void TcpIpc::close() { - if (m_io != nullptr) { - m_io->close(); - delete m_io; - m_io = nullptr; - } -} - -int32_t TcpIpc::readBuffer(char **buffer, int32_t waitSecs) { - ACE_Time_Value wtime(waitSecs); - iovec buffs; - buffs.iov_base = nullptr; - buffs.iov_len = 0; - int32_t red = static_cast(m_io->recvv(&buffs, &wtime)); - if ((red == -1) && ((errno == ECONNRESET) || (errno == EPIPE))) { - FWKEXCEPTION("During attempt to read: Connection failure errno: " << errno); - } - if (red == -1) { - } - *buffer = reinterpret_cast(buffs.iov_base); - return buffs.iov_len; -} - -int32_t TcpIpc::sendBuffers(int32_t cnt, char *buffers[], int32_t lengths[], - int32_t waitSecs) { - ACE_Time_Value wtime(waitSecs); - int32_t tot = 0; - if (cnt > 2) { - FWKEXCEPTION("During attempt to write: Too many buffers passed in."); - } - iovec buffs[2]; - for (int32_t idx = 0; idx < cnt; idx++) { - buffs[idx].iov_base = buffers[idx]; - buffs[idx].iov_len = lengths[idx]; - tot += lengths[idx]; - } - int32_t wrote = static_cast(m_io->sendv(buffs, cnt, &wtime)); - if ((wrote == -1) && ((errno == ECONNRESET) || (errno == EPIPE))) { - FWKEXCEPTION( - "During attempt to write: Connection failure errno: " << errno); - } - if (tot != wrote) { - FWKSEVERE("Failed to write all bytes attempted, wrote " - << wrote << ", attempted " << tot); - } - return wrote; -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/TcpIpc.hpp b/tests/cpp/fwklib/TcpIpc.hpp deleted file mode 100644 index d714d4331d..0000000000 --- a/tests/cpp/fwklib/TcpIpc.hpp +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_TCPIPC_H_ -#define GEODE_FWKLIB_TCPIPC_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include - -#include -#include - -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -class TcpIpc { - private: - ACE_SOCK_Stream* m_io; - std::string m_ipaddr; - - void init(int32_t sockBufferSize = 0); - void clearNagle(ACE_HANDLE sock); - int32_t setSize(ACE_HANDLE sock, int32_t flag, int32_t size); - int32_t getSize(ACE_HANDLE sock, int32_t flag); - - public: - explicit TcpIpc(std::string& ipaddr, int32_t sockBufferSize = 0) - : m_ipaddr(ipaddr) { - init(sockBufferSize); - } - explicit TcpIpc(char* ipaddr, int32_t sockBufferSize = 0) : m_ipaddr(ipaddr) { - init(sockBufferSize); - } - - explicit TcpIpc(int32_t sockBufferSize = 0) { init(sockBufferSize); } - - ~TcpIpc(); - - void close(); - - bool accept(ACE_SOCK_Acceptor* acceptor, int32_t waitSecs = 0); - bool connect(int32_t waitSecs = 0); - - int32_t readBuffer(char** buffer, int32_t waitSecs = 0); - int32_t sendBuffer(char* buffer, int32_t length, int32_t waitSecs = 0) { - char* buffs[1]; - buffs[0] = buffer; - int32_t lengths[1]; - lengths[0] = length; - return sendBuffers(1, buffs, lengths, waitSecs); - } - int32_t sendBuffers(int32_t cnt, char* buffers[], int32_t lengths[], - int32_t waitSecs = 0); -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_TCPIPC_H_ diff --git a/tests/cpp/fwklib/TimeBomb.cpp b/tests/cpp/fwklib/TimeBomb.cpp deleted file mode 100644 index 59ad3eeeaa..0000000000 --- a/tests/cpp/fwklib/TimeBomb.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include -#include -#include - -#include - -#include "config.h" - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -int32_t TimeBomb::svc() { - while (!m_stop) { - if (m_armed) { - if (m_endOfLife < ACE_OS::gettimeofday()) { - if (m_msg.length() > 0) { - FWKSEVERE("Timeout failure has occurred, waited " - << m_seconds << " seconds. " << m_msg); - } else { - FWKSEVERE("Timeout failure has occurred, waited " << m_seconds - << " seconds."); - } - -#if defined(_SOLARIS) - - int32_t pid = ACE_OS::getpid(); - char buf[8192]; - sprintf(buf, "bash -c \"pstack %d\"", pid); - FILE* pip = popen(buf, "r"); - if (!pip) { - FWKSEVERE("TimeBomb: Unable to dump threads."); - } else { - std::this_thread::sleep_for(std::chrono::seconds(10)); - - std::string dump; - buf[0] = 0; - while (fgets(buf, 8192, pip)) { - dump.append(buf); - buf[0] = 0; - } - dump.append(buf); - pclose(pip); - - FWKSEVERE("TimeBomb reports these threads in process:" - << dump << "End of dump.\n"); - } - -#endif - -#if defined(_LINUX) - - int32_t pid = ACE_OS::getpid(); - char buf[8192]; - sprintf(buf, - "bash -c \"perl $GEODE_NATIVE_HOME/../framework/scripts/gdb.pl " - "%d ; cat " - "gdbout.%d\"", - pid, pid); - FILE* pip = popen(buf, "r"); - if (!pip) { - FWKSEVERE("TimeBomb: Unable to dump threads."); - } else { - std::this_thread::sleep_for(std::chrono::seconds(10)); - - std::string dump; - buf[0] = 0; - while (fgets(buf, 8192, pip)) { - dump.append(buf); - buf[0] = 0; - } - dump.append(buf); - pclose(pip); - - FWKSEVERE("TimeBomb reports these threads in process:" - << dump << "End of dump.\n"); - } - -#elif defined(_WIN32) - - int32_t pid = ACE_OS::getpid(); - char buf[8192]; - - sprintf(buf, - "bash -c \"perl $GEODE_NATIVE_HOME/../framework/scripts/cdb.pl " - "%d\"", - pid); - FILE* pip = _popen(buf, "r"); - if (!pip) { - FWKSEVERE("TimeBomb: Unable to dump threads."); - } else { - std::this_thread::sleep_for(std::chrono::seconds(20)); - - std::string dump; - buf[0] = 0; - while (fgets(buf, 8192, pip)) { - dump.append(buf); - buf[0] = 0; - } - dump.append(buf); - _pclose(pip); - - FWKSEVERE("TimeBomb reports these threads in process:" - << dump << "End of dump.\n"); - } - -#endif - - FWKSEVERE("Will now abort by calling exit( " << m_exitCode << " )."); - exit(m_exitCode); - } - } - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - return 0; -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/TimeBomb.hpp b/tests/cpp/fwklib/TimeBomb.hpp deleted file mode 100644 index 7171db01e3..0000000000 --- a/tests/cpp/fwklib/TimeBomb.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_TIMEBOMB_H_ -#define GEODE_FWKLIB_TIMEBOMB_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 - -#include -#include -#include - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -class TimeBomb : public ACE_Task_Base { - private: - bool m_stop; - bool m_armed; - ACE_Time_Value m_endOfLife; - int32_t m_seconds; - int32_t m_exitCode; - std::string m_msg; - - int32_t svc() override; - - public: - inline TimeBomb(uint32_t seconds, int32_t exitCode, const std::string& msg) - : m_stop(false), m_armed(false) { - arm(seconds, exitCode, msg); - activate(); - } - - inline TimeBomb() - : m_stop(false), m_armed(false), m_seconds(0), m_exitCode(-1) {} - - ~TimeBomb() override { - m_armed = false; - m_stop = true; - wait(); - } - - inline void arm(uint32_t seconds, int32_t exitCode, const std::string& msg) { - // FWKINFO( "Timebomb set for " << seconds << " seconds." ); - m_seconds = seconds; - m_exitCode = exitCode; - m_msg = msg; - m_endOfLife = ACE_OS::gettimeofday() + ACE_Time_Value(m_seconds); - m_armed = true; - char tbuf[64]; - const time_t tsec = static_cast(m_endOfLife.sec()); - ACE_OS::ctime_r(&tsec, tbuf, 64); - for (int32_t len = static_cast(strlen(tbuf)); len >= 0; len--) { - if ((tbuf[len] == '\n') || (tbuf[len] == '\r')) { - tbuf[len] = ' '; - } - } - FWKINFO("Timebomb set for: " << tbuf); - } - inline void disarm() { m_armed = false; } -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_TIMEBOMB_H_ diff --git a/tests/cpp/fwklib/UDPIpc.cpp b/tests/cpp/fwklib/UDPIpc.cpp deleted file mode 100644 index 11fc65633f..0000000000 --- a/tests/cpp/fwklib/UDPIpc.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 "UDPIpc.hpp" - -#include -#include -#include - -#include "FwkStrCvt.hpp" -#include "GsRandom.hpp" -#include "config.h" - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -bool UDPMessage::ping(ACE_SOCK_Dgram& io, ACE_INET_Addr& who) { - clear(); - setCmd(ACK_REQUEST); - setSender(who); - return send(io); -} - -std::string UDPMessage::dump(int32_t max) { - char buf[1024]; - std::string dmp("Dump of message parts: "); - sprintf(buf, "\nTag: %u\nCmd: %u %s\nId: %u\nLength: %u\nMessage:\n", - m_hdr.tag, m_hdr.cmd, cmdString(m_hdr.cmd), m_hdr.id, - ntohl(m_hdr.length)); - dmp += buf; - if (!m_msg.empty()) { - if (max > 0) { - dmp += m_msg.substr(0, max); - } else { - dmp += m_msg; - } - } else { - dmp += "No Message."; - } - dmp += "\nEnd of Dump"; - return dmp; -} - -bool UDPMessage::receiveFrom(ACE_SOCK_Dgram& io, - const ACE_Time_Value* timeout) { - bool ok = true; - ACE_Time_Value wait(2); - if (!timeout) { - timeout = &wait; - } - iovec buffs; - int32_t red = static_cast(io.recv(&buffs, m_sender, 0, timeout)); - if (red < 0) { - if (errno != ETIME) { - FWKEXCEPTION("UDPMessage::receiveFrom: Failed, errno: " << errno); - } - return false; - } - uint32_t len = buffs.iov_len; - if (len < UDP_HEADER_SIZE) { // We must at least have a header - FWKEXCEPTION("UDPMessage::receiveFrom: Failed, header length: " << len); - } - clear(); - memcpy(&m_hdr, buffs.iov_base, UDP_HEADER_SIZE); - if (m_hdr.tag != UDP_MSG_TAG) { - FWKEXCEPTION("UDPMessage::receiveFrom: Failed, invalid tag: " << m_hdr.tag); - } - char* ptr = reinterpret_cast(buffs.iov_base); - ptr += UDP_HEADER_SIZE; - len -= UDP_HEADER_SIZE; - uint32_t sent = ntohl(m_hdr.length); - if (sent != len) { - FWKEXCEPTION("UDPMessage::receiveFrom: Failed, expected " - << sent << " bytes, received " << len); - } - if (len > 0) { - m_msg = std::string(ptr, len); - } - delete[] reinterpret_cast(buffs.iov_base); - // FWKINFO( "UDPMessage::receiveFrom: " << dump( 50 ) );; - if (needToAck()) { - UDPMessage ack(ACK); - ok = (ok && ack.sendTo(io, m_sender)); - } - return ok; -} - -bool UDPMessage::sendTo(ACE_SOCK_Dgram& io, ACE_INET_Addr& who) { - setSender(who); - return send(io); -} - -bool UDPMessage::send(ACE_SOCK_Dgram& io) { - bool ok = true; - int32_t tot = 0; - int32_t vcnt = 1; - iovec buffs[2]; - m_hdr.length = 0; - buffs[0].iov_base = reinterpret_cast(&m_hdr); - buffs[0].iov_len = UDP_HEADER_SIZE; - tot += UDP_HEADER_SIZE; - if (!m_msg.empty()) { - auto len = static_cast(m_msg.size()); - m_hdr.length = htonl(len); - buffs[1].iov_base = const_cast(m_msg.c_str()); - buffs[1].iov_len = len; - vcnt = 2; - tot += len; - } - // FWKINFO( "UDPMessage::send: " << dump( 50 ) );; - int32_t sent = static_cast(io.send(buffs, vcnt, m_sender)); - if (sent < 0) { - FWKEXCEPTION("UDPMessage::send: Failed, errno: " << errno); - } - if (sent != tot) { - ok = false; - FWKSEVERE("UDPMessage::send: Failed to completely send, " << sent << ", " - << tot); - } - if (needToAck()) { - UDPMessage ack; - ok = (ok && ack.receiveFrom(io)); - } - return ok; -} - -UDPMessageClient::UDPMessageClient(std::string server) - : m_server(server.c_str()) { - int32_t result = -1; - int32_t tries = 100; - ACE_INET_Addr* client = new ACE_INET_Addr(); - while ((result < 0) && (tries > 0)) { - uint32_t port = GsRandom::random(1111u, 31111u) + tries; - client->set(port, "localhost"); - result = m_io.open(*client); - } - delete client; - if (result < 0) { - FWKEXCEPTION("Client failed to open io, " << errno); - } - const ACE_Time_Value timeout(20); - UDPMessage msg; - tries = 3; - bool pingMsg = false; - while (!pingMsg && tries-- > 0) { - try { - pingMsg = msg.ping(m_io, m_server); - } catch (...) { - continue; - } - } - if (pingMsg) { - // if ( msg.ping( m_io, m_server ) ) { - msg.setSender(m_server); - bool connectionOK = false; - tries = 10; - while (!connectionOK && (--tries > 0)) { - try { - msg.clear(); - msg.setCmd(ADDR_REQUEST); - if (msg.sendTo(m_io, m_server)) { - if (msg.receiveFrom(m_io, &timeout)) { - std::string newConn = msg.what(); - ACE_INET_Addr conn(newConn.c_str()); - if (msg.ping(m_io, conn)) { // We have a working addr - m_server = conn; - connectionOK = true; - tries = 0; - } - } - } - } catch (...) { - continue; - } - } - if (!connectionOK) { - FWKEXCEPTION( - "UDPMessageClient failed to establish connection to server."); - } - } else { - FWKEXCEPTION("Failed to contact " << server); - } -} - -int32_t Receiver::doTask() { - auto msg = std::unique_ptr(new UDPMessage()); - UDPMessage cmsg; - try { - while (*m_run) { - if (isListener()) { - cmsg.clear(); - ACE_Time_Value wait(30); // Timeout is relative time. - if (cmsg.receiveFrom(*m_io, &wait)) { - if (cmsg.getCmd() == ADDR_REQUEST) { - auto&& addr = m_addrs.front(); - m_addrs.pop_front(); - m_addrs.push_back(addr); - cmsg.clear(); - cmsg.setMessage(addr); - cmsg.setCmd(ADDR_RESPONSE); - cmsg.send(*m_io); - } - } - } else { - msg->clear(); - ACE_Time_Value timeout(2); - if (msg->receiveFrom( - *m_io, &timeout)) { // Timeout is relative time, send ack. - if (msg->getCmd() == ADDR_REQUEST) { - auto&& addr = m_addrs.front(); - m_addrs.pop_front(); - m_addrs.push_back(addr); - cmsg.clear(); - cmsg.setMessage(addr); - cmsg.setCmd(ADDR_RESPONSE); - cmsg.send(*m_io); - } - if (msg->length() > 0) { - m_queues->putInbound(msg.release()); - msg.reset(new UDPMessage()); - } - } - } - } - } catch (FwkException& ex) { - FWKSEVERE("Receiver::doTask() caught exception: " << ex.what()); - } catch (...) { - FWKSEVERE("Receiver::doTask() caught unknown exception"); - } - return 0; -} - -void Receiver::initialize() { - int32_t tries = 100; - uint16_t port = m_basePort; - int32_t lockResult = m_mutex.tryacquire(); - int32_t result = -1; - if (lockResult != -1) { // The listener thread - ACE_INET_Addr addr(port, "localhost"); - m_listener = ACE_Thread::self(); - result = m_io->open(addr); - } else { - while ((result < 0) && (--tries > 0)) { - port += ++m_offset; - ACE_INET_Addr addr(port, "localhost"); - result = m_io->open(addr); - if (result == 0) { - char hbuff[256]; - char* hst = &hbuff[0]; - char* fqdn = ACE_OS::getenv("GF_FQDN"); - if (fqdn) { - hst = fqdn; - } else { - addr.get_host_name(hbuff, 255); - } - char buff[1024]; - sprintf(buff, "%s:%u", hst, port); - m_addrs.push_back(buff); - } - } - } - if (result < 0) { - FWKEXCEPTION("Server failed to open io, " << errno << ", on port " << port); - } -} - -int32_t STReceiver::doTask() { - auto msg = std::unique_ptr(new UDPMessage()); - try { - while (*m_run) { - msg->clear(); - ACE_Time_Value timeout(2); // Timeout is relative time - if (msg->receiveFrom(m_io, &timeout)) { - if (msg->getCmd() == ADDR_REQUEST) { - msg->clear(); - msg->setMessage(m_addr); - msg->setCmd(ADDR_RESPONSE); - msg->send(m_io); - } else { - if (msg->length() > 0) { - m_queues->putInbound(msg.release()); - msg.reset(new UDPMessage()); - } - } - } - } - } catch (FwkException& ex) { - FWKSEVERE("STReceiver::doTask() caught exception: " << ex.what()); - } catch (...) { - FWKSEVERE("STReceiver::doTask() caught unknown exception"); - } - return 0; -} - -void STReceiver::initialize() { - int32_t result = -1; - ACE_INET_Addr addr(m_basePort, "localhost"); - result = m_io.open(addr); - if (result == 0) { - char hbuff[256]; - char* hst = &hbuff[0]; - char* fqdn = ACE_OS::getenv("GF_FQDN"); - if (fqdn) { - hst = fqdn; - } else { - addr.get_host_name(hbuff, 255); - } - char buff[1024]; - sprintf(buff, "%s:%u", hst, m_basePort); - m_addr = buff; - } - if (result < 0) { - FWKEXCEPTION("STReceiver::initialize failed to open io, " - << errno << ", on port " << m_basePort); - } -} - -int32_t Responder::doTask() { - try { - while (*m_run) { - UDPMessage* msg = m_queues->getOutbound(); - if (msg) { - msg->send(*m_io); - delete msg; - } - } - } catch (FwkException& ex) { - FWKSEVERE("Responder::doTask() caught exception: " << ex.what()); - } catch (...) { - FWKSEVERE("Responder::doTask() caught unknown exception"); - } - return 0; -} - -void Responder::initialize() { - int32_t result = -1; - int32_t tries = 100; - while ((result < 0) && (--tries > 0)) { - uint16_t port = ++m_offset + 111 + m_basePort; - result = m_io->open(ACE_INET_Addr(port, "localhost")); - if (result < 0) { - FWKWARN("Server failed to open io, " << errno << ", on port " << port); - } - } - if (result < 0) { - FWKEXCEPTION("Server failed to open io, " << errno); - } -} - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache diff --git a/tests/cpp/fwklib/UDPIpc.hpp b/tests/cpp/fwklib/UDPIpc.hpp deleted file mode 100644 index a8cd9be9fb..0000000000 --- a/tests/cpp/fwklib/UDPIpc.hpp +++ /dev/null @@ -1,301 +0,0 @@ -#pragma once - -#ifndef GEODE_FWKLIB_UDPIPC_H_ -#define GEODE_FWKLIB_UDPIPC_H_ - -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 -#include -#include - -#include -#include -#include -#include -#include - -#include "FwkLog.hpp" -#include "GsRandom.hpp" -#include "Service.hpp" -#include "config.h" - -#ifdef _WIN32 - -#define popen _popen -#define pclose _pclose -#define MODE "wt" - -#else // linux, et. al. - -#include -#define MODE "w" - -#endif // WIN32 - -namespace apache { -namespace geode { -namespace client { -namespace testframework { - -#define UDP_HEADER_SIZE 8 -#define UDP_MSG_TAG static_cast(189) - -enum UdpCmds { Null, ACK, ACK_REQUEST, ADDR_REQUEST, ADDR_RESPONSE }; - -typedef struct { - uint8_t tag; - uint8_t cmd; - uint16_t id; - uint32_t length; -} UdpHeader; - -class UDPMessage : public IPCMessage { - protected: - ACE_INET_Addr m_sender; - UdpHeader m_hdr; - - public: - UDPMessage() { - clearHdr(); - m_msg.clear(); - } - - explicit UDPMessage(UdpCmds cmd) { - clearHdr(); - m_msg.clear(); - setCmd(cmd); - } - - explicit UDPMessage(std::string content) : IPCMessage(content) { clearHdr(); } - - UDPMessage(UDPMessage& msg) : IPCMessage(msg.what()) { - clearHdr(); - setCmd(msg.getCmd()); - } - - ~UDPMessage() noexcept override = default; - - void setCmd(UdpCmds cmd) { m_hdr.cmd = cmd; } - - UdpCmds getCmd() { return static_cast(m_hdr.cmd); } - - ACE_INET_Addr& getSender() { return m_sender; } - - void setSender(ACE_INET_Addr& addr) { m_sender = addr; } - - bool receiveFrom(ACE_SOCK_Dgram& io, const ACE_Time_Value* timeout = nullptr); - - bool sendTo(ACE_SOCK_Dgram& io, ACE_INET_Addr& who); - - bool ping(ACE_SOCK_Dgram& io, ACE_INET_Addr& who); - - bool send(ACE_SOCK_Dgram& io); - - std::string dump(int32_t max = 0); - - bool needToAck() { return (m_hdr.cmd == ACK_REQUEST); } - - const char* cmdString(uint32_t cmd) { - const char* UdpStrings[] = {"Null", "ACK", "ACK_REQUEST", "ADDR_REQUEST", - "ADDR_RESPONSE"}; - if (cmd > 4) { - return "UNKNOWN"; - } - return UdpStrings[cmd]; - } - - void clearHdr() { - m_hdr.tag = UDP_MSG_TAG; - m_hdr.cmd = 0; - m_hdr.id = 0; - m_hdr.length = 0; - } - - virtual void clear() override { - clearHdr(); - m_msg.clear(); - } -}; - -class UDPMessageClient { - private: - ACE_INET_Addr m_server; - ACE_SOCK_Dgram m_io; - - public: - explicit UDPMessageClient(std::string server); - - ~UDPMessageClient() { m_io.close(); } - - ACE_SOCK_Dgram& getConn() { return m_io; } - - ACE_INET_Addr& getServer() { return m_server; } -}; - -class UDPMessageQueues : public SharedTaskObject { - private: - std::atomic m_cntInbound; - std::atomic m_cntOutbound; - std::atomic m_cntProcessed; - - SafeQueue m_inbound; - SafeQueue m_outbound; - - std::string m_label; - - public: - explicit UDPMessageQueues(std::string label) - : m_cntInbound(), m_cntOutbound(0), m_cntProcessed(0), m_label(label) {} - ~UDPMessageQueues() noexcept override { - FWKINFO(m_label << "MessageQueues::Inbound count: " << m_cntInbound); - FWKINFO(m_label << "MessageQueues::Processed count: " << m_cntProcessed); - FWKINFO(m_label << "MessageQueues::Outbound count: " << m_cntOutbound); - FWKINFO(m_label << "MessageQueues::Inbound still queued: " - << m_inbound.size()); - FWKINFO(m_label << "MessageQueues::Outbound still queued: " - << m_outbound.size()); - } - - void putInbound(UDPMessage* msg) { - m_inbound.enqueue(msg); - m_cntInbound++; - } - - void putOutbound(UDPMessage* msg) { - m_outbound.enqueue(msg); - m_cntProcessed++; - } - - UDPMessage* getInbound() { return m_inbound.dequeue(); } - - UDPMessage* getOutbound() { - UDPMessage* msg = m_outbound.dequeue(); - if (msg) { - m_cntOutbound++; - } - return msg; - } - - void initialize() override {} - void finalize() override {} -}; - -class Receiver : public ServiceTask { - private: - ACE_TSS m_io; - uint16_t m_basePort; - ACE_thread_t m_listener; - std::atomic m_offset{0}; - std::list m_addrs; - UDPMessageQueues* m_queues; - ACE_Thread_Mutex m_mutex; - - public: - Receiver(UDPMessageQueues* shared, uint16_t port) - : ServiceTask(shared), m_basePort(port), m_mutex() { - m_listener = ACE_Thread_NULL; - m_queues = dynamic_cast(m_shared); - } - - virtual ~Receiver() noexcept override = default; - - bool isListener() { return (m_listener == ACE_Thread::self()); } - - int32_t doTask() override; - - void initialize() override; - - void finalize() override { m_io->close(); } -}; - -class STReceiver : public ServiceTask { - private: - ACE_SOCK_Dgram m_io; - uint16_t m_basePort; - UDPMessageQueues* m_queues; - std::string m_addr; - - public: - STReceiver(UDPMessageQueues* shared, uint16_t port) - : ServiceTask(shared), m_basePort(port) { - m_queues = dynamic_cast(m_shared); - } - - ~STReceiver() noexcept override = default; - - int32_t doTask() override; - - void initialize() override; - - void finalize() override { m_io.close(); } -}; - -class Processor : public ServiceTask { - private: - UDPMessageQueues* m_queues; - // UNUSED bool m_sendReply; - - public: - explicit Processor(UDPMessageQueues* shared) : ServiceTask(shared) { - m_queues = dynamic_cast(m_shared); - } - - ~Processor() noexcept override = default; - - int32_t doTask() override { - while (*m_run) { - UDPMessage* msg = m_queues->getInbound(); - if (msg) { - m_queues->putOutbound(msg); - } - } - return 0; - } - void initialize() override {} - void finalize() override {} -}; - -class Responder : public ServiceTask { - private: - ACE_TSS m_io; - uint16_t m_basePort; - std::atomic m_offset{0}; - UDPMessageQueues* m_queues; - - public: - Responder(UDPMessageQueues* shared, uint16_t port) - : ServiceTask(shared), m_basePort(port) { - m_queues = dynamic_cast(m_shared); - } - - ~Responder() noexcept override = default; - - int32_t doTask() override; - - void initialize() override; - - void finalize() override { m_io->close(); } -}; - -} // namespace testframework -} // namespace client -} // namespace geode -} // namespace apache - -#endif // GEODE_FWKLIB_UDPIPC_H_