75955ce90ae182ea109eca6a6f86b2b1b7188ff1
[anna.git] / example / diameter / launcher / testing / TestManager.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
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 //
7
8 // Standard
9 #include <climits>
10 #include <cmath>
11
12 // Project
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>
21
22 // Process
23 #include <TestManager.hpp>
24 #include <TestClock.hpp>
25 #include <Launcher.hpp>
26 #include <OriginHost.hpp>
27
28
29 class TestTimer;
30
31
32
33
34 ///////////////////////////////////////////////////////////////////////////////////////////////////
35 void TestManager::StatSummary::newTCState(const TestCase::State::_v beginState, const TestCase::State::_v endState) throw() {
36
37   if ((beginState == TestCase::State::Initialized)&&(endState == TestCase::State::Initialized)) { // special case (new test case provisioning)
38     a_initializedTcs++;
39     return;
40   }
41
42   switch (beginState) {
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;
47   default: break;
48   }
49   switch (endState) {
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;
54   default: break;
55   }
56 }
57
58 void TestManager::StatSummary::clear() throw() {
59   a_initializedTcs = 0;
60   a_inprogressTcs = 0;
61   a_failedTcs = 0;
62   a_sucessTcs = 0;
63 }
64
65 anna::xml::Node *TestManager::StatSummary::asXML(anna::xml::Node* parent) const throw() {
66   anna::xml::Node* result = parent->createChild("StatSummary");
67
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);
74
75   return result;
76 }
77 ///////////////////////////////////////////////////////////////////////////////////////////////////
78
79
80
81 TestManager::TestManager() :
82       anna::timex::TimeEventObserver("TestManager") {
83   a_timeController = NULL;
84   a_reportsDirectory = "./";
85
86   a_dumpInProgressReports = false;
87   a_dumpInitializedReports = false;
88   a_dumpFailedReports = false;
89   a_dumpSuccessReports = false;
90
91   a_dumpHexMessages = false;
92   a_synchronousAmount = 1;
93   a_poolRepeats = 0; // repeat disabled by default
94   a_poolCycle = 1;
95   a_inProgressLimit = UINT_MAX; // no limit
96   a_clock = NULL;
97   //a_testPool.clear();
98   //a_statSummary.clear();
99   a_currentTestIt = a_testPool.end();
100 }
101
102 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase)  throw(anna::RuntimeException) {
103
104   std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
105   if (it != a_sessionIdTestCaseMap.end()) { // found
106     unsigned int id = it->second->getId();
107     if (id != testCase->getId()) {
108       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);
109     }
110   }
111   else {
112     a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
113     LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager::registerSessionId for test case (id = %llu): %s)", testCase->getId(), sessionId.c_str()), ANNA_FILE_LOCATION));
114   }
115 }
116
117 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
118 throw(anna::RuntimeException) {
119   TestTimer* result(NULL);
120
121   if(a_timeController == NULL)
122     throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
123
124   anna::Guard guard(a_timeController, "TestManager::createTimer");              // avoid interblocking
125   result = a_timers.create();
126   result->setType(type);
127   result->setId((anna::timex::TimeEvent::Id) testCaseStep);
128   result->setObserver(this);
129   result->setContext(testCaseStep);
130   result->setTimeout(timeout);
131
132   LOGDEBUG(
133       std::string msg("TestManager::createTimer | ");
134   msg += result->asString();
135   anna::Logger::debug(msg, ANNA_FILE_LOCATION);
136   );
137
138   a_timeController->activate(result);
139   return result;
140 }
141
142 void TestManager::cancelTimer(TestTimer* timer)
143 throw() {
144   if(timer == NULL)
145     return;
146
147   LOGDEBUG(
148       std::string msg("TestManager::cancel | ");
149   msg += timer->asString();
150   anna::Logger::debug(msg, ANNA_FILE_LOCATION);
151   );
152
153   try {
154     if(a_timeController == NULL)
155       a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
156
157     a_timeController->cancel(timer);
158   } catch(anna::RuntimeException& ex) {
159     ex.trace();
160   }
161 }
162
163 //------------------------------------------------------------------------------------------
164 // Se invoca automaticamente desde anna::timex::Engine
165 //------------------------------------------------------------------------------------------
166 void TestManager::release(anna::timex::TimeEvent* timeEvent)
167 throw() {
168   TestTimer* timer = static_cast <TestTimer*>(timeEvent);
169   timer->setContext(NULL);
170   a_timers.release(timer);
171 }
172
173 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
174
175   if (testTicksPerSecond  == 0) {
176     if (a_clock) {
177       a_timeController->cancel(a_clock);
178       LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
179     }
180     else {
181       LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
182     }
183     return true;
184   }
185   else if (testTicksPerSecond  < 0) {
186     LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
187     return false;
188   }
189
190   anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
191   a_synchronousAmount = 1;
192
193   if (admlTimeInterval < anna::Millisecond(1)) {
194     LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for for triggering testing system", ANNA_FILE_LOCATION));
195     return false;
196   }
197
198   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
199   const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
200
201   if (admlTimeInterval < admlMinResolution) {
202     int maximumObtained = 1000 / (int)admlMinResolution;
203     a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
204     // calculate again:
205     admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
206   }
207
208   if (a_synchronousAmount > 1) {
209     LOGWARNING(
210         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             testTicksPerSecond,
212             a_synchronousAmount,
213             admlTimeInterval.getValue(),
214             a_synchronousAmount,
215             1000/admlTimeInterval,
216             a_synchronousAmount);
217
218     anna::Logger::warning(msg, ANNA_FILE_LOCATION);
219     );
220   }
221
222   if (a_clock) {
223     a_clock->setTimeout(admlTimeInterval);
224   }
225   else {
226     a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
227   }
228
229   if (!a_clock->isActive()) a_timeController->activate(a_clock);
230
231   return true;
232 }
233
234 bool TestManager::gotoTestCase(unsigned int id) throw() {
235   test_pool_it it = a_testPool.find(id);
236   if (it != a_testPool.end()) {
237     a_currentTestIt = it;
238     return true;
239   }
240
241   return false;
242 }
243
244 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
245
246   if (!tests()) return NULL;
247   test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
248   if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
249   return NULL;
250 }
251
252 TestCase *TestManager::getTestCase(unsigned int id) throw() {
253
254   test_pool_nc_it it = a_testPool.find(id);
255   if (it != a_testPool.end()) return it->second;
256
257   TestCase *result = new TestCase(id);
258   a_testPool[id] = result;
259   return result;
260 }
261
262 bool TestManager::clearPool() throw() {
263   if (!tests()) return false;
264   for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
265   // TODO: stop the possible command threads or there will be a core dump
266
267   a_testPool.clear();
268   a_sessionIdTestCaseMap.clear();
269   a_currentTestIt = a_testPool.end();
270   a_poolCycle = 1;
271   configureTTPS(0); // stop
272   a_statSummary.clear();
273   return true;
274 }
275
276 bool TestManager::resetPool(bool hard) throw() {
277   bool result = false; // any reset
278
279   if (!tests()) return result;
280   for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
281     if (it->second->reset(hard))
282       result = true;
283   }
284   //a_sessionIdTestCaseMap.clear();
285   return result;
286 }
287
288 bool TestManager::tick() throw() {
289   LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
290   return execTestCases(a_synchronousAmount);
291 }
292
293 bool TestManager::execTestCases(int sync_amount) throw() {
294
295   if (!tests()) {
296     LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming", ANNA_FILE_LOCATION));
297     return false;
298   }
299
300   // Synchronous sendings per tick:
301   int count = sync_amount;
302   while (count > 0) {
303     if (!nextTestCase()) return false; // stop the clock
304     count--;
305   }
306
307   return true;
308 }
309
310 bool TestManager::nextTestCase() throw() {
311
312   while (true) {
313
314     // Limit for in-progress test cases:
315     if (getInProgressCount() >= a_inProgressLimit) {
316       LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
317       return true; // wait next tick to release OTA test cases
318     }
319
320     // Next test case:
321     if (a_currentTestIt == a_testPool.end())
322       a_currentTestIt = a_testPool.begin();
323     else
324       a_currentTestIt++;
325
326     // Completed:
327     if (a_currentTestIt == a_testPool.end()) {
328       if ((a_poolCycle > a_poolRepeats) && (a_poolRepeats != -1)) {
329         LOGWARNING(anna::Logger::warning("Testing pool cycle completed. No remaining repeat cycles left. Suspending", ANNA_FILE_LOCATION));
330         a_poolCycle = 1;
331         return false;
332       }
333       else {
334         LOGWARNING(
335             std::string nolimit = (a_poolRepeats != -1) ? "":" [no limit]";
336         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         );
338         a_poolCycle++;
339         //a_currentTestIt = a_testPool.begin();
340         return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
341         // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
342       }
343     }
344
345     // Soft reset to initialize already finished (in previous cycle) test cases:
346     a_currentTestIt->second->reset(false);
347
348     // Process test case:
349     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));
350     if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
351       a_currentTestIt->second->process();
352       return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
353       //  time for complete the test cases pool regarding the single test case lifetime. You shouldn't
354       //  forget to programm a test case timeout with a reasonable value
355     }
356   }
357 }
358
359 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
360   try {
361     sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
362   }
363   catch (anna::RuntimeException &ex) {
364     //ex.trace();
365     LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
366     return NULL;
367   }
368   std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
369   if (sessionIdIt != a_sessionIdTestCaseMap.end())
370     return sessionIdIt->second;
371
372   LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
373   return NULL;
374 }
375
376 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
377
378   // Testing disabled:
379   if (!tests()) return;
380
381   // Identify the test case:
382   std::string sessionId;
383   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
384   if (!tc) return;
385
386   // Work with Test case:
387   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
388   if (!tsw) { // store as 'uncovered'
389     std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
390
391     try {
392       static anna::diameter::codec::Message codecMsg;
393       codecMsg.decode(message);
394       hint += "\n"; hint += codecMsg.asXMLString();
395
396       //      // Host checking:
397       //      std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
398       //      if (messageOH != host->getName()) {
399       //        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       //      }
401     }
402     catch (anna::RuntimeException &ex) {
403       ex.trace();
404       hint += "\n"; hint += ex.asString();
405     }
406     hint += "\n"; hint += clientSession->asString();
407
408     tc->addDebugSummaryHint(hint);
409   }
410   else {
411     tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
412     tc->process();
413   }
414 }
415
416 void TestManager::receiveMessage(const anna::DataBlock &message, OriginHost *host, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
417
418   // Testing disabled:
419   if (!tests()) return;
420
421   // Identify the test case:
422   std::string sessionId;
423   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
424   if (!tc) return;
425
426   // Work with Test case:
427   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
428   if (!tsw) { // store as 'uncovered'
429     std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
430
431     try {
432       static anna::diameter::codec::Message codecMsg;
433       codecMsg.decode(message);
434       hint += "\n"; hint += codecMsg.asXMLString();
435
436       //      // Host checking:
437       //      std::string messageOH = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
438       //      if (messageOH != host->getName()) {
439       //        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       //      }
441     }
442     catch (anna::RuntimeException &ex) {
443       ex.trace();
444       hint += "\n"; hint += ex.asString();
445     }
446     hint += "\n"; hint += serverSession->asString();
447
448     tc->addDebugSummaryHint(hint);
449   }
450   else {
451     tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
452     tc->process();
453   }
454 }
455
456 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
457 throw() {
458   anna::xml::Node* result = parent->createChild("TestManager");
459
460   int poolSize = a_testPool.size();
461   result->createAttribute("NumberOfTestCases", poolSize);
462   if (a_poolRepeats) result->createAttribute("PoolRepeats", a_poolRepeats);
463   else result->createAttribute("PoolRepeats", "disabled");
464   result->createAttribute("PoolCycle", a_poolCycle);
465   a_statSummary.asXML(result);
466   if (a_inProgressLimit == UINT_MAX)
467     result->createAttribute("InProgressLimit", "<no limit>");
468   else
469     result->createAttribute("InProgressLimit", a_inProgressLimit);
470   result->createAttribute("DumpInitializedReports", (a_dumpInitializedReports ? "yes":"no"));
471   result->createAttribute("DumpInProgressReports", (a_dumpInProgressReports ? "yes":"no"));
472   result->createAttribute("DumpFailedReports", (a_dumpFailedReports ? "yes":"no"));
473   result->createAttribute("DumpSuccessReports", (a_dumpSuccessReports ? "yes":"no"));
474   result->createAttribute("DumpHexMessages", (a_dumpHexMessages ? "yes":"no"));
475   result->createAttribute("ReportsDirectory", a_reportsDirectory);
476   if (a_clock) {
477     result->createAttribute("AsynchronousSendings", a_synchronousAmount);
478     int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
479     result->createAttribute("TicksPerSecond", ticksPerSecond);
480   }
481   if (a_currentTestIt != a_testPool.end()) {
482     result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
483   }
484   if (poolSize != 0) {
485     anna::xml::Node* testCases = result->createChild("TestCases");
486     for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
487       if (((*it).second->getState() == TestCase::State::Initialized) && (!getDumpInitializedReports())) continue;
488       if (((*it).second->getState() == TestCase::State::InProgress) && (!getDumpInProgressReports())) continue;
489       if (((*it).second->getState() == TestCase::State::Failed) && (!getDumpFailedReports())) continue;
490       if (((*it).second->getState() == TestCase::State::Success) && (!getDumpSuccessReports())) continue;
491       (*it).second->asXML(testCases);
492     }
493   }
494
495   return result;
496 }
497
498 std::string TestManager::asXMLString() const throw() {
499   anna::xml::Node root("root");
500   return anna::xml::Compiler().apply(asXML(&root));
501 }
502