1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
13 #include <anna/xml/Compiler.hpp>
14 #include <anna/xml/Node.hpp>
15 #include <anna/core/tracing/Logger.hpp>
16 #include <anna/app/functions.hpp>
17 #include <anna/timex/Engine.hpp>
18 #include <anna/diameter/helpers/base/functions.hpp>
19 #include <anna/diameter.comm/ClientSession.hpp>
20 #include <anna/diameter.comm/ServerSession.hpp>
23 #include <TestManager.hpp>
24 #include <TestClock.hpp>
25 #include <Launcher.hpp>
26 #include <OriginHost.hpp>
34 ///////////////////////////////////////////////////////////////////////////////////////////////////
35 void TestManager::StatSummary::newTCState(const TestCase::State::_v beginState, const TestCase::State::_v endState) throw() {
37 if ((beginState == TestCase::State::Initialized)&&(endState == TestCase::State::Initialized)) { // special case (new test case provisioning)
43 case TestCase::State::Initialized: a_initializedTcs--; break;
44 case TestCase::State::InProgress: a_inprogressTcs--; break;
45 case TestCase::State::Failed: a_failedTcs--; break;
46 case TestCase::State::Success: a_sucessTcs--; break;
50 case TestCase::State::Initialized: a_initializedTcs++; break;
51 case TestCase::State::InProgress: a_inprogressTcs++; break;
52 case TestCase::State::Failed: a_failedTcs++; break;
53 case TestCase::State::Success: a_sucessTcs++; break;
58 void TestManager::StatSummary::clear() throw() {
65 anna::xml::Node *TestManager::StatSummary::asXML(anna::xml::Node* parent) const throw() {
66 anna::xml::Node* result = parent->createChild("StatSummary");
68 anna::xml::Node* tcs = result->createChild("TestCasesCounts");
69 tcs->createAttribute("Total", a_initializedTcs + a_inprogressTcs + a_failedTcs + a_sucessTcs);
70 tcs->createAttribute("Initialized", a_initializedTcs);
71 tcs->createAttribute("InProgress", a_inprogressTcs);
72 tcs->createAttribute("Failed", a_failedTcs);
73 tcs->createAttribute("Success", a_sucessTcs);
77 ///////////////////////////////////////////////////////////////////////////////////////////////////
81 TestManager::TestManager() :
82 anna::timex::TimeEventObserver("TestManager") {
83 a_timeController = NULL;
84 a_reportsDirectory = "./";
86 a_dumpInProgressReports = false;
87 a_dumpInitializedReports = false;
88 a_dumpFailedReports = false;
89 a_dumpSuccessReports = false;
91 a_dumpHexMessages = false;
92 a_synchronousAmount = 1;
93 a_poolRepeats = 0; // repeat disabled by default
95 a_inProgressLimit = UINT_MAX; // no limit
98 a_currentTestIt = a_testPool.end();
101 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
103 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
104 if (it != a_sessionIdTestCaseMap.end()) { // found
105 unsigned int id = it->second->getId();
106 if (id != testCase->getId()) {
107 throw anna::RuntimeException(anna::functions::asString("There is another test case (id = %llu) which registered such sessionId: %s", id, sessionId.c_str()), ANNA_FILE_LOCATION);
111 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
115 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
116 throw(anna::RuntimeException) {
117 TestTimer* result(NULL);
119 if(a_timeController == NULL)
120 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
122 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
123 result = a_timers.create();
124 result->setType(type);
125 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
126 result->setObserver(this);
127 result->setContext(testCaseStep);
128 result->setTimeout(timeout);
131 std::string msg("TestManager::createTimer | ");
132 msg += result->asString();
133 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
136 a_timeController->activate(result);
140 void TestManager::cancelTimer(TestTimer* timer)
146 std::string msg("TestManager::cancel | ");
147 msg += timer->asString();
148 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
152 if(a_timeController == NULL)
153 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
155 a_timeController->cancel(timer);
156 } catch(anna::RuntimeException& ex) {
161 //------------------------------------------------------------------------------------------
162 // Se invoca automaticamente desde anna::timex::Engine
163 //------------------------------------------------------------------------------------------
164 void TestManager::release(anna::timex::TimeEvent* timeEvent)
166 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
167 timer->setContext(NULL);
168 a_timers.release(timer);
171 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
173 if (testTicksPerSecond == 0) {
175 a_timeController->cancel(a_clock);
176 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
179 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
183 else if (testTicksPerSecond < 0) {
184 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
188 anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
189 a_synchronousAmount = 1;
191 if (admlTimeInterval < anna::Millisecond(1)) {
192 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
196 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
197 const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
199 if (admlTimeInterval < admlMinResolution) {
200 int maximumObtained = 1000 / (int)admlMinResolution;
201 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
203 admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
206 if (a_synchronousAmount > 1) {
208 std::string msg = anna::functions::asString("Desired testing time trigger rate (%d events per second) requires more than one sending per event (%d every %lld milliseconds). Consider launch more instances with lower rate (for example %d ADML processes with %d ttps), or configure %d or more sockets to the remote endpoints to avoid burst sendings",
211 admlTimeInterval.getValue(),
213 1000/admlTimeInterval,
214 a_synchronousAmount);
216 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
221 a_clock->setTimeout(admlTimeInterval);
224 a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
227 if (!a_clock->isActive()) a_timeController->activate(a_clock);
232 bool TestManager::gotoTestCase(unsigned int id) throw() {
233 test_pool_it it = a_testPool.find(id);
234 if (it != a_testPool.end()) {
235 a_currentTestIt = it;
242 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
244 if (!tests()) return NULL;
245 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
246 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
250 TestCase *TestManager::getTestCase(unsigned int id) throw() {
252 test_pool_nc_it it = a_testPool.find(id);
253 if (it != a_testPool.end()) return it->second;
255 TestCase *result = new TestCase(id);
256 a_testPool[id] = result;
260 bool TestManager::clearPool() throw() {
261 if (!tests()) return false;
262 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
263 // TODO: stop the possible command threads or there will be a core dump
266 a_sessionIdTestCaseMap.clear();
267 a_currentTestIt = a_testPool.end();
269 configureTTPS(0); // stop
270 a_statSummary.clear();
274 bool TestManager::resetPool(bool hard) throw() {
275 bool result = false; // any reset
277 if (!tests()) return result;
278 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
279 if (it->second->reset(hard))
282 //a_sessionIdTestCaseMap.clear();
286 bool TestManager::tick() throw() {
287 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
288 return execTestCases(a_synchronousAmount);
291 bool TestManager::execTestCases(int sync_amount) throw() {
294 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming", ANNA_FILE_LOCATION));
298 // Synchronous sendings per tick:
299 int count = sync_amount;
301 if (!nextTestCase()) return false; // stop the clock
308 bool TestManager::nextTestCase() throw() {
312 // Limit for in-progress test cases:
313 if (getInProgressCount() >= a_inProgressLimit) {
314 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
315 return true; // wait next tick to release OTA test cases
319 if (a_currentTestIt == a_testPool.end())
320 a_currentTestIt = a_testPool.begin();
325 if (a_currentTestIt == a_testPool.end()) {
326 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
327 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
333 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
334 anna::Logger::warning(anna::functions::asString("Testing pool cycle %d completed (repeats configured: %d%s). Restarting for the %s cycle", a_poolCycle, a_poolRepeats, nolimit.c_str(), (a_poolRepeats == a_poolCycle) ? "last":"next"), ANNA_FILE_LOCATION);
337 //a_currentTestIt = a_testPool.begin();
338 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
339 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
343 // Soft reset to initialize already finished (in previous cycle) test cases:
344 a_currentTestIt->second->reset(false);
346 // Process test case:
347 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Processing test case id = %llu, currently '%s' state", a_currentTestIt->first, TestCase::asText(a_currentTestIt->second->getState())), ANNA_FILE_LOCATION));
348 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
349 a_currentTestIt->second->process();
350 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
351 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
352 // forget to programm a test case timeout with a reasonable value
357 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
359 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
361 catch (anna::RuntimeException &ex) {
363 LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
366 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
367 if (sessionIdIt != a_sessionIdTestCaseMap.end())
368 return sessionIdIt->second;
370 LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
374 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
377 if (!tests()) return;
379 // Identify the test case:
380 std::string sessionId;
381 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
384 // Work with Test case:
385 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
386 if (!tsw) { // store as 'uncovered'
387 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
390 static anna::diameter::codec::Message codecMsg;
391 codecMsg.decode(message);
392 hint += "\n"; hint += codecMsg.asXMLString();
395 // std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
396 // if (messageOH != host->getName()) {
397 // LOGWARNING(anna::Logger::warning(anna::functions::asString("Received message from host '%s', with different Origin-Host: %s", host->getName().c_str(), messageOH.c_str()), ANNA_FILE_LOCATION));
400 catch (anna::RuntimeException &ex) {
402 hint += "\n"; hint += ex.asString();
404 hint += "\n"; hint += clientSession->asString();
406 tc->addDebugSummaryHint(hint);
409 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
414 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
417 if (!tests()) return;
419 // Identify the test case:
420 std::string sessionId;
421 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
424 // Work with Test case:
425 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
426 if (!tsw) { // store as 'uncovered'
427 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
430 static anna::diameter::codec::Message codecMsg;
431 codecMsg.decode(message);
432 hint += "\n"; hint += codecMsg.asXMLString();
435 // std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
436 // if (messageOH != host->getName()) {
437 // LOGWARNING(anna::Logger::warning(anna::functions::asString("Received message from host '%s', with different Origin-Host: %s", host->getName().c_str(), messageOH.c_str()), ANNA_FILE_LOCATION));
440 catch (anna::RuntimeException &ex) {
442 hint += "\n"; hint += ex.asString();
444 hint += "\n"; hint += serverSession->asString();
446 tc->addDebugSummaryHint(hint);
449 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
454 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
456 anna::xml::Node* result = parent->createChild("TestManager");
458 int poolSize = a_testPool.size();
459 result->createAttribute("NumberOfTestCases", poolSize);
460 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
461 else result->createAttribute("PoolRepeats", "disabled");
462 result->createAttribute("PoolCycle", a_poolCycle);
463 a_statSummary.asXML(result);
464 if (a_inProgressLimit == UINT_MAX)
465 result->createAttribute("InProgressLimit", "<no limit>");
467 result->createAttribute("InProgressLimit", a_inProgressLimit);
468 result->createAttribute("DumpInitializedReports", (a_dumpInitializedReports ? "yes":"no"));
469 result->createAttribute("DumpInProgressReports", (a_dumpInProgressReports ? "yes":"no"));
470 result->createAttribute("DumpFailedReports", (a_dumpFailedReports ? "yes":"no"));
471 result->createAttribute("DumpSuccessReports", (a_dumpSuccessReports ? "yes":"no"));
472 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
473 result->createAttribute("ReportsDirectory", a_reportsDirectory);
475 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
476 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
477 result->createAttribute("TicksPerSecond", ticksPerSecond);
479 if (a_currentTestIt != a_testPool.end()) {
480 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
483 anna::xml::Node* testCases = result->createChild("TestCases");
484 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
485 if (((*it).second->getState() == TestCase::State::Initialized) && (!getDumpInitializedReports())) continue;
486 if (((*it).second->getState() == TestCase::State::InProgress) && (!getDumpInProgressReports())) continue;
487 if (((*it).second->getState() == TestCase::State::Failed) && (!getDumpFailedReports())) continue;
488 if (((*it).second->getState() == TestCase::State::Success) && (!getDumpSuccessReports())) continue;
489 (*it).second->asXML(testCases);
496 std::string TestManager::asXMLString() const throw() {
497 anna::xml::Node root("root");
498 return anna::xml::Compiler().apply(asXML(&root));