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>
27 #include <RealmNode.hpp>
33 TestManager::TestManager() :
34 anna::timex::TimeEventObserver("TestManager") {
35 a_timeController = NULL;
36 a_reportsDirectory = "./";
37 a_dumpReports = false;
38 a_dumpHexMessages = false;
39 a_synchronousAmount = 1;
40 a_poolRepeats = 0; // repeat disabled by default
42 a_inProgressCount = 0;
43 a_inProgressLimit = UINT_MAX; // no limit
46 a_currentTestIt = a_testPool.end();
49 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase) throw(anna::RuntimeException) {
51 std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
52 if (it != a_sessionIdTestCaseMap.end()) { // found
53 unsigned int id = it->second->getId();
54 if (id != testCase->getId()) {
55 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);
59 a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
63 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
64 throw(anna::RuntimeException) {
65 TestTimer* result(NULL);
67 if(a_timeController == NULL)
68 throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
70 anna::Guard guard(a_timeController, "TestManager::createTimer"); // avoid interblocking
71 result = a_timers.create();
72 result->setType(type);
73 result->setId((anna::timex::TimeEvent::Id) testCaseStep);
74 result->setObserver(this);
75 result->setContext(testCaseStep);
76 result->setTimeout(timeout);
79 std::string msg("TestManager::createTimer | ");
80 msg += result->asString();
81 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
84 a_timeController->activate(result);
88 void TestManager::cancelTimer(TestTimer* timer)
94 std::string msg("TestManager::cancel | ");
95 msg += timer->asString();
96 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
100 if(a_timeController == NULL)
101 a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
103 a_timeController->cancel(timer);
104 } catch(anna::RuntimeException& ex) {
109 //------------------------------------------------------------------------------------------
110 // Se invoca automaticamente desde anna::timex::Engine
111 //------------------------------------------------------------------------------------------
112 void TestManager::release(anna::timex::TimeEvent* timeEvent)
114 TestTimer* timer = static_cast <TestTimer*>(timeEvent);
115 timer->setContext(NULL);
116 a_timers.release(timer);
119 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
121 if (testTicksPerSecond == 0) {
123 a_timeController->cancel(a_clock);
124 LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
127 LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
131 else if (testTicksPerSecond < 0) {
132 LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
136 anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
137 a_synchronousAmount = 1;
139 if (admlTimeInterval < anna::Millisecond(1)) {
140 LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
144 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
145 const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
147 if (admlTimeInterval < admlMinResolution) {
148 int maximumObtained = 1000 / (int)admlMinResolution;
149 a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
151 admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
154 if (a_synchronousAmount > 1) {
156 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",
159 admlTimeInterval.getValue(),
161 1000/admlTimeInterval,
162 a_synchronousAmount);
164 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
169 a_clock->setTimeout(admlTimeInterval);
172 a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
175 if (!a_clock->isActive()) a_timeController->activate(a_clock);
180 bool TestManager::gotoTestCase(unsigned int id) throw() {
181 test_pool_it it = a_testPool.find(id);
182 if (it != a_testPool.end()) {
183 a_currentTestIt = it;
190 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
192 if (!tests()) return NULL;
193 test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
194 if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
198 TestCase *TestManager::getTestCase(unsigned int id) throw() {
200 test_pool_nc_it it = a_testPool.find(id);
201 if (it != a_testPool.end()) return it->second;
203 TestCase *result = new TestCase(id);
204 a_testPool[id] = result;
208 bool TestManager::clearPool() throw() {
209 if (!tests()) return false;
210 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
212 a_sessionIdTestCaseMap.clear();
213 a_currentTestIt = a_testPool.end();
215 configureTTPS(0); // stop
219 bool TestManager::resetPool(bool hard) throw() {
220 bool result = false; // any reset
222 if (!tests()) return result;
223 for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
224 if (it->second->reset(hard))
227 //a_sessionIdTestCaseMap.clear();
231 bool TestManager::tick() throw() {
232 LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
235 LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming. Stopping test clock", ANNA_FILE_LOCATION));
239 // Synchronous sendings per tick:
240 int count = a_synchronousAmount;
242 if (!nextTestCase()) return false; // stop the clock
249 bool TestManager::nextTestCase() throw() {
253 // Limit for in-progress test cases:
254 if (a_inProgressCount >= a_inProgressLimit) {
255 LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
256 return true; // wait next tick to release OTA test cases
260 if (a_currentTestIt == a_testPool.end())
261 a_currentTestIt = a_testPool.begin();
266 if (a_currentTestIt == a_testPool.end()) {
267 if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
268 LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
274 std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
275 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);
278 //a_currentTestIt = a_testPool.begin();
279 return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
280 // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
284 // Soft reset to initialize already finished (in previous cycle) test cases:
285 a_currentTestIt->second->reset(false);
287 // Process test case:
288 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));
289 if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
290 a_currentTestIt->second->process();
291 return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
292 // time for complete the test cases pool regarding the single test case lifetime. You shouldn't
293 // forget to programm a test case timeout with a reasonable value
298 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
300 sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
302 catch (anna::RuntimeException &ex) {
304 LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
307 std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
308 if (sessionIdIt != a_sessionIdTestCaseMap.end())
309 return sessionIdIt->second;
311 LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
315 void TestManager::receiveMessage(const anna::DataBlock &message, RealmNode *realm, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
318 if (!tests()) return;
320 // Identify the test case:
321 std::string sessionId;
322 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
325 // Work with Test case:
326 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
327 if (!tsw) { // store as 'uncovered'
328 std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
331 static anna::diameter::codec::Message codecMsg;
332 codecMsg.decode(message);
333 hint += "\n"; hint += codecMsg.asXMLString();
335 // // Realm checking:
336 // std::string messageOR = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
337 // if (messageOR != realm->getName()) {
338 // 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));
341 catch (anna::RuntimeException &ex) {
343 hint += "\n"; hint += ex.asString();
345 hint += "\n"; hint += clientSession->asString();
347 tc->addDebugSummaryHint(hint);
350 tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
355 void TestManager::receiveMessage(const anna::DataBlock &message, RealmNode *realm, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
358 if (!tests()) return;
360 // Identify the test case:
361 std::string sessionId;
362 TestCase *tc = getTestCaseFromSessionId(message, sessionId);
365 // Work with Test case:
366 TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
367 if (!tsw) { // store as 'uncovered'
368 std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
371 static anna::diameter::codec::Message codecMsg;
372 codecMsg.decode(message);
373 hint += "\n"; hint += codecMsg.asXMLString();
375 // // Realm checking:
376 // std::string messageOR = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
377 // if (messageOR != realm->getName()) {
378 // 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));
381 catch (anna::RuntimeException &ex) {
383 hint += "\n"; hint += ex.asString();
385 hint += "\n"; hint += serverSession->asString();
387 tc->addDebugSummaryHint(hint);
390 tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
395 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
397 anna::xml::Node* result = parent->createChild("TestManager");
399 int poolSize = a_testPool.size();
400 result->createAttribute("NumberOfTestCases", poolSize);
401 if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
402 else result->createAttribute("PoolRepeats", "disabled");
403 result->createAttribute("PoolCycle", a_poolCycle);
404 result->createAttribute("InProgressCount", a_inProgressCount);
405 if (a_inProgressLimit == UINT_MAX)
406 result->createAttribute("InProgressLimit", "<no limit>");
408 result->createAttribute("InProgressLimit", a_inProgressLimit);
409 result->createAttribute("DumpReports", (a_dumpReports ? "yes":"no"));
410 result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
411 result->createAttribute("ReportsDirectory", a_reportsDirectory);
413 result->createAttribute("AsynchronousSendings", a_synchronousAmount);
414 int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
415 result->createAttribute("TicksPerSecond", ticksPerSecond);
417 if (a_currentTestIt != a_testPool.end()) {
418 result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
420 if (a_dumpReports && poolSize != 0) {
421 anna::xml::Node* testCases = result->createChild("TestCases");
422 for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
423 (*it).second->asXML(testCases);
430 std::string TestManager::asXMLString() const throw() {
431 anna::xml::Node root("root");
432 return anna::xml::Compiler().apply(asXML(&root));