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