Fixes & improvements
[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() 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
185   delete a_messageCodec;
186   a_messageCodec = NULL;
187   return false;
188 }
189
190 const char* TestStep::asText(const Type::_v type)
191 throw() {
192   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Command" };
193   return text [type];
194 }
195
196 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
197 throw() {
198   anna::xml::Node* result = parent->createChild("TestStep");
199
200   result->createAttribute("Number", a_number);
201   result->createAttribute("Type", asText(a_type));
202   result->createAttribute("Completed", (a_completed ? "yes":"no"));
203
204   // Begin
205   std::string s_aux = a_beginTimestamp.asString();
206   //  int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
207   //  if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
208   result->createAttribute("BeginTimestamp", s_aux);
209
210   // End
211   s_aux = a_endTimestamp.asString();
212   //  deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
213   //  if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
214   result->createAttribute("EndTimestamp", s_aux);
215
216   return result;
217 }
218
219 std::string TestStep::asXMLString() throw() {
220   anna::xml::Node root("root");
221   return anna::xml::Compiler().apply(asXML(&root));
222 }
223
224 bool TestStep::execute() throw() {
225
226   int ia = a_testCase->interactiveAmount();
227   if (ia > -1) {
228     if (ia == 0) return false;
229     a_testCase->interactiveExecution();
230     LOGDEBUG(anna::Logger::debug("Interactive execution ...", ANNA_FILE_LOCATION));
231     if (a_executed) return false; // avoid repeating (this implies amount consumption)
232   }
233
234   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));
235   setBeginTimestamp(anna::functions::millisecond());
236   a_executed = true;
237   return do_execute();
238 }
239
240 void TestStep::complete() throw() {
241   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));
242   a_completed = true;
243   setEndTimestamp(anna::functions::millisecond());
244   do_complete();
245 }
246
247 void TestStep::reset() throw() {
248   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));
249   // type and testCase kept
250   a_completed = false;
251   a_executed = false;
252   a_beginTimestamp = 0;
253   a_endTimestamp = 0;
254   do_reset();
255 }
256
257 void TestStep::next() throw() {
258   a_testCase->nextStep();
259   a_testCase->process();
260 }
261
262
263 ////////////////////////////////////////////////////////////////////////////////////////////////////////
264 // TestStepTimeout
265 ////////////////////////////////////////////////////////////////////////////////////////////////////////
266 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
267 throw() {
268   anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
269   //parent->createChild("TestStepTimeout");
270   result->createAttribute("Timeout", a_timeout.asString());
271
272   return result;
273 }
274
275 bool TestStepTimeout::do_execute() throw() {
276   try {
277     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
278   }
279   catch (anna::RuntimeException &ex) {
280     ex.trace();
281     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
282     a_testCase->setState(TestCase::State::Failed);
283   }
284
285   return true; // go next
286 }
287
288 void TestStepTimeout::do_complete() throw() {
289   int stepNumber = getNumber();
290   if (stepNumber == a_testCase->steps()) {
291     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)
292     a_testCase->setState(TestCase::State::Success);
293   }
294   else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
295     a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
296     a_testCase->setState(TestCase::State::Failed);
297   }
298
299   a_timer = NULL;
300 }
301
302 void TestStepTimeout::do_reset() throw() {
303   try {
304     TestManager::instantiate().cancelTimer(a_timer);
305   }
306   catch (anna::RuntimeException &ex) {
307     ex.trace();
308   }
309   a_timer = NULL;
310   //a_timeout = 0; THIS IS CONFIGURATION INFO
311 }
312
313 ////////////////////////////////////////////////////////////////////////////////////////////////////////
314 // TestStepSendxml
315 ////////////////////////////////////////////////////////////////////////////////////////////////////////
316 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
317 throw() {
318   anna::xml::Node* result = TestStep::asXML(parent);
319   //parent->createChild("TestStepSendxml");
320   std::string msg = "", xmlmsg = "";
321
322   // Message
323   if (TestManager::instantiate().getDumpHex()) {
324     if (a_message.isEmpty()) {
325       msg = "<empty>";
326     }
327     else {
328       msg = "\n"; msg += a_message.asString(); msg += "\n";
329     }
330   }
331
332   if (decodeMessage()) {
333     xmlmsg = "\n";
334     xmlmsg += a_messageCodec->asXMLString();
335     xmlmsg += "\n";
336   }
337   else {
338     xmlmsg = "<unable to decode, check traces>"; 
339   }
340
341   if (msg != "") result->createAttribute("Message", msg);
342   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
343   result->createAttribute("Expired", (a_expired ? "yes":"no"));
344   if (a_waitForRequestStepNumber != -1)
345     result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
346
347   return result;
348 }
349
350 bool TestStepSendxml::do_execute() throw() {
351   bool success = false;
352   std::string failReason, s_warn;
353   MyDiameterEntity *entity = a_originHost->getEntity(); // by default
354   MyLocalServer *localServer = a_originHost->getDiameterServer(); // by default
355   const TestStepWait *tsw = NULL;
356
357   // Create comm message:
358   anna::diameter::comm::Message *msg = a_originHost->createCommMessage();
359   //msg->clearBody();
360   msg->setBody(a_message);
361
362   try {
363     // Update sequence for answers:
364     if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
365       // Request which was received:
366       tsw = static_cast<const TestStepWait*>(a_testCase->getStep(a_waitForRequestStepNumber));
367
368       const anna::DataBlock &request = tsw->getMsgDataBlock();
369       anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
370       anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
371
372       // Update sequence:
373       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
374       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
375
376       // Check Session-Id for warning ...
377       std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
378       std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
379
380       if (sessionIdRequest != sessionIdAnswer) {
381         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());
382         LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
383         a_testCase->addDebugSummaryHint(s_warn);
384       }
385     }
386
387     if (getType() == Type::Sendxml2e) {
388       anna::diameter::comm::ClientSession *usedClientSession = NULL;
389
390       if (tsw) { // is an answer for a received request on wait condition
391         anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
392         if (clientSession) {
393           /* response NULL (is an answer) */clientSession->send(msg);
394           success = true;
395           usedClientSession = clientSession;
396         }
397         else {
398           failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
399           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
400         }
401       }
402       else {
403         if (entity) {
404           success = entity->send(msg);
405           anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
406           usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
407         }
408         else {
409           failReason = "There is no diameter entity currently configured. Unable to send the message";
410           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
411         }
412       } // else (normal sending)
413
414       // Detailed log:
415       if(a_originHost->logEnabled()) {
416         if (decodeMessage()) {
417           std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
418           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
419         }
420       }
421     }
422     else if (getType() == Type::Sendxml2c) {
423       anna::diameter::comm::ServerSession *usedServerSession = NULL;
424
425       if (tsw) { // is an answer for a received request on wait condition
426         anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
427         if (serverSession) {
428           /* response NULL (is an answer) */serverSession->send(msg);
429           success = true;
430           usedServerSession = serverSession;
431         }
432         else {
433           failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
434           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
435         }
436       }
437       else {
438         if (localServer) {
439           success = localServer->send(msg);
440           usedServerSession = localServer->getLastUsedResource();
441         }
442         else {
443           failReason = "There is no diameter local server currently configured. Unable to send the message";
444           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
445         }
446       } // else (normal sending)
447
448       // Detailed log:
449       if(a_originHost->logEnabled()) {
450         if (decodeMessage()) {
451           std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
452           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
453         }
454       }
455     }
456
457   } catch(anna::RuntimeException &ex) {
458     failReason = ex.asString();
459   }
460
461   // release msg
462   a_originHost->releaseCommMessage(msg);
463
464   if (!success) {
465     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
466     a_testCase->setState(TestCase::State::Failed);
467   }
468   else {
469     complete();
470   }
471
472   return success; // go next if sent was OK
473 }
474
475 void TestStepSendxml::do_reset() throw() {
476   a_expired = false;
477   //a_message.clear();
478   //a_messageAlreadyDecoded = false;
479 }
480
481 ////////////////////////////////////////////////////////////////////////////////////////////////////////
482 // TestStepDelay
483 ////////////////////////////////////////////////////////////////////////////////////////////////////////
484 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
485 throw() {
486   anna::xml::Node* result = TestStep::asXML(parent);
487   //parent->createChild("TestStepDelay");
488
489   result->createAttribute("Delay", ((a_delay == 0) ? "dummy step, no delay" : a_delay.asString()));
490
491   return result;
492 }
493
494 bool TestStepDelay::do_execute() throw() {
495   if (a_delay == 0) { complete(); return true; } // special case
496   try {
497     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
498   }
499   catch (anna::RuntimeException &ex) {
500     ex.trace();
501     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
502     a_testCase->setState(TestCase::State::Failed);
503   }
504
505   return false; // don't go next (wait complete)
506 }
507
508 void TestStepDelay::do_complete() throw() {
509   if (a_delay == 0) return; // special case
510   a_timer = NULL;
511   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
512   // TODO, avoid this recursion
513 }
514
515 void TestStepDelay::do_reset() throw() {
516   if (a_delay == 0) return; // special case
517   try {
518     TestManager::instantiate().cancelTimer(a_timer);
519   }
520   catch (anna::RuntimeException &ex) {
521     ex.trace();
522   }
523   a_timer = NULL;
524   //a_delay = 0; THIS IS CONFIGURATION INFO
525 }
526
527 ////////////////////////////////////////////////////////////////////////////////////////////////////////
528 // TestStepWait
529 ////////////////////////////////////////////////////////////////////////////////////////////////////////
530 void TestStepWait::setCondition(bool fromEntity,
531     const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
532     const std::string &sessionId, const std::string &resultCode,
533     const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
534
535   a_condition.setReceivedFromEntity(fromEntity);
536   a_condition.setCode(code);
537   a_condition.setBitR(bitR);
538   a_condition.setResultCode(resultCode);
539   a_condition.setSessionId(sessionId);
540   a_condition.setHopByHop(hopByHop);
541   a_condition.setMsisdn(msisdn);
542   a_condition.setImsi(imsi);
543   a_condition.setServiceContextId(serviceContextId);
544 }
545
546 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
547
548   a_condition.setReceivedFromEntity(fromEntity);
549   a_condition.setRegexp(regexp);
550 }
551
552 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
553 throw() {
554   anna::xml::Node* result = TestStep::asXML(parent);
555   //parent->createChild("TestStepWait");
556   std::string msg = "", xmlmsg = "";
557
558   // Condition
559   a_condition.asXML(result);
560
561   // Message
562   if (TestManager::instantiate().getDumpHex()) {
563     if (a_message.isEmpty()) {
564       msg = "<empty>";
565     }
566     else {
567       msg = "\n"; msg += a_message.asString(); msg += "\n";
568     }
569   }
570
571   if (decodeMessage()) {
572     xmlmsg = "\n";
573     xmlmsg += a_messageCodec->asXMLString();
574     xmlmsg += "\n";
575   }
576   else {
577     xmlmsg = "<unable to decode, check traces>"; 
578   }
579
580   if (msg != "") result->createAttribute("MatchedMessage", msg);
581   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
582   if (a_clientSession) result->createAttribute("ClientSessionOrigin", anna::functions::asString("%p", a_clientSession));
583   if (a_serverSession) result->createAttribute("ServerSessionOrigin", anna::functions::asString("%p", a_serverSession));
584
585   return result;
586 }
587
588 bool TestStepWait::do_execute() throw() {
589   return a_completed;
590 }
591
592 void TestStepWait::do_complete() throw() {
593   //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
594   // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
595 }
596
597 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
598   if (a_condition.comply(db/*, matchSessionId*/)) {
599     a_message = db; // store matched
600     complete();
601     return true;
602   }
603
604   return false;
605 }
606
607 void TestStepWait::do_reset() throw() {
608   a_message.clear();
609   a_clientSession = NULL;
610   a_serverSession = NULL;
611 }
612
613 ////////////////////////////////////////////////////////////////////////////////////////////////////////
614 // TestStepCmd
615 ////////////////////////////////////////////////////////////////////////////////////////////////////////
616 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
617 throw() {
618   anna::xml::Node* result = TestStep::asXML(parent);
619   //parent->createChild("TestStepCmd");
620
621   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
622   if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
623   if (a_threadRunning) {
624     if (a_childPid != -1)
625       result->createAttribute("ChildPid", a_childPid);
626   }
627   else {
628     if (a_resultCode != -2) {
629       result->createAttribute("ResultCode", a_resultCode);
630       //if (a_output != "") result->createAttribute("Output", a_output);
631     }
632   }
633
634   return result;
635 }
636
637 bool TestStepCmd::do_execute() throw() {
638   if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
639     // Special tags to replace:
640     std::string cmd = getScript();
641     size_t index;
642     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
643       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
644     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
645       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
646     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
647       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
648
649     a_thread = std::thread(cmdRunOnThread, this, cmd);
650     //a_thread = std::thread(cmdRunOnThreadWithFork, this, cmd);
651
652     a_thread.detach();
653   }
654
655   return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
656   // We must implement a interrupt procedure for the thread on reset call... TODO !
657 }
658
659 void TestStepCmd::do_complete() throw() {
660
661   a_threadRunning = false;
662   if (a_threadDeprecated) {
663     a_threadDeprecated = false;
664     do_reset();
665     setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
666     a_testCase->setState(TestCase::State::Failed);
667     return; // ignore TODO: interrupt the thread to avoid execution of the script
668   }
669
670   if (getResultCode() != 0)
671     a_testCase->setState(TestCase::State::Failed);
672   else
673     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
674   // TODO, avoid this recursion
675 }
676
677 void TestStepCmd::do_reset() throw() {
678
679     if (a_threadRunning) {
680       std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
681       LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
682       a_threadDeprecated = true;
683     }
684 //  if (a_threadRunning) {
685 //    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());
686 //    LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
687 //    kill (a_childPid, SIGKILL);
688 //  }
689
690   a_resultCode = -2;
691   a_errorMsg = "";
692   //a_output = "";
693   a_childPid = -1;
694 }
695