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