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