Fixes and improvs. Basic DRA feature.
[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 <TestCase.hpp>
25 #include <TestClock.hpp>
26 #include <Launcher.hpp>
27
28
29 class TestTimer;
30
31
32 TestManager::TestManager() :
33   anna::timex::TimeEventObserver("TestManager") {
34   a_timeController = NULL;
35   a_reportsDirectory = "./";
36   a_dumpReports = false;
37   a_synchronousAmount = 1;
38   a_poolRepeat = false;
39   a_inProgressCount = 0;
40   a_inProgressLimit = UINT_MAX; // no limit
41   a_clock = NULL;
42   //a_testPool.clear();
43   a_currentTestIt = a_testPool.end();
44 }
45
46 void TestManager::registerSessionId(const std::string &sessionId, const TestCase *testCase)  throw(anna::RuntimeException) {
47
48   std::map<std::string /* session id's */, TestCase*>::const_iterator it = a_sessionIdTestCaseMap.find(sessionId);
49   if (it != a_sessionIdTestCaseMap.end()) { // found
50     unsigned int id = it->second->getId();
51     if (id != testCase->getId()) {
52       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);
53     }
54   }
55   else {
56     a_sessionIdTestCaseMap[sessionId] = const_cast<TestCase*>(testCase);
57   }
58 }
59
60 TestTimer* TestManager::createTimer(TestCaseStep* testCaseStep, const anna::Millisecond &timeout, const TestTimer::Type::_v type)
61 throw(anna::RuntimeException) {
62   TestTimer* result(NULL);
63
64   if(a_timeController == NULL)
65     throw anna::RuntimeException("You must invoke 'setTimerController' with a not NULL timex engine", ANNA_FILE_LOCATION);
66
67   anna::Guard guard(a_timeController, "TestManager::createTimer");              // avoid interblocking
68   result = a_timers.create();
69   result->setType(type);
70   result->setId((anna::timex::TimeEvent::Id) testCaseStep);
71   result->setObserver(this);
72   result->setContext(testCaseStep);
73   result->setTimeout(timeout);
74
75   LOGDEBUG(
76     std::string msg("TestManager::createTimer | ");
77     msg += result->asString();
78     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
79   );
80
81   a_timeController->activate(result);
82   return result;
83 }
84
85 void TestManager::cancelTimer(TestTimer* timer)
86 throw() {
87   if(timer == NULL)
88     return;
89
90   LOGDEBUG(
91     std::string msg("TestManager::cancel | ");
92     msg += timer->asString();
93     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
94   );
95
96   try {
97     if(a_timeController == NULL)
98       a_timeController = anna::app::functions::component <anna::timex::Engine> (ANNA_FILE_LOCATION);
99
100     a_timeController->cancel(timer);
101   } catch(anna::RuntimeException& ex) {
102     ex.trace();
103   }
104 }
105
106 //------------------------------------------------------------------------------------------
107 // Se invoca automaticamente desde anna::timex::Engine
108 //------------------------------------------------------------------------------------------
109 void TestManager::release(anna::timex::TimeEvent* timeEvent)
110 throw() {
111   TestTimer* timer = static_cast <TestTimer*>(timeEvent);
112   timer->setContext(NULL);
113   a_timers.release(timer);
114 }
115
116 bool TestManager::configureTTPS(int testTicksPerSecond) throw() {
117
118   if (testTicksPerSecond  == 0) {
119     if (a_clock) {
120       a_timeController->cancel(a_clock);
121       LOGDEBUG(anna::Logger::debug("Testing timer clock stopped !", ANNA_FILE_LOCATION));
122     }
123     else {
124       LOGDEBUG(anna::Logger::debug("No testing timer started yet !", ANNA_FILE_LOCATION));
125     }
126     return true;
127   }
128   else if (testTicksPerSecond  < 0) {
129     LOGWARNING(anna::Logger::warning("Invalid 'ttps' provided", ANNA_FILE_LOCATION));
130     return false;
131   }
132
133   anna::Millisecond admlTimeInterval = anna::Millisecond(1000 / testTicksPerSecond);
134   a_synchronousAmount = 1;
135
136   if (admlTimeInterval < anna::Millisecond(1)) {
137     LOGWARNING(anna::Logger::warning("Not allowed to configure more than 1000 events per second for the time trigger testing system", ANNA_FILE_LOCATION));
138     return false;
139   }
140
141   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
142   const anna::Millisecond &admlMinResolution = my_app.getADMLMinResolution();
143
144   if (admlTimeInterval < admlMinResolution) {
145     int maximumObtained = 1000 / (int)admlMinResolution;
146     a_synchronousAmount = ceil((double)testTicksPerSecond/maximumObtained);
147     // calculate again:
148     admlTimeInterval = anna::Millisecond(a_synchronousAmount * 1000 / testTicksPerSecond);
149   }
150
151   if (a_synchronousAmount > 1) {
152     LOGWARNING(
153       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",
154                         testTicksPerSecond,
155                         a_synchronousAmount,
156                         admlTimeInterval.getValue(),
157                         a_synchronousAmount,
158                         1000/admlTimeInterval,
159                         a_synchronousAmount);
160
161       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
162     );
163   }
164
165   if (a_clock) {
166     a_clock->setTimeout(admlTimeInterval);
167   }
168   else {
169     a_clock = new TestClock("Testing clock", admlTimeInterval, this); // clock
170   }
171
172   if (!a_clock->isActive()) a_timeController->activate(a_clock);
173
174   return true;
175 }
176
177 bool TestManager::gotoTestCase(unsigned int id) throw() {
178   test_pool_it it = a_testPool.find(id);
179   if (it != a_testPool.end()) {
180     a_currentTestIt = it;
181     return true;
182   }
183
184   return false;
185 }
186
187 TestCase *TestManager::findTestCase(unsigned int id) const throw() { // id = -1 provides current test case triggered
188
189   if (!tests()) return NULL;
190   test_pool_it it = ((id != -1) ? a_testPool.find(id) : a_currentTestIt);
191   if (it != a_testPool.end()) return const_cast<TestCase*>(it->second);
192   return NULL;
193 }
194
195 TestCase *TestManager::getTestCase(unsigned int id) throw() {
196
197   test_pool_nc_it it = a_testPool.find(id);
198   if (it != a_testPool.end()) return it->second;
199
200   TestCase *result = new TestCase(id);
201   a_testPool[id] = result;
202   return result;
203 }
204
205 bool TestManager::clearPool() throw() {
206   if (!tests()) return false;
207   for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) delete it->second;
208   a_testPool.clear();
209   a_sessionIdTestCaseMap.clear();
210   a_currentTestIt = a_testPool.end();
211   configureTTPS(0); // stop
212   return true;
213 }
214
215 bool TestManager::resetPool(bool hard) throw() {
216   bool result = false; // any reset
217
218   if (!tests()) return result;
219   for (test_pool_nc_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
220     it->second->reset(hard);
221     result = true;
222   }
223   //a_sessionIdTestCaseMap.clear();
224   return result;
225 }
226
227 bool TestManager::tick() throw() {
228   LOGDEBUG(anna::Logger::debug("New test clock tick !", ANNA_FILE_LOCATION));
229
230   if (!tests()) {
231     LOGWARNING(anna::Logger::warning("Testing pool is empty. You need programming. Stopping test clock", ANNA_FILE_LOCATION));
232     return false;
233   }
234
235   // Synchronous sendings per tick:
236   int count = a_synchronousAmount;
237   while (count > 0) {
238     if (!nextTestCase()) return false; // stop the clock
239     count--;
240   }
241
242   return true;
243 }
244
245 bool TestManager::nextTestCase() throw() {
246
247   while (true) {
248
249     // Limit for in-progress test cases:
250     if (a_inProgressCount >= a_inProgressLimit) {
251       LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
252       return true; // wait next tick to release OTA test cases
253     }
254
255     // Next test case:
256     if (a_currentTestIt == a_testPool.end())
257       a_currentTestIt = a_testPool.begin();
258     else
259       a_currentTestIt++;
260
261     // Completed:
262     if (a_currentTestIt == a_testPool.end()) {
263       if (a_poolRepeat) {
264         LOGWARNING(anna::Logger::warning("Testing pool cycle completed. Repeat mode on. Restarting", ANNA_FILE_LOCATION));
265         //a_currentTestIt = a_testPool.begin();
266         return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
267                      // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
268       }
269       else {
270         LOGWARNING(anna::Logger::warning("Testing pool cycle completed. Repeat mode off. Suspending", ANNA_FILE_LOCATION));
271         return false;
272       }
273     }
274
275     // Soft reset to initialize already finished (in previous cycle) test cases:
276     a_currentTestIt->second->reset(false);
277
278     // Process test case:
279     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));
280     if (a_currentTestIt->second->getState() != TestCase::State::InProgress) {
281       a_currentTestIt->second->process();
282       return true; // is not probably to reach still In-Progress test cases from previous cycles due to the whole
283                    //  time for complete the test cases pool regarding the single test case lifetime. You shouldn't
284                    //  forget to programm a test case timeout with a reasonable value
285     }
286   }
287 }
288
289 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw() {
290   try {
291     sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
292   }
293   catch (anna::RuntimeException &ex) {
294     //ex.trace();
295     LOGWARNING(anna::Logger::warning("Cannot get the Session-Id from received DataBlock in order to identify the Test Case", ANNA_FILE_LOCATION));
296     return NULL;
297   }
298   std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
299   if (sessionIdIt != a_sessionIdTestCaseMap.end())
300     return sessionIdIt->second;
301
302   LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
303   return NULL;
304 }
305
306 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
307
308   // Testing disabled:
309   if (!tests()) return;
310
311   // Identify the test case:
312   std::string sessionId;
313   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
314   if (!tc) return;
315
316   // Work with Test case:
317   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
318   if (!tsw) { // store as 'uncovered'
319     std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
320
321     try {
322       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
323       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
324       codecMsg.decode(message);
325       hint += "\n"; hint += codecMsg.asXMLString();
326     }
327     catch (anna::RuntimeException &ex) {
328       ex.trace();
329       hint += "\n"; hint += ex.asString();
330     }
331     hint += "\n"; hint += clientSession->asString();
332
333     tc->addDebugSummaryHint(hint);
334   }
335   else {
336     tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
337   }
338 }
339
340 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
341
342   // Testing disabled:
343   if (!tests()) return;
344
345   // Identify the test case:
346   std::string sessionId;
347   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
348   if (!tc) return;
349
350   // Work with Test case:
351   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
352   if (!tsw) { // store as 'uncovered'
353     std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
354
355     try {
356       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
357       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
358       codecMsg.decode(message);
359       hint += "\n"; hint += codecMsg.asXMLString();
360     }
361     catch (anna::RuntimeException &ex) {
362       ex.trace();
363       hint += "\n"; hint += ex.asString();
364     }
365     hint += "\n"; hint += serverSession->asString();
366
367     tc->addDebugSummaryHint(hint);
368   }
369   else {
370     tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
371   }
372 }
373
374 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
375 throw() {
376   anna::xml::Node* result = parent->createChild("TestManager");
377
378   int poolSize = a_testPool.size();
379   result->createAttribute("NumberOfTestCases", poolSize);
380   result->createAttribute("PoolRepeat", (a_poolRepeat ? "yes":"no"));
381   result->createAttribute("InProgressCount", a_inProgressCount);
382   if (a_inProgressLimit == UINT_MAX)
383     result->createAttribute("InProgressLimit", "<no limit>");
384   else
385     result->createAttribute("InProgressLimit", a_inProgressLimit);
386   result->createAttribute("DumpReports", (a_dumpReports ? "yes":"no"));
387   result->createAttribute("ReportsDirectory", a_reportsDirectory);
388   if (a_clock) {
389     result->createAttribute("AsynchronousSendings", a_synchronousAmount);
390     int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
391     result->createAttribute("TicksPerSecond", ticksPerSecond);
392   }
393   if (a_currentTestIt != a_testPool.end()) {
394     result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
395   }
396   if (a_dumpReports && poolSize != 0) {
397     anna::xml::Node* testCases = result->createChild("TestCases");
398     for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
399       (*it).second->asXML(testCases);
400     }
401   }
402
403   return result;
404 }
405
406 std::string TestManager::asXMLString() const throw() {
407   anna::xml::Node root("root");
408   return anna::xml::Compiler().apply(asXML(&root));
409 }
410