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