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 <TestCase.hpp>
25 #include <TestClock.hpp>
26 #include <Launcher.hpp>
32 TestManager::TestManager() :
33 anna::timex::TimeEventObserver("TestManager") {
34 a_timeController = NULL;
35 a_reportsDirectory = "./";
36 a_dumpReports = false;
37 a_dumpHexMessages = false;
38 a_synchronousAmount = 1;
39 a_poolRepeats = 0; // repeat disabled by default
41 a_inProgressCount = 0;
42 a_inProgressLimit = UINT_MAX; // no limit
45 a_currentTestIt = a_testPool.end();
48 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
50 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
51 if (it != a_sessionIdTestCaseMap.end()) { // found
52 unsigned int id = it->second->getId();
53 if (id != testCase->getId()) {
54 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);
58 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
62 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
63 throw(anna::RuntimeException) {
64 TestTimer* result(NULL);
66 if(a_timeController == NULL)
67 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
69 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
70 result = a_timers.create();
71 result->setType(type);
72 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
73 result->setObserver(this);
74 result->setContext(testCaseStep);
75 result->setTimeout(timeout);
78 std::string msg("TestManager::createTimer | ");
79 msg += result->asString();
80 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
83 a_timeController->activate(result);
87 void TestManager::cancelTimer(TestTimer* timer)
93 std::string msg("TestManager::cancel | ");
94 msg += timer->asString();
95 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
99 if(a_timeController == NULL)
100 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
102 a_timeController->cancel(timer);
103 } catch(anna::RuntimeException& ex) {
108 //------------------------------------------------------------------------------------------
109 // Se invoca automaticamente desde anna::timex::Engine
110 //------------------------------------------------------------------------------------------
111 void TestManager::release(anna::timex::TimeEvent* timeEvent)
113 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
114 timer->setContext(NULL);
115 a_timers.release(timer);
118 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
120 if (testTicksPerSecond == 0) {
122 a_timeController->cancel(a_clock);
123 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
126 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
130 else if (testTicksPerSecond < 0) {
131 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
135 anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
136 a_synchronousAmount = 1;
138 if (admlTimeInterval < anna::Millisecond(1)) {
139 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
143 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
144 const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
146 if (admlTimeInterval < admlMinResolution) {
147 int maximumObtained = 1000 / (int)admlMinResolution;
148 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
150 admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
153 if (a_synchronousAmount > 1) {
155 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",
158 admlTimeInterval.getValue(),
160 1000/admlTimeInterval,
161 a_synchronousAmount);
163 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
168 a_clock->setTimeout(admlTimeInterval);
171 a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
174 if (!a_clock->isActive()) a_timeController->activate(a_clock);
179 bool TestManager::gotoTestCase(unsigned int id) throw() {
180 test_pool_it it = a_testPool.find(id);
181 if (it != a_testPool.end()) {
182 a_currentTestIt = it;
189 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
191 if (!tests()) return NULL;
192 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
193 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
197 TestCase *TestManager::getTestCase(unsigned int id) throw() {
199 test_pool_nc_it it = a_testPool.find(id);
200 if (it != a_testPool.end()) return it->second;
202 TestCase *result = new TestCase(id);
203 a_testPool[id] = result;
207 bool TestManager::clearPool() throw() {
208 if (!tests()) return false;
209 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
211 a_sessionIdTestCaseMap.clear();
212 a_currentTestIt = a_testPool.end();
214 configureTTPS(0); // stop
218 bool TestManager::resetPool(bool hard) throw() {
219 bool result = false; // any reset
221 if (!tests()) return result;
222 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
223 it->second->reset(hard);
226 //a_sessionIdTestCaseMap.clear();
230 bool TestManager::tick() throw() {
231 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
234 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming. Stopping test clock", ANNA_FILE_LOCATION));
238 // Synchronous sendings per tick:
239 int count = a_synchronousAmount;
241 if (!nextTestCase()) return false; // stop the clock
248 bool TestManager::nextTestCase() throw() {
252 // Limit for in-progress test cases:
253 if (a_inProgressCount >= a_inProgressLimit) {
254 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
255 return true; // wait next tick to release OTA test cases
259 if (a_currentTestIt == a_testPool.end())
260 a_currentTestIt = a_testPool.begin();
265 if (a_currentTestIt == a_testPool.end()) {
266 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
267 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
273 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
274 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);
277 //a_currentTestIt = a_testPool.begin();
278 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
279 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
283 // Soft reset to initialize already finished (in previous cycle) test cases:
284 a_currentTestIt->second->reset(false);
286 // Process test case:
287 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));
288 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
289 a_currentTestIt->second->process();
290 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
291 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
292 // forget to programm a test case timeout with a reasonable value
297 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
299 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
301 catch (anna::RuntimeException &ex) {
303 LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
306 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
307 if (sessionIdIt != a_sessionIdTestCaseMap.end())
308 return sessionIdIt->second;
310 LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
314 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
317 if (!tests()) return;
319 // Identify the test case:
320 std::string sessionId;
321 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
324 // Work with Test case:
325 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
326 if (!tsw) { // store as 'uncovered'
327 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
330 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
331 static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
332 codecMsg.decode(message);
333 hint += "\n"; hint += codecMsg.asXMLString();
335 catch (anna::RuntimeException &ex) {
337 hint += "\n"; hint += ex.asString();
339 hint += "\n"; hint += clientSession->asString();
341 tc->addDebugSummaryHint(hint);
344 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
348 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
351 if (!tests()) return;
353 // Identify the test case:
354 std::string sessionId;
355 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
358 // Work with Test case:
359 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
360 if (!tsw) { // store as 'uncovered'
361 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
364 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
365 static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
366 codecMsg.decode(message);
367 hint += "\n"; hint += codecMsg.asXMLString();
369 catch (anna::RuntimeException &ex) {
371 hint += "\n"; hint += ex.asString();
373 hint += "\n"; hint += serverSession->asString();
375 tc->addDebugSummaryHint(hint);
378 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
382 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
384 anna::xml::Node* result = parent->createChild("TestManager");
386 int poolSize = a_testPool.size();
387 result->createAttribute("NumberOfTestCases", poolSize);
388 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
389 else result->createAttribute("PoolRepeats", "disabled");
390 result->createAttribute("PoolCycle", a_poolCycle);
391 result->createAttribute("InProgressCount", a_inProgressCount);
392 if (a_inProgressLimit == UINT_MAX)
393 result->createAttribute("InProgressLimit", "<no limit>");
395 result->createAttribute("InProgressLimit", a_inProgressLimit);
396 result->createAttribute("DumpReports", (a_dumpReports ? "yes":"no"));
397 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
398 result->createAttribute("ReportsDirectory", a_reportsDirectory);
400 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
401 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
402 result->createAttribute("TicksPerSecond", ticksPerSecond);
404 if (a_currentTestIt != a_testPool.end()) {
405 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
407 if (a_dumpReports && poolSize != 0) {
408 anna::xml::Node* testCases = result->createChild("TestCases");
409 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
410 (*it).second->asXML(testCases);
417 std::string TestManager::asXMLString() const throw() {
418 anna::xml::Node root("root");
419 return anna::xml::Compiler().apply(asXML(&root));