ca45e9c3199969a6dd48103bea28aab5272208a4
[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   int count = a_synchronousAmount;
236   while (count > 0) {
237     if (!nextTestCase()) return false; // stop the clock
238     count--;
239   }
240
241   return true;
242 }
243
244 bool TestManager::nextTestCase() throw() {
245
246   while (true) {
247
248     // Limit for in-progress test cases:
249     if (a_inProgressCount >= a_inProgressLimit) {
250       LOGDEBUG(anna::Logger::debug(anna::functions::asString("TestManager next case ignored (over in-progress count limit: %llu)", a_inProgressLimit), ANNA_FILE_LOCATION));
251       return true; // wait next tick to release OTA test cases
252     }
253
254     // Next test case:
255     if (a_currentTestIt == a_testPool.end())
256       a_currentTestIt = a_testPool.begin();
257     else
258       a_currentTestIt++;
259
260     // Completed:
261     if (a_currentTestIt == a_testPool.end()) {
262       if (a_poolRepeat) {
263         LOGWARNING(anna::Logger::warning("Testing pool cycle completed. Repeat mode on. Restarting", ANNA_FILE_LOCATION));
264         //a_currentTestIt = a_testPool.begin();
265         return true; // avoids infinite loop: if the cycle takes less time than test cases completion, below reset never will turns state
266                      // into Initialized and this while will be infinite. It is preferable to wait one tick when the cycle is completed.
267       }
268       else {
269         LOGWARNING(anna::Logger::warning("Testing pool cycle completed. Repeat mode off. Suspending", ANNA_FILE_LOCATION));
270         return false;
271       }
272     }
273
274     // Hard reset, because normally a cycle takes more time that a single test case lifetime. We can consider that never
275     //  going to break a in-progress test case due to cycle repeat
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;
283     }
284   }
285 }
286
287 TestCase *TestManager::getTestCaseFromSessionId(const anna::DataBlock &message, std::string &sessionId) throw(anna::RuntimeException) {
288   sessionId = anna::diameter::helpers::base::functions::getSessionId(message);
289   std::map<std::string /* session id's */, TestCase*>::const_iterator sessionIdIt = a_sessionIdTestCaseMap.find(sessionId);
290   if (sessionIdIt != a_sessionIdTestCaseMap.end())
291     return sessionIdIt->second;
292
293   LOGWARNING(anna::Logger::warning(anna::functions::asString("Cannot identify the Test Case for received Session-Id: %s", sessionId.c_str()), ANNA_FILE_LOCATION));
294   return NULL;
295 }
296
297 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ClientSession *clientSession) throw(anna::RuntimeException) {
298
299   // Testing disabled:
300   if (!tests()) return;
301
302   // Identify the test case:
303   std::string sessionId;
304   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
305   if (!tc) return;
306
307   // Work with Test case:
308   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, true /* comes from entity */);
309   if (!tsw) { // store as 'uncovered'
310     std::string hint = "Uncovered condition for received message from entity over Session-Id '"; hint += sessionId; hint += "':";
311
312     try {
313       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
314       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
315       codecMsg.decode(message);
316       hint += "\n"; hint += codecMsg.asXMLString();
317     }
318     catch (anna::RuntimeException &ex) {
319       ex.trace();
320       hint += "\n"; hint += ex.asString();
321     }
322     hint += "\n"; hint += clientSession->asString();
323
324     tc->addDebugSummaryHint(hint);
325   }
326   else {
327     tsw->setClientSession(const_cast<anna::diameter::comm::ClientSession*>(clientSession));
328   }
329 }
330
331 void TestManager::receiveMessage(const anna::DataBlock &message, const anna::diameter::comm::ServerSession *serverSession) throw(anna::RuntimeException) {
332
333   // Testing disabled:
334   if (!tests()) return;
335
336   // Identify the test case:
337   std::string sessionId;
338   TestCase *tc = getTestCaseFromSessionId(message, sessionId);
339   if (!tc) return;
340
341   // Work with Test case:
342   TestStepWait *tsw = tc->searchNextWaitConditionFulfilled(message, false /* comes from client */);
343   if (!tsw) { // store as 'uncovered'
344     std::string hint = "Uncovered condition for received message from client over Session-Id '"; hint += sessionId; hint += "':";
345
346     try {
347       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
348       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
349       codecMsg.decode(message);
350       hint += "\n"; hint += codecMsg.asXMLString();
351     }
352     catch (anna::RuntimeException &ex) {
353       ex.trace();
354       hint += "\n"; hint += ex.asString();
355     }
356     hint += "\n"; hint += serverSession->asString();
357
358     tc->addDebugSummaryHint(hint);
359   }
360   else {
361     tsw->setServerSession(const_cast<anna::diameter::comm::ServerSession*>(serverSession));
362   }
363 }
364
365 anna::xml::Node* TestManager::asXML(anna::xml::Node* parent) const
366 throw() {
367   anna::xml::Node* result = parent->createChild("TestManager");
368
369   int poolSize = a_testPool.size();
370   result->createAttribute("NumberOfTestCases", poolSize);
371   result->createAttribute("PoolRepeat", (a_poolRepeat ? "yes":"no"));
372   result->createAttribute("InProgressCount", a_inProgressCount);
373   if (a_inProgressLimit == UINT_MAX)
374     result->createAttribute("InProgressLimit", "<no limit>");
375   else
376     result->createAttribute("InProgressLimit", a_inProgressLimit);
377   result->createAttribute("DumpReports", (a_dumpReports ? "yes":"no"));
378   result->createAttribute("ReportsDirectory", a_reportsDirectory);
379   if (a_clock) {
380     result->createAttribute("AsynchronousSendings", a_synchronousAmount);
381     int ticksPerSecond = (a_synchronousAmount * 1000) / a_clock->getTimeout();
382     result->createAttribute("TicksPerSecond", ticksPerSecond);
383   }
384   if (a_currentTestIt != a_testPool.end()) {
385     result->createAttribute("CurrentTestCaseId", (*a_currentTestIt).first);
386   }
387   if (a_dumpReports && poolSize != 0) {
388     anna::xml::Node* testCases = result->createChild("TestCases");
389     for (test_pool_it it = a_testPool.begin(); it != a_testPool.end(); it++) {
390       (*it).second->asXML(testCases);
391     }
392   }
393
394   return result;
395 }
396
397 std::string TestManager::asXMLString() const throw() {
398   anna::xml::Node root("root");
399   return anna::xml::Compiler().apply(asXML(&root));
400 }
401