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/helpers/dcca/functions.hpp>
20 #include <anna/diameter.comm/ClientSession.hpp>
21 #include <anna/diameter.comm/ServerSession.hpp>
24 #include <TestManager.hpp>
25 #include <TestClock.hpp>
26 #include <Launcher.hpp>
27 #include <OriginHost.hpp>
35 ///////////////////////////////////////////////////////////////////////////////////////////////////
36 void TestManager::StatSummary::newTCState(const TestCase::State::_v beginState, const TestCase::State::_v endState) throw() {
38 if ((beginState == TestCase::State::Initialized)&&(endState == TestCase::State::Initialized)) { // special case (new test case provisioning)
44 case TestCase::State::Initialized: a_initializedTcs--; break;
45 case TestCase::State::InProgress: a_inprogressTcs--; break;
46 case TestCase::State::Failed: a_failedTcs--; break;
47 case TestCase::State::Success: a_sucessTcs--; break;
51 case TestCase::State::Initialized: a_initializedTcs++; break;
52 case TestCase::State::InProgress: a_inprogressTcs++; break;
53 case TestCase::State::Failed: a_failedTcs++; break;
54 case TestCase::State::Success: a_sucessTcs++; break;
59 void TestManager::StatSummary::clear() throw() {
66 anna::xml::Node *TestManager::StatSummary::asXML(anna::xml::Node* parent) const throw() {
67 anna::xml::Node* result = parent->createChild("StatSummary");
69 anna::xml::Node* tcs = result->createChild("TestCasesCounts");
70 tcs->createAttribute("Total", a_initializedTcs + a_inprogressTcs + a_failedTcs + a_sucessTcs);
71 tcs->createAttribute("Initialized", a_initializedTcs);
72 tcs->createAttribute("InProgress", a_inprogressTcs);
73 tcs->createAttribute("Failed", a_failedTcs);
74 tcs->createAttribute("Success", a_sucessTcs);
78 ///////////////////////////////////////////////////////////////////////////////////////////////////
82 TestManager::TestManager() :
83 anna::timex::TimeEventObserver("TestManager") {
84 a_timeController = NULL;
85 a_reportsDirectory = "./";
87 a_dumpInProgressReports = false;
88 a_dumpInitializedReports = false;
89 a_dumpFailedReports = false;
90 a_dumpSuccessReports = false;
92 a_dumpHexMessages = false;
93 a_synchronousAmount = 1;
94 a_poolRepeats = 0; // repeat disabled by default
96 a_inProgressLimit = UINT_MAX; // no limit
99 //a_statSummary.clear();
100 a_currentTestIt = a_testPool.end();
103 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
105 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
106 if (it != a_sessionIdTestCaseMap.end()) { // found
107 unsigned int id = it->second->getId();
108 if (id != testCase->getId()) {
109 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);
113 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
114 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager::registerSessionId for test case (id = %llu): %s)", testCase->getId(), sessionId.c_str()), ANNA_FILE_LOCATION));
118 void TestManager::registerSubscriberId(const std::string &subscriberId, const TestCase *testCase) throw(anna::RuntimeException) {
120 std::map<std::string /* subscriber id's */, TestCase*>::const_iterator it = a_subscriberIdTestCaseMap.find(subscriberId);
121 if (it != a_subscriberIdTestCaseMap.end()) { // found
122 unsigned int id = it->second->getId();
123 if (id != testCase->getId()) {
124 throw anna::RuntimeException(anna::functions::asString("There is another test case (id = %llu) which registered such subscriberId: %s", id, subscriberId.c_str()), ANNA_FILE_LOCATION);
128 a_subscriberIdTestCaseMap[subscriberId] = const_cast<TestCase*>(testCase);
129 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager::registerSubscriberId for test case (id = %llu): %s)", testCase->getId(), subscriberId.c_str()), ANNA_FILE_LOCATION));
133 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
134 throw(anna::RuntimeException) {
135 TestTimer* result(NULL);
137 if(a_timeController == NULL)
138 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
140 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
141 result = a_timers.create();
142 result->setType(type);
143 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
144 result->setObserver(this);
145 result->setContext(testCaseStep);
146 result->setTimeout(timeout);
149 std::string msg("TestManager::createTimer | ");
150 msg += result->asString();
151 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
154 a_timeController->activate(result);
158 void TestManager::cancelTimer(TestTimer* timer)
164 std::string msg("TestManager::cancel | ");
165 msg += timer->asString();
166 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
170 if(a_timeController == NULL)
171 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
173 a_timeController->cancel(timer);
174 } catch(anna::RuntimeException& ex) {
179 //------------------------------------------------------------------------------------------
180 // Se invoca automaticamente desde anna::timex::Engine
181 //------------------------------------------------------------------------------------------
182 void TestManager::release(anna::timex::TimeEvent* timeEvent)
184 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
185 timer->setContext(NULL);
186 a_timers.release(timer);
189 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
191 if (testTicksPerSecond == 0) {
193 a_timeController->cancel(a_clock);
194 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
197 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
201 else if (testTicksPerSecond < 0) {
202 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
206 anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
207 a_synchronousAmount = 1;
209 if (admlTimeInterval < anna::Millisecond(1)) {
210 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
214 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
215 const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
217 if (admlTimeInterval < admlMinResolution) {
218 int maximumObtained = 1000 / (int)admlMinResolution;
219 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
221 admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
224 if (a_synchronousAmount > 1) {
226 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",
229 admlTimeInterval.getValue(),
231 1000/admlTimeInterval,
232 a_synchronousAmount);
234 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
239 a_clock->setTimeout(admlTimeInterval);
242 a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
245 if (!a_clock->isActive()) a_timeController->activate(a_clock);
250 bool TestManager::gotoTestCase(unsigned int id) throw() {
251 test_pool_it it = a_testPool.find(id);
252 if (it != a_testPool.end()) {
253 a_currentTestIt = it;
260 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
262 if (!tests()) return NULL;
263 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
264 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
268 TestCase *TestManager::getTestCase(unsigned int id) throw() {
270 test_pool_nc_it it = a_testPool.find(id);
271 if (it != a_testPool.end()) return it->second;
273 TestCase *result = new TestCase(id);
274 a_testPool[id] = result;
278 bool TestManager::clearPool() throw() {
279 if (!tests()) return false;
280 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
281 // TODO: stop the possible command threads or there will be a core dump
284 a_sessionIdTestCaseMap.clear();
285 a_subscriberIdTestCaseMap.clear();
286 a_currentTestIt = a_testPool.end();
288 configureTTPS(0); // stop
289 a_statSummary.clear();
293 bool TestManager::resetPool(bool hard) throw() {
294 bool result = false; // any reset
296 if (!tests()) return result;
297 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
298 if (it->second->reset(hard))
301 //a_sessionIdTestCaseMap.clear();
302 //a_subscriberIdTestCaseMap.clear();
306 bool TestManager::tick() throw() {
307 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
308 return execTestCases(a_synchronousAmount);
311 bool TestManager::execTestCases(int sync_amount) throw() {
314 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming", ANNA_FILE_LOCATION));
318 // Synchronous sendings per tick:
319 int count = sync_amount;
321 if (!nextTestCase()) return false; // stop the clock
328 bool TestManager::nextTestCase() throw() {
332 // Limit for in-progress test cases:
333 if (getInProgressCount() >= a_inProgressLimit) {
334 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
335 return true; // wait next tick to release OTA test cases
339 if (a_currentTestIt == a_testPool.end())
340 a_currentTestIt = a_testPool.begin();
345 if (a_currentTestIt == a_testPool.end()) {
346 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
347 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
353 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
354 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);
357 //a_currentTestIt = a_testPool.begin();
358 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
359 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
363 // Soft reset to initialize already finished (in previous cycle) test cases:
364 a_currentTestIt->second->reset(false);
366 // Process test case:
367 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));
368 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
369 a_currentTestIt->second->process();
370 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
371 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
372 // forget to programm a test case timeout with a reasonable value
377 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
379 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
381 catch (anna::RuntimeException &ex) {
383 LOGDEBUG(anna::Logger::debug("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
386 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
387 if (sessionIdIt != a_sessionIdTestCaseMap.end())
388 return sessionIdIt->second;
390 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
394 TestCase *TestManager::getTestCaseFromSubscriberId(const anna::DataBlock &message, std::string &subscriberId) throw() {
396 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(message, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
397 if (subscriberId == "") // try with IMSI
398 subscriberId = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(message, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
400 catch (anna::RuntimeException &ex) {
402 LOGDEBUG(anna::Logger::debug("Cannot get the Subscriber-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
405 std::map<std::string /* subscriber id's */, TestCase*>::const_iterator subscriberIdIt = a_subscriberIdTestCaseMap.find(subscriberId);
406 if (subscriberIdIt != a_subscriberIdTestCaseMap.end())
407 return subscriberIdIt->second;
409 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Cannot identify the Test Case for received Subscriber-Id: %s", subscriberId.c_str()), ANNA_FILE_LOCATION));
413 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
416 if (!tests()) return;
418 // Identify the test case:
419 std::string sessionId, subscriberId;
421 tc = getTestCaseFromSessionId(message, sessionId);
423 tc = getTestCaseFromSubscriberId(message, subscriberId);
425 LOGWARNING(anna::Logger::warning(anna::comm::functions::asText("Cannot identify the Test Case for the message received from server: ", message), ANNA_FILE_LOCATION)); // this should not appear
429 // Work with Test case:
430 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
431 if (!tsw) { // store as 'uncovered'
432 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
435 static anna::diameter::codec::Message codecMsg;
436 codecMsg.decode(message);
437 hint += "\n"; hint += codecMsg.asXMLString();
440 // std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
441 // if (messageOH != host->getName()) {
442 // 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));
445 catch (anna::RuntimeException &ex) {
447 hint += "\n"; hint += ex.asString();
449 hint += "\n"; hint += clientSession->asString();
451 tc->addDebugSummaryHint(hint);
454 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
459 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
462 if (!tests()) return;
464 // Identify the test case:
465 std::string sessionId, subscriberId;
467 tc = getTestCaseFromSessionId(message, sessionId);
469 tc = getTestCaseFromSubscriberId(message, subscriberId);
471 LOGWARNING(anna::Logger::warning(anna::comm::functions::asText("Cannot identify the Test Case for the message received from client: ", message), ANNA_FILE_LOCATION)); // this should not appear
475 // Work with Test case:
476 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
477 if (!tsw) { // store as 'uncovered'
478 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
481 static anna::diameter::codec::Message codecMsg;
482 codecMsg.decode(message);
483 hint += "\n"; hint += codecMsg.asXMLString();
486 // std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
487 // if (messageOH != host->getName()) {
488 // 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));
491 catch (anna::RuntimeException &ex) {
493 hint += "\n"; hint += ex.asString();
495 hint += "\n"; hint += serverSession->asString();
497 tc->addDebugSummaryHint(hint);
500 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
505 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
507 anna::xml::Node* result = parent->createChild("TestManager");
509 int poolSize = a_testPool.size();
510 result->createAttribute("NumberOfTestCases", poolSize);
511 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
512 else result->createAttribute("PoolRepeats", "disabled");
513 result->createAttribute("PoolCycle", a_poolCycle);
514 a_statSummary.asXML(result);
515 if (a_inProgressLimit == UINT_MAX)
516 result->createAttribute("InProgressLimit", "<no limit>");
518 result->createAttribute("InProgressLimit", a_inProgressLimit);
519 result->createAttribute("DumpInitializedReports", (a_dumpInitializedReports ? "yes":"no"));
520 result->createAttribute("DumpInProgressReports", (a_dumpInProgressReports ? "yes":"no"));
521 result->createAttribute("DumpFailedReports", (a_dumpFailedReports ? "yes":"no"));
522 result->createAttribute("DumpSuccessReports", (a_dumpSuccessReports ? "yes":"no"));
523 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
524 result->createAttribute("ReportsDirectory", a_reportsDirectory);
526 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
527 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
528 result->createAttribute("TicksPerSecond", ticksPerSecond);
530 if (a_currentTestIt != a_testPool.end()) {
531 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
534 anna::xml::Node* testCases = result->createChild("TestCases");
535 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
536 if (((*it).second->getState() == TestCase::State::Initialized) && (!getDumpInitializedReports())) continue;
537 if (((*it).second->getState() == TestCase::State::InProgress) && (!getDumpInProgressReports())) continue;
538 if (((*it).second->getState() == TestCase::State::Failed) && (!getDumpFailedReports())) continue;
539 if (((*it).second->getState() == TestCase::State::Success) && (!getDumpSuccessReports())) continue;
540 (*it).second->asXML(testCases);
547 std::string TestManager::asXMLString() const throw() {
548 anna::xml::Node root("root");
549 return anna::xml::Compiler().apply(asXML(&root));