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