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