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