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 <RealmNode.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 = "./";
85 a_dumpReports = false;
86 a_dumpHexMessages = false;
87 a_synchronousAmount = 1;
88 a_poolRepeats = 0; // repeat disabled by default
90 a_inProgressLimit = UINT_MAX; // no limit
93 a_currentTestIt = a_testPool.end();
96 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
98 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
99 if (it != a_sessionIdTestCaseMap.end()) { // found
100 unsigned int id = it->second->getId();
101 if (id != testCase->getId()) {
102 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);
106 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
110 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
111 throw(anna::RuntimeException) {
112 TestTimer* result(NULL);
114 if(a_timeController == NULL)
115 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
117 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
118 result = a_timers.create();
119 result->setType(type);
120 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
121 result->setObserver(this);
122 result->setContext(testCaseStep);
123 result->setTimeout(timeout);
126 std::string msg("TestManager::createTimer | ");
127 msg += result->asString();
128 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
131 a_timeController->activate(result);
135 void TestManager::cancelTimer(TestTimer* timer)
141 std::string msg("TestManager::cancel | ");
142 msg += timer->asString();
143 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
147 if(a_timeController == NULL)
148 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
150 a_timeController->cancel(timer);
151 } catch(anna::RuntimeException& ex) {
156 //------------------------------------------------------------------------------------------
157 // Se invoca automaticamente desde anna::timex::Engine
158 //------------------------------------------------------------------------------------------
159 void TestManager::release(anna::timex::TimeEvent* timeEvent)
161 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
162 timer->setContext(NULL);
163 a_timers.release(timer);
166 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
168 if (testTicksPerSecond == 0) {
170 a_timeController->cancel(a_clock);
171 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
174 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
178 else if (testTicksPerSecond < 0) {
179 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
183 anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
184 a_synchronousAmount = 1;
186 if (admlTimeInterval < anna::Millisecond(1)) {
187 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
191 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
192 const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
194 if (admlTimeInterval < admlMinResolution) {
195 int maximumObtained = 1000 / (int)admlMinResolution;
196 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
198 admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
201 if (a_synchronousAmount > 1) {
203 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",
206 admlTimeInterval.getValue(),
208 1000/admlTimeInterval,
209 a_synchronousAmount);
211 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
216 a_clock->setTimeout(admlTimeInterval);
219 a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
222 if (!a_clock->isActive()) a_timeController->activate(a_clock);
227 bool TestManager::gotoTestCase(unsigned int id) throw() {
228 test_pool_it it = a_testPool.find(id);
229 if (it != a_testPool.end()) {
230 a_currentTestIt = it;
237 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
239 if (!tests()) return NULL;
240 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
241 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
245 TestCase *TestManager::getTestCase(unsigned int id) throw() {
247 test_pool_nc_it it = a_testPool.find(id);
248 if (it != a_testPool.end()) return it->second;
250 TestCase *result = new TestCase(id);
251 a_testPool[id] = result;
255 bool TestManager::clearPool() throw() {
256 if (!tests()) return false;
257 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
258 // TODO: stop the possible command threads or there will be a core dump
261 a_sessionIdTestCaseMap.clear();
262 a_currentTestIt = a_testPool.end();
264 configureTTPS(0); // stop
265 a_statSummary.clear();
269 bool TestManager::resetPool(bool hard) throw() {
270 bool result = false; // any reset
272 if (!tests()) return result;
273 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
274 if (it->second->reset(hard))
277 //a_sessionIdTestCaseMap.clear();
281 bool TestManager::tick() throw() {
282 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
283 return execTestCases(a_synchronousAmount);
286 bool TestManager::execTestCases(int sync_amount) throw() {
289 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming", ANNA_FILE_LOCATION));
293 // Synchronous sendings per tick:
294 int count = sync_amount;
296 if (!nextTestCase()) return false; // stop the clock
303 bool TestManager::nextTestCase() throw() {
307 // Limit for in-progress test cases:
308 if (getInProgressCount() >= a_inProgressLimit) {
309 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
310 return true; // wait next tick to release OTA test cases
314 if (a_currentTestIt == a_testPool.end())
315 a_currentTestIt = a_testPool.begin();
320 if (a_currentTestIt == a_testPool.end()) {
321 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
322 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
328 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
329 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);
332 //a_currentTestIt = a_testPool.begin();
333 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
334 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
338 // Soft reset to initialize already finished (in previous cycle) test cases:
339 a_currentTestIt->second->reset(false);
341 // Process test case:
342 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));
343 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
344 a_currentTestIt->second->process();
345 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
346 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
347 // forget to programm a test case timeout with a reasonable value
352 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
354 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
356 catch (anna::RuntimeException &ex) {
358 LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
361 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
362 if (sessionIdIt != a_sessionIdTestCaseMap.end())
363 return sessionIdIt->second;
365 LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
369 void TestManager::receiveMessage(const anna::DataBlock &message, RealmNode *realm, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
372 if (!tests()) return;
374 // Identify the test case:
375 std::string sessionId;
376 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
379 // Work with Test case:
380 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
381 if (!tsw) { // store as 'uncovered'
382 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
385 static anna::diameter::codec::Message codecMsg;
386 codecMsg.decode(message);
387 hint += "\n"; hint += codecMsg.asXMLString();
389 // // Realm checking:
390 // std::string messageOR = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
391 // if (messageOR != realm->getName()) {
392 // LOGWARNING(anna::Logger::warning(anna::functions::asString("Received message from realm '%s', with different Origin-Realm: %s", realm->getName().c_str(), messageOR.c_str()), ANNA_FILE_LOCATION));
395 catch (anna::RuntimeException &ex) {
397 hint += "\n"; hint += ex.asString();
399 hint += "\n"; hint += clientSession->asString();
401 tc->addDebugSummaryHint(hint);
404 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
409 void TestManager::receiveMessage(const anna::DataBlock &message, RealmNode *realm, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
412 if (!tests()) return;
414 // Identify the test case:
415 std::string sessionId;
416 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
419 // Work with Test case:
420 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
421 if (!tsw) { // store as 'uncovered'
422 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
425 static anna::diameter::codec::Message codecMsg;
426 codecMsg.decode(message);
427 hint += "\n"; hint += codecMsg.asXMLString();
429 // // Realm checking:
430 // std::string messageOR = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
431 // if (messageOR != realm->getName()) {
432 // LOGWARNING(anna::Logger::warning(anna::functions::asString("Received message from realm '%s', with different Origin-Realm: %s", realm->getName().c_str(), messageOR.c_str()), ANNA_FILE_LOCATION));
435 catch (anna::RuntimeException &ex) {
437 hint += "\n"; hint += ex.asString();
439 hint += "\n"; hint += serverSession->asString();
441 tc->addDebugSummaryHint(hint);
444 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
449 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
451 anna::xml::Node* result = parent->createChild("TestManager");
453 int poolSize = a_testPool.size();
454 result->createAttribute("NumberOfTestCases", poolSize);
455 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
456 else result->createAttribute("PoolRepeats", "disabled");
457 result->createAttribute("PoolCycle", a_poolCycle);
458 a_statSummary.asXML(result);
459 if (a_inProgressLimit == UINT_MAX)
460 result->createAttribute("InProgressLimit", "<no limit>");
462 result->createAttribute("InProgressLimit", a_inProgressLimit);
463 result->createAttribute("DumpReports", (a_dumpReports ? "yes":"no"));
464 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
465 result->createAttribute("ReportsDirectory", a_reportsDirectory);
467 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
468 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
469 result->createAttribute("TicksPerSecond", ticksPerSecond);
471 if (a_currentTestIt != a_testPool.end()) {
472 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
474 if (a_dumpReports && poolSize != 0) {
475 anna::xml::Node* testCases = result->createChild("TestCases");
476 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
477 (*it).second->asXML(testCases);
484 std::string TestManager::asXMLString() const throw() {
485 anna::xml::Node root("root");
486 return anna::xml::Compiler().apply(asXML(&root));