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