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