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