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