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