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