Fix answer condition from message
[anna.git] / source / 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 // cmd with fork:
20 #include <sys/types.h>
21 #include <unistd.h>
22
23
24 // Project
25 #include <anna/testing/TestStep.hpp>
26
27 #include <anna/testing/defines.hpp>
28 #include <anna/diameter/codec/Message.hpp>
29 #include <anna/diameter.comm/OriginHost.hpp>
30 #include <anna/testing/TestCase.hpp>
31 #include <anna/testing/TestManager.hpp>
32 #include <anna/testing/TestTimer.hpp>
33 #include <anna/xml/Compiler.hpp>
34 #include <anna/core/util/Millisecond.hpp>
35 #include <anna/diameter.comm/Message.hpp>
36 #include <anna/diameter.comm/Entity.hpp>
37 #include <anna/diameter.comm/LocalServer.hpp>
38 #include <anna/diameter.comm/ClientSession.hpp>
39 #include <anna/diameter.comm/ServerSession.hpp>
40 #include <anna/diameter.comm/Server.hpp>
41 #include <anna/core/tracing/Logger.hpp>
42 #include <anna/diameter/codec/functions.hpp>
43 #include <anna/diameter/helpers/base/functions.hpp>
44
45
46
47 using namespace anna::testing;
48
49
50 namespace {
51
52   void handle_sigchld(int sig) {
53     while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
54   }
55
56   void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
57
58     // Thread running:
59     step->setThreadRunning(true);
60
61     int status = -2;
62
63     struct sigaction sa;
64     sa.sa_handler = &handle_sigchld;
65     sigemptyset(&sa.sa_mask);
66     sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
67     if (sigaction(SIGCHLD, &sa, 0) != -1) {
68       status = system(cmd.c_str());
69       /* POPEN version:
70           char readbuf[256];
71           FILE *fp = popen(cmd.c_str(), "r");
72           if (fp) {
73             while(fgets(readbuf, sizeof(readbuf), fp))
74               step->appendOutput("\n");
75               step->appendOutput(readbuf);
76               status = pclose(fp);
77           }
78           else {
79             status = -1;
80           }
81        */
82     }
83     else {
84       perror(0);
85     }
86     // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
87     // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
88     //   perror(0);
89     //   exit(1);
90     // }
91
92     if (status < 0) {
93       char buf[256];
94       char const * str = strerror_r(errno, buf, 256);
95       step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
96     }
97
98     step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
99     step->complete();
100     // TODO: terminate thread when deprecated (RT signal ?)
101     // TODO: mutex the step while setting data here !!
102   }
103
104 /*
105   void cmdRunOnThreadWithFork (TestStepCmd *step, const std::string &cmd) {
106
107     // Thread running:
108     step->setThreadRunning(true);
109
110     pid_t cpid, w;
111     int status = -2;
112
113     if ((cpid = fork()) < 0) {
114       step->setErrorMsg("Error in fork()");
115     }
116     else if (cpid == 0) {
117       // child
118       status = system(cmd.c_str());
119       _exit(WEXITSTATUS(status));
120     }
121     else {
122       // parent
123       step->setChildPid(cpid);
124       do {
125         w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
126         if (w != -1) {
127
128           if (WIFEXITED(status)) {
129             step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
130             break;
131           }
132           else if (WIFSIGNALED(status)) {
133             step->setErrorMsg(anna::functions::asString("killed by signal %d", WTERMSIG(status)));
134             step->setResultCode(128 + WTERMSIG(status));
135             break;
136           } else if (WIFSTOPPED(status)) {
137             step->setErrorMsg(anna::functions::asString("stopped by signal %d", WSTOPSIG(status)));
138           } else if (WIFCONTINUED(status)) {
139             step->setErrorMsg("continued");
140           }
141         }
142         else {
143           step->setErrorMsg("waitpid error");
144           step->setResultCode(-1);
145           break;
146         }
147       } while (!WIFEXITED(status) && !WIFSIGNALED(status));
148
149       step->complete();
150     }
151   }
152 */
153
154   bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message &messageCodec) throw() {
155
156     if (message.isEmpty())
157       return false;
158
159     bool result = true;
160     try {
161       messageCodec.clear();
162       messageCodec.decode(message);
163     }
164     catch (anna::RuntimeException &ex) {
165       ex.trace();
166       result = false;
167     }
168
169     return result;
170   }
171 }
172
173
174 ////////////////////////////////////////////////////////////////////////////////////////////////////////
175 // TestStep
176 ////////////////////////////////////////////////////////////////////////////////////////////////////////
177 void TestStep::initialize(TestCase *testCase) {
178   a_testCase = testCase;
179   a_completed = false;
180   a_type = Type::Unconfigured;
181   a_beginTimestamp = 0;
182   a_endTimestamp = 0;
183   a_number = testCase->steps() + 1; // testCase is not NULL
184 }
185
186 bool TestStep::decodeMessage(bool trust) throw() {
187   if (a_messageCodec) return true;
188   a_messageCodec = new anna::diameter::codec::Message;
189   if (::decodeMessage(a_message, *a_messageCodec)) return true;
190   if (trust) {
191     LOGDEBUG(anna::Logger::debug("Error DECODING, but trusting it ...", ANNA_FILE_LOCATION));
192     return true;
193   }
194
195   delete a_messageCodec;
196   a_messageCodec = NULL;
197   return false;
198 }
199
200 const char* TestStep::asText(const Type::_v type)
201 throw() {
202   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Command" };
203   return text [type];
204 }
205
206 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
207 throw() {
208   anna::xml::Node* result = parent->createChild("TestStep");
209
210   result->createAttribute("Number", a_number);
211   result->createAttribute("Type", asText(a_type));
212   result->createAttribute("Completed", (a_completed ? "yes":"no"));
213
214   // Begin
215   std::string s_aux = a_beginTimestamp.asString();
216   //  int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
217   //  if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
218   result->createAttribute("BeginTimestamp", s_aux);
219
220   // End
221   s_aux = a_endTimestamp.asString();
222   //  deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
223   //  if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
224   result->createAttribute("EndTimestamp", s_aux);
225
226   return result;
227 }
228
229 std::string TestStep::asXMLString() throw() {
230   anna::xml::Node root("root");
231   return anna::xml::Compiler().apply(asXML(&root));
232 }
233
234 bool TestStep::execute() throw() {
235
236   int ia = a_testCase->interactiveAmount();
237   if (ia > -1) {
238     if (ia == 0) return false;
239     a_testCase->interactiveExecution();
240     LOGDEBUG(anna::Logger::debug("Interactive execution ...", ANNA_FILE_LOCATION));
241     if (a_executed) return false; // avoid repeating (this implies amount consumption)
242   }
243
244   LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
245   setBeginTimestamp(anna::functions::millisecond());
246   a_executed = true;
247   return do_execute();
248 }
249
250 void TestStep::complete() throw() {
251   LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
252   a_completed = true;
253   setEndTimestamp(anna::functions::millisecond());
254   do_complete();
255 }
256
257 void TestStep::reset() throw() {
258   LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
259   // type and testCase kept
260   a_completed = false;
261   a_executed = false;
262   a_beginTimestamp = 0;
263   a_endTimestamp = 0;
264   do_reset();
265 }
266
267 void TestStep::next() throw() {
268   a_testCase->nextStep();
269   a_testCase->process();
270 }
271
272
273 ////////////////////////////////////////////////////////////////////////////////////////////////////////
274 // TestStepTimeout
275 ////////////////////////////////////////////////////////////////////////////////////////////////////////
276 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
277 throw() {
278   anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
279   //parent->createChild("TestStepTimeout");
280   result->createAttribute("Timeout", a_timeout.asString());
281
282   return result;
283 }
284
285 bool TestStepTimeout::do_execute() throw() {
286   try {
287     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
288   }
289   catch (anna::RuntimeException &ex) {
290     ex.trace();
291     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
292     a_testCase->setState(TestCase::State::Failed);
293   }
294
295   return true; // go next
296 }
297
298 void TestStepTimeout::do_complete() throw() {
299   int stepNumber = getNumber();
300   if (stepNumber == a_testCase->steps()) {
301     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)
302     a_testCase->setState(TestCase::State::Success);
303   }
304   else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
305     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
306     a_testCase->setState(TestCase::State::Failed);
307   }
308
309   a_timer = NULL;
310 }
311
312 void TestStepTimeout::do_reset() throw() {
313   try {
314     TestManager::instantiate().cancelTimer(a_timer);
315   }
316   catch (anna::RuntimeException &ex) {
317     ex.trace();
318   }
319   a_timer = NULL;
320   //a_timeout = 0; THIS IS CONFIGURATION INFO
321 }
322
323 ////////////////////////////////////////////////////////////////////////////////////////////////////////
324 // TestStepSendxml
325 ////////////////////////////////////////////////////////////////////////////////////////////////////////
326 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
327 throw() {
328   anna::xml::Node* result = TestStep::asXML(parent);
329   //parent->createChild("TestStepSendxml");
330   std::string msg = "", xmlmsg = "";
331
332   // Message
333   if (TestManager::instantiate().getDumpHex()) {
334     if (a_message.isEmpty()) {
335       msg = "<empty>";
336     }
337     else {
338       msg = "\n"; msg += a_message.asString(); msg += "\n";
339     }
340   }
341
342   if (decodeMessage()) {
343     xmlmsg = "\n";
344     xmlmsg += a_messageCodec->asXMLString();
345     xmlmsg += "\n";
346   }
347   else {
348     xmlmsg = "<unable to decode, check traces>";
349   }
350
351   if (msg != "") result->createAttribute("Message", msg);
352   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
353   result->createAttribute("Expired", (a_expired ? "yes":"no"));
354   if (a_waitForRequestStepNumber != -1)
355     result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
356
357   return result;
358 }
359
360 bool TestStepSendxml::do_execute() throw() {
361   bool success = false;
362   std::string failReason = "Error sending diameter message";
363   anna::diameter::comm::Entity *entity = a_originHost->getEntity(); // by default
364   anna::diameter::comm::LocalServer *localServer = a_originHost->getDiameterServer(); // by default
365   const TestStepWait *tsw = NULL;
366   anna::diameter::comm::Message *msg = a_originHost->createCommMessage();
367
368   try {
369
370     if (a_waitForRequestStepNumber != -1) {
371       bool thisIsAnswer = anna::diameter::codec::functions::isAnswer(getMsgDataBlock());
372       LOGDEBUG(
373          std::string trace = anna::functions::asString("'Wait For Request' step number for this %s: %d", (thisIsAnswer ? "answer":"request"), a_waitForRequestStepNumber);
374          anna::Logger::debug(trace, ANNA_FILE_LOCATION);
375       );
376
377       // Referenced request in the 'wait for request step':
378       tsw = static_cast<const TestStepWait*>(a_testCase->getStep(a_waitForRequestStepNumber));
379       const anna::DataBlock &referenceRequest = tsw->getMsgDataBlock();
380       std::string sessionIdReferenceRequest = anna::diameter::helpers::base::functions::getSessionId(referenceRequest);
381
382       if (thisIsAnswer) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
383         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(referenceRequest);
384         anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(referenceRequest);
385
386         // Update sequence:
387         anna::diameter::codec::functions::setHopByHop(a_message, hbh);
388         anna::diameter::codec::functions::setEndToEnd(a_message, ete);
389       }
390
391       // Session-Id substitution:
392       std::string thisSessionId = anna::diameter::helpers::base::functions::getSessionId(getMsgDataBlock());
393       if (thisSessionId != sessionIdReferenceRequest) {
394         static anna::diameter::codec::Message codecMsg;
395         codecMsg.decode(getMsgDataBlock());
396         codecMsg.getAvp("Session-Id")->getUTF8String()->setValue(sessionIdReferenceRequest);
397         a_message = codecMsg.code();
398         std::string trace = anna::functions::asString("Replacing %s Session-Id (%s) to set the corresponding request one (%s)", (thisIsAnswer ? "answer":"request"), thisSessionId.c_str(), sessionIdReferenceRequest.c_str());
399         LOGDEBUG(anna::Logger::debug(trace, ANNA_FILE_LOCATION));
400         a_testCase->addDebugSummaryHint(trace);
401       }
402     }
403
404     // Create comm message:
405     //msg->clearBody();
406     msg->setBody(a_message);
407
408
409     if (getType() == Type::Sendxml2e) {
410       anna::diameter::comm::ClientSession *usedClientSession = NULL;
411
412       if (tsw) { // is an answer for a received request on wait condition
413         anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
414         if (clientSession) {
415           /* response NULL (is an answer) */clientSession->send(msg);
416           success = true;
417           usedClientSession = clientSession;
418         }
419         else {
420           failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
421           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
422         }
423       }
424       else {
425         if (entity) {
426           success = entity->send(msg);
427           anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
428           usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
429         }
430         else {
431           failReason = "There is no diameter entity currently configured. Unable to send the message";
432           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
433         }
434       } // else (normal sending)
435
436       // Detailed log:
437       if(a_originHost->logEnabled()) {
438         if (decodeMessage(true /* trust */)) {
439           std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
440           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
441         }
442       }
443     }
444     else if (getType() == Type::Sendxml2c) {
445       anna::diameter::comm::ServerSession *usedServerSession = NULL;
446
447       if (tsw) { // is an answer for a received request on wait condition
448         anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
449         if (serverSession) {
450           /* response NULL (is an answer) */serverSession->send(msg);
451           success = true;
452           usedServerSession = serverSession;
453         }
454         else {
455           failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
456           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
457         }
458       }
459       else {
460         if (localServer) {
461           success = localServer->send(msg);
462           usedServerSession = localServer->getLastUsedResource();
463         }
464         else {
465           failReason = "There is no diameter local server currently configured. Unable to send the message";
466           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
467         }
468       } // else (normal sending)
469
470       // Detailed log:
471       if(a_originHost->logEnabled()) {
472         if (decodeMessage(true /* trust */)) {
473           std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
474           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
475         }
476       }
477     }
478
479   } catch(anna::RuntimeException &ex) {
480     failReason = ex.asString();
481   }
482
483   // release msg
484   a_originHost->releaseCommMessage(msg);
485
486   if (!success) {
487     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
488     a_testCase->setState(TestCase::State::Failed);
489   }
490   else {
491     complete();
492   }
493
494   return success; // go next if sent was OK
495 }
496
497 void TestStepSendxml::do_reset() throw() {
498   a_expired = false;
499   //a_message.clear();
500   //a_messageAlreadyDecoded = false;
501 }
502
503 ////////////////////////////////////////////////////////////////////////////////////////////////////////
504 // TestStepDelay
505 ////////////////////////////////////////////////////////////////////////////////////////////////////////
506 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
507 throw() {
508   anna::xml::Node* result = TestStep::asXML(parent);
509   //parent->createChild("TestStepDelay");
510
511   result->createAttribute("Delay", ((a_delay == 0) ? "dummy step, no delay" : a_delay.asString()));
512
513   return result;
514 }
515
516 bool TestStepDelay::do_execute() throw() {
517   if (a_delay == 0) { complete(); return true; } // special case
518   try {
519     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
520   }
521   catch (anna::RuntimeException &ex) {
522     ex.trace();
523     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
524     a_testCase->setState(TestCase::State::Failed);
525   }
526
527   return false; // don't go next (wait complete)
528 }
529
530 void TestStepDelay::do_complete() throw() {
531   if (a_delay == 0) return; // special case
532   a_timer = NULL;
533   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
534   // TODO, avoid this recursion
535 }
536
537 void TestStepDelay::do_reset() throw() {
538   if (a_delay == 0) return; // special case
539   try {
540     TestManager::instantiate().cancelTimer(a_timer);
541   }
542   catch (anna::RuntimeException &ex) {
543     ex.trace();
544   }
545   a_timer = NULL;
546   //a_delay = 0; THIS IS CONFIGURATION INFO
547 }
548
549 ////////////////////////////////////////////////////////////////////////////////////////////////////////
550 // TestStepWait
551 ////////////////////////////////////////////////////////////////////////////////////////////////////////
552 void TestStepWait::setCondition(bool fromEntity,
553     const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
554     const std::string &sessionId, const std::string &resultCode,
555     const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
556
557   a_condition.setReceivedFromEntity(fromEntity);
558   a_condition.setCode(code);
559   a_condition.setBitR(bitR);
560   a_condition.setResultCode(resultCode);
561   a_condition.setSessionId(sessionId);
562   a_condition.setHopByHop(hopByHop);
563   a_condition.setMsisdn(msisdn);
564   a_condition.setImsi(imsi);
565   a_condition.setServiceContextId(serviceContextId);
566 }
567
568 void TestStepWait::setConditionRegexpHex(bool fromEntity, const std::string &regexp) throw() {
569   a_condition.setReceivedFromEntity(fromEntity);
570   a_condition.setRegexpHex(regexp);
571 }
572
573 void TestStepWait::setConditionRegexpXml(bool fromEntity, const std::string &regexp) throw() {
574   a_condition.setReceivedFromEntity(fromEntity);
575   a_condition.setRegexpXml(regexp);
576 }
577
578 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
579 throw() {
580   anna::xml::Node* result = TestStep::asXML(parent);
581   //parent->createChild("TestStepWait");
582   std::string msg = "", xmlmsg = "";
583
584   // Condition
585   a_condition.asXML(result);
586
587   // Message
588   if (TestManager::instantiate().getDumpHex()) {
589     if (a_message.isEmpty()) {
590       msg = "<empty>";
591     }
592     else {
593       msg = "\n"; msg += a_message.asString(); msg += "\n";
594     }
595   }
596
597   if (a_message.isEmpty()) {
598       xmlmsg = "<empty>";
599   }
600   else {
601     if (decodeMessage()) {
602       xmlmsg = "\n";
603       xmlmsg += a_messageCodec->asXMLString();
604       xmlmsg += "\n";
605     }
606     else {
607       xmlmsg = "<unable to decode, check traces>";
608     }
609   }
610
611   if (msg != "") result->createAttribute("MatchedMessage", msg);
612   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
613   if (a_clientSession) result->createAttribute("ClientSessionOrigin", anna::functions::asString("%p", a_clientSession));
614   if (a_serverSession) result->createAttribute("ServerSessionOrigin", anna::functions::asString("%p", a_serverSession));
615
616   return result;
617 }
618
619 bool TestStepWait::do_execute() throw() {
620   return a_completed;
621 }
622
623 void TestStepWait::do_complete() throw() {
624   //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
625   // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
626 }
627
628 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
629   if (a_condition.comply(db/*, matchSessionId*/)) {
630     a_message = db; // store matched
631     complete();
632     return true;
633   }
634
635   return false;
636 }
637
638 void TestStepWait::do_reset() throw() {
639   a_message.clear();
640   a_clientSession = NULL;
641   a_serverSession = NULL;
642 }
643
644 ////////////////////////////////////////////////////////////////////////////////////////////////////////
645 // TestStepCmd
646 ////////////////////////////////////////////////////////////////////////////////////////////////////////
647 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
648 throw() {
649   anna::xml::Node* result = TestStep::asXML(parent);
650   //parent->createChild("TestStepCmd");
651
652   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
653   if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
654   if (a_threadRunning) {
655     if (a_childPid != -1)
656       result->createAttribute("ChildPid", a_childPid);
657   }
658   else {
659     if (a_resultCode != -2) {
660       result->createAttribute("ResultCode", a_resultCode);
661       //if (a_output != "") result->createAttribute("Output", a_output);
662     }
663   }
664
665   return result;
666 }
667
668 bool TestStepCmd::do_execute() throw() {
669   if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
670     // Special tags to replace:
671     std::string cmd = getScript();
672     size_t index;
673     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
674       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
675     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
676       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
677     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
678       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
679
680     a_thread = std::thread(cmdRunOnThread, this, cmd);
681     //a_thread = std::thread(cmdRunOnThreadWithFork, this, cmd);
682
683     a_thread.detach();
684   }
685
686   return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
687   // We must implement a interrupt procedure for the thread on reset call... TODO !
688 }
689
690 void TestStepCmd::do_complete() throw() {
691
692   a_threadRunning = false;
693   if (a_threadDeprecated) {
694     a_threadDeprecated = false;
695     do_reset();
696     setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
697     a_testCase->setState(TestCase::State::Failed);
698     return; // ignore TODO: interrupt the thread to avoid execution of the script
699   }
700
701   if (getResultCode() != 0)
702     a_testCase->setState(TestCase::State::Failed);
703   else
704     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
705   // TODO, avoid this recursion
706 }
707
708 void TestStepCmd::do_reset() throw() {
709
710     if (a_threadRunning) {
711       std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
712       LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
713       a_threadDeprecated = true;
714     }
715 //  if (a_threadRunning) {
716 //    std::string s_warn = anna::functions::asString("Thread still in progress: killing child pid %d within step %d for Test Case %llu", a_childPid, getNumber(), a_testCase->getId());
717 //    LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
718 //    kill (a_childPid, SIGKILL);
719 //  }
720
721   a_resultCode = -2;
722   a_errorMsg = "";
723   //a_output = "";
724   a_childPid = -1;
725 }
726