Comments and popen solution (commented)
[anna.git] / example / diameter / launcher / testing / TestStep.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
9 // Standard
10 #include <string>
11 #include <iostream>
12 #include <errno.h>
13
14 #include <signal.h>     // sigaction, sigemptyset, struct sigaction, SIGCHLD, SA_RESTART, SA_NOCLDSTOP
15 #include <stdio.h>      // perror
16 #include <stdlib.h>     // exit
17 #include <sys/wait.h>   // waitpid, pid_t, WNOHANG
18
19 // Project
20 #include <anna/xml/Compiler.hpp>
21 #include <anna/core/util/Millisecond.hpp>
22 #include <anna/diameter.comm/Message.hpp>
23 #include <anna/core/tracing/Logger.hpp>
24 #include <anna/diameter/codec/functions.hpp>
25 #include <anna/diameter/helpers/base/functions.hpp>
26
27 // Process
28 #include <RealmNode.hpp>
29 #include <MyDiameterEntity.hpp>
30 #include <MyLocalServer.hpp>
31 #include <TestStep.hpp>
32 #include <Launcher.hpp>
33 #include <TestCase.hpp>
34 #include <TestManager.hpp>
35 #include <TestTimer.hpp>
36
37
38 namespace {
39
40   void handle_sigchld(int sig) {
41     while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
42   }
43
44   void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
45
46     // Thread running:
47     step->setThreadRunning(true);
48
49     int status = -2;
50
51     struct sigaction sa;
52     sa.sa_handler = &handle_sigchld;
53     sigemptyset(&sa.sa_mask);
54     sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
55     if (sigaction(SIGCHLD, &sa, 0) != -1) {
56       status = system(cmd.c_str());
57      /* POPEN version:
58       char readbuf[256];
59       FILE *fp = popen(cmd.c_str(), "r");
60       if (fp) {
61         while(fgets(readbuf, sizeof(readbuf), fp))
62           step->appendOutput("\n");
63           step->appendOutput(readbuf);
64           status = pclose(fp);
65       }
66       else {
67         status = -1;
68       }
69       */
70     }
71     else {
72       perror(0);
73     }
74     // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
75     // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
76     //   perror(0);
77     //   exit(1);
78     // }
79
80     if (status < 0) {
81       char buf[256];
82       char const * str = strerror_r(errno, buf, 256);
83       step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
84     }
85
86     step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
87     step->complete();
88     // TODO: terminate thread when deprecated (RT signal ?)
89     // TODO: mutex the step while setting data here !!
90   }
91 }
92
93
94 ////////////////////////////////////////////////////////////////////////////////////////////////////////
95 // TestStep
96 ////////////////////////////////////////////////////////////////////////////////////////////////////////
97 void TestStep::initialize(TestCase *testCase) {
98   a_testCase = testCase;
99   a_completed = false;
100   a_type = Type::Unconfigured;
101   a_beginTimestamp = 0;
102   a_endTimestamp = 0;
103   a_number = testCase->steps() + 1; // testCase is not NULL
104 }
105
106 const char* TestStep::asText(const Type::_v type)
107 throw() {
108   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
109   return text [type];
110 }
111
112 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent) const
113 throw() {
114   anna::xml::Node* result = parent->createChild("TestStep");
115
116   result->createAttribute("Number", a_number);
117   result->createAttribute("Type", asText(a_type));
118   result->createAttribute("Completed", (a_completed ? "yes":"no"));
119
120   // Begin
121   std::string s_aux = a_beginTimestamp.asString();
122 //  int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
123 //  if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
124   result->createAttribute("BeginTimestamp", s_aux);
125
126   // End
127   s_aux = a_endTimestamp.asString();
128 //  deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
129 //  if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
130   result->createAttribute("EndTimestamp", s_aux);
131
132   return result;
133 }
134
135 std::string TestStep::asXMLString() const throw() {
136   anna::xml::Node root("root");
137   return anna::xml::Compiler().apply(asXML(&root));
138 }
139
140 bool TestStep::execute() throw() {
141   LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
142   setBeginTimestamp(anna::functions::millisecond());
143   return do_execute();
144 }
145
146 void TestStep::complete() throw() {
147   LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
148   a_completed = true;
149   setEndTimestamp(anna::functions::millisecond());
150   do_complete();
151 }
152
153 void TestStep::reset() throw() {
154   LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
155   // type and testCase kept
156   a_completed = false;
157   a_beginTimestamp = 0;
158   a_endTimestamp = 0;
159   do_reset();
160 }
161
162 void TestStep::next() throw() {
163   a_testCase->nextStep();
164   a_testCase->process();
165 }
166
167
168 ////////////////////////////////////////////////////////////////////////////////////////////////////////
169 // TestStepTimeout
170 ////////////////////////////////////////////////////////////////////////////////////////////////////////
171 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent) const
172 throw() {
173   anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
174   //parent->createChild("TestStepTimeout");
175   result->createAttribute("Timeout", a_timeout.asString());
176
177   return result;
178 }
179
180 bool TestStepTimeout::do_execute() throw() {
181   try {
182     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
183   }
184   catch (anna::RuntimeException &ex) {
185     ex.trace();
186     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
187     a_testCase->setState(TestCase::State::Failed);
188   }
189
190   return true; // go next
191 }
192
193 void TestStepTimeout::do_complete() throw() {
194   int stepNumber = getNumber();
195   if (stepNumber == a_testCase->steps()) {
196     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) but it was the last test case step", stepNumber)); // before report (when set Failed state)
197     a_testCase->setState(TestCase::State::Success);
198   }
199   else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
200     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
201     a_testCase->setState(TestCase::State::Failed);
202   }
203
204   a_timer = NULL;
205 }
206
207 void TestStepTimeout::do_reset() throw() {
208   LOGDEBUG(anna::Logger::debug(anna::functions::asString("REXXXXXET %s for Test Case %llu (%p) (%p) (a_timer %p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this, a_timer), ANNA_FILE_LOCATION));
209
210   try {
211     TestManager::instantiate().cancelTimer(a_timer);
212   }
213   catch (anna::RuntimeException &ex) {
214     ex.trace();
215   }
216   a_timer = NULL;
217   //a_timeout = 0; THIS IS CONFIGURATION INFO
218 }
219
220 ////////////////////////////////////////////////////////////////////////////////////////////////////////
221 // TestStepSendxml
222 ////////////////////////////////////////////////////////////////////////////////////////////////////////
223 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
224 throw() {
225   anna::xml::Node* result = TestStep::asXML(parent);
226   //parent->createChild("TestStepSendxml");
227   std::string msg = "", xmlmsg = "";
228
229   // Message
230   if (TestManager::instantiate().getDumpHex()) {
231     if (a_message.isEmpty()) {
232       msg = "<empty>";
233     }
234     else {
235       msg = "\n"; msg += a_message.asString(); msg += "\n";
236     }
237   }
238
239   if (!a_message.isEmpty()) {
240     try {
241       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
242       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
243       codecMsg.decode(a_message);
244       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
245     }
246     catch (anna::RuntimeException &ex) {
247       ex.trace();
248     }
249   }
250
251   if (msg != "") result->createAttribute("Message", msg);
252   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
253   result->createAttribute("Expired", (a_expired ? "yes":"no"));
254   if (a_waitForRequestStepNumber != -1)
255     result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
256
257   return result;
258 }
259
260 bool TestStepSendxml::do_execute() throw() {
261   anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
262   bool success = false;
263   std::string failReason, s_warn;
264
265   try {
266     // Update sequence for answers:
267     if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
268       // Request which was received:
269       const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
270       const anna::DataBlock &request = tsw->getMsgDataBlock();
271       anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
272       anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
273       // Update sequence:
274       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
275       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
276
277       // Check Session-Id for warning ...
278       std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
279       std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
280       if (sessionIdRequest != sessionIdAnswer) {
281         s_warn = anna::functions::asString("Sending an answer which Session-Id (%s) is different than supposed corresponding request (%s)", sessionIdAnswer.c_str(), sessionIdRequest.c_str());
282         LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
283         a_testCase->addDebugSummaryHint(s_warn);
284       }
285     }
286
287     if (getType() == Type::Sendxml2e) {
288       MyDiameterEntity *entity = a_realmNode->getEntity();
289       if (entity) {
290         //msg->clearBody();
291         msg->setBody(a_message);
292         /* response = NULL =*/entity->send(msg);
293         success = true;
294       }
295       else {
296         failReason = "There is no diameter entity currently configured. Unable to send the message";
297         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
298       }
299     }
300     else if (getType() == Type::Sendxml2c) {
301       MyLocalServer *localServer = a_realmNode->getDiameterServer();
302       if (localServer) {
303         //msg->clearBody();
304         msg->setBody(a_message);
305         /* response = NULL =*/localServer->send(msg);
306         success = true;
307       }
308       else {
309         failReason = "There is no diameter local server currently configured. Unable to send the message";
310         LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
311       }
312     }
313   } catch(anna::RuntimeException &ex) {
314     failReason = ex.asString();
315   }
316
317   // release msg
318   a_realmNode->releaseCommMessage(msg);
319
320   if (!success) {
321     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
322     a_testCase->setState(TestCase::State::Failed);
323   }
324   else {
325     complete();
326   }
327
328   return success; // go next if sent was OK
329 }
330
331 void TestStepSendxml::do_reset() throw() {
332   a_expired = false;
333   //a_message.clear();
334 }
335
336 ////////////////////////////////////////////////////////////////////////////////////////////////////////
337 // TestStepDelay
338 ////////////////////////////////////////////////////////////////////////////////////////////////////////
339 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
340 throw() {
341   anna::xml::Node* result = TestStep::asXML(parent);
342   //parent->createChild("TestStepDelay");
343
344   result->createAttribute("Delay", a_delay.asString());
345
346   return result;
347 }
348
349 bool TestStepDelay::do_execute() throw() {
350   try {
351     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
352   }
353   catch (anna::RuntimeException &ex) {
354     ex.trace();
355     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
356     a_testCase->setState(TestCase::State::Failed);
357   }
358
359   return false; // don't go next (wait complete)
360 }
361
362 void TestStepDelay::do_complete() throw() {
363   a_timer = NULL;
364   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
365 }
366
367 void TestStepDelay::do_reset() throw() {
368   try {
369     TestManager::instantiate().cancelTimer(a_timer);
370   }
371   catch (anna::RuntimeException &ex) {
372     ex.trace();
373   }
374   a_timer = NULL;
375   //a_delay = 0; THIS IS CONFIGURATION INFO
376 }
377
378 ////////////////////////////////////////////////////////////////////////////////////////////////////////
379 // TestStepWait
380 ////////////////////////////////////////////////////////////////////////////////////////////////////////
381 void TestStepWait::setCondition(bool fromEntity,
382                                   const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
383                                   const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
384
385   a_condition.setReceivedFromEntity(fromEntity);
386   a_condition.setCode(code);
387   a_condition.setBitR(bitR);
388   a_condition.setResultCode(resultCode);
389   a_condition.setSessionId(sessionId);
390   a_condition.setHopByHop(hopByHop);
391   a_condition.setMsisdn(msisdn);
392   a_condition.setImsi(imsi);
393   a_condition.setServiceContextId(serviceContextId);
394 }
395
396 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
397
398   a_condition.setReceivedFromEntity(fromEntity);
399   a_condition.setRegexp(regexp);
400 }
401
402 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
403 throw() {
404   anna::xml::Node* result = TestStep::asXML(parent);
405   //parent->createChild("TestStepWait");
406   std::string msg = "", xmlmsg = "";
407
408   // Condition
409   a_condition.asXML(result);
410
411   // Message
412   if (TestManager::instantiate().getDumpHex()) {
413     if (a_message.isEmpty()) {
414       msg = "<empty>";
415     }
416     else {
417       msg = "\n"; msg += a_message.asString(); msg += "\n";
418     }
419   }
420
421   if (!a_message.isEmpty()) {
422     try {
423       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
424       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
425       codecMsg.decode(a_message);
426       xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
427     }
428     catch (anna::RuntimeException &ex) {
429       ex.trace();
430     }
431   }
432
433   if (msg != "") result->createAttribute("MatchedMessage", msg);
434   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
435
436   return result;
437 }
438
439 bool TestStepWait::do_execute() throw() {
440   return a_completed;
441 }
442
443 void TestStepWait::do_complete() throw() {
444   a_testCase->process(); // next() not invoked; we only want to reactivate the test case
445 }
446
447 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
448   if (a_condition.comply(db/*, matchSessionId*/)) {
449     a_message = db; // store matched
450     complete();
451     return true;
452   }
453
454   return false;
455 }
456
457 void TestStepWait::do_reset() throw() {
458   a_message.clear();
459   a_clientSession = NULL;
460   a_serverSession = NULL;
461 }
462
463 ////////////////////////////////////////////////////////////////////////////////////////////////////////
464 // TestStepCmd
465 ////////////////////////////////////////////////////////////////////////////////////////////////////////
466 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent) const
467 throw() {
468   anna::xml::Node* result = TestStep::asXML(parent);
469   //parent->createChild("TestStepCmd");
470
471   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
472   result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
473   if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
474   if (!a_threadRunning && a_resultCode != -2) {
475     result->createAttribute("ResultCode", a_resultCode);
476     //if (a_output != "") result->createAttribute("Output", a_output);
477   }
478
479   return result;
480 }
481
482 bool TestStepCmd::do_execute() throw() {
483   if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
484     // Special tags to replace:
485     std::string cmd = getScript();
486     cmd += " ";
487     cmd += getParameters();
488     size_t index;
489     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
490       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
491     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
492       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
493     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
494       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
495
496     a_thread = std::thread(cmdRunOnThread, this, cmd);
497     a_thread.detach();
498   }
499
500   return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
501                 // We must implement a interrupt procedure for the thread on reset call... TODO !       
502 }
503
504 void TestStepCmd::do_complete() throw() {
505
506   a_threadRunning = false;
507   if (a_threadDeprecated) {
508     a_threadDeprecated = false;
509     do_reset();
510     setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
511     a_testCase->setState(TestCase::State::Failed);
512     return; // ignore TODO: interrupt the thread to avoid execution of the script
513   }
514
515   if (getResultCode() != 0)
516     a_testCase->setState(TestCase::State::Failed);
517   else
518     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
519 }
520
521 void TestStepCmd::do_reset() throw() {
522
523   if (a_threadRunning) {
524     std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
525     LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
526     a_threadDeprecated = true;
527   }
528
529   a_resultCode = -2;
530   //a_output = "";
531 }
532