4a75f3beccbb3aea757ae599321c147d27309313
[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
372       // Referenced request in the 'wait for request step':
373       tsw = static_cast<const TestStepWait*>(a_testCase->getStep(a_waitForRequestStepNumber));
374       const anna::DataBlock &referenceRequest = tsw->getMsgDataBlock();
375       std::string sessionIdReferenceRequest = anna::diameter::helpers::base::functions::getSessionId(referenceRequest);
376       bool thisIsAnswer = anna::diameter::codec::functions::isRequest(getMsgDataBlock());
377
378       if (thisIsAnswer) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
379         anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(referenceRequest);
380         anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(referenceRequest);
381
382         // Update sequence:
383         anna::diameter::codec::functions::setHopByHop(a_message, hbh);
384         anna::diameter::codec::functions::setEndToEnd(a_message, ete);
385       }
386
387       // Session-Id substitution:
388       std::string thisSessionId = anna::diameter::helpers::base::functions::getSessionId(getMsgDataBlock());
389       if (thisSessionId != sessionIdReferenceRequest) {
390         static anna::diameter::codec::Message codecMsg;
391         codecMsg.decode(getMsgDataBlock());
392         codecMsg.getAvp("Session-Id")->getUTF8String()->setValue(sessionIdReferenceRequest);
393         a_message = codecMsg.code();
394         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());
395         LOGDEBUG(anna::Logger::debug(trace, ANNA_FILE_LOCATION));
396         a_testCase->addDebugSummaryHint(trace);
397       }
398     }
399
400     // Create comm message:
401     //msg->clearBody();
402     msg->setBody(a_message);
403
404
405     if (getType() == Type::Sendxml2e) {
406       anna::diameter::comm::ClientSession *usedClientSession = NULL;
407
408       if (tsw) { // is an answer for a received request on wait condition
409         anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
410         if (clientSession) {
411           /* response NULL (is an answer) */clientSession->send(msg);
412           success = true;
413           usedClientSession = clientSession;
414         }
415         else {
416           failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
417           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
418         }
419       }
420       else {
421         if (entity) {
422           success = entity->send(msg);
423           anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
424           usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
425         }
426         else {
427           failReason = "There is no diameter entity currently configured. Unable to send the message";
428           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
429         }
430       } // else (normal sending)
431
432       // Detailed log:
433       if(a_originHost->logEnabled()) {
434         if (decodeMessage(true /* trust */)) {
435           std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
436           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
437         }
438       }
439     }
440     else if (getType() == Type::Sendxml2c) {
441       anna::diameter::comm::ServerSession *usedServerSession = NULL;
442
443       if (tsw) { // is an answer for a received request on wait condition
444         anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
445         if (serverSession) {
446           /* response NULL (is an answer) */serverSession->send(msg);
447           success = true;
448           usedServerSession = serverSession;
449         }
450         else {
451           failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
452           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
453         }
454       }
455       else {
456         if (localServer) {
457           success = localServer->send(msg);
458           usedServerSession = localServer->getLastUsedResource();
459         }
460         else {
461           failReason = "There is no diameter local server currently configured. Unable to send the message";
462           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
463         }
464       } // else (normal sending)
465
466       // Detailed log:
467       if(a_originHost->logEnabled()) {
468         if (decodeMessage(true /* trust */)) {
469           std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
470           a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
471         }
472       }
473     }
474
475   } catch(anna::RuntimeException &ex) {
476     failReason = ex.asString();
477   }
478
479   // release msg
480   a_originHost->releaseCommMessage(msg);
481
482   if (!success) {
483     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
484     a_testCase->setState(TestCase::State::Failed);
485   }
486   else {
487     complete();
488   }
489
490   return success; // go next if sent was OK
491 }
492
493 void TestStepSendxml::do_reset() throw() {
494   a_expired = false;
495   //a_message.clear();
496   //a_messageAlreadyDecoded = false;
497 }
498
499 ////////////////////////////////////////////////////////////////////////////////////////////////////////
500 // TestStepDelay
501 ////////////////////////////////////////////////////////////////////////////////////////////////////////
502 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
503 throw() {
504   anna::xml::Node* result = TestStep::asXML(parent);
505   //parent->createChild("TestStepDelay");
506
507   result->createAttribute("Delay", ((a_delay == 0) ? "dummy step, no delay" : a_delay.asString()));
508
509   return result;
510 }
511
512 bool TestStepDelay::do_execute() throw() {
513   if (a_delay == 0) { complete(); return true; } // special case
514   try {
515     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
516   }
517   catch (anna::RuntimeException &ex) {
518     ex.trace();
519     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
520     a_testCase->setState(TestCase::State::Failed);
521   }
522
523   return false; // don't go next (wait complete)
524 }
525
526 void TestStepDelay::do_complete() throw() {
527   if (a_delay == 0) return; // special case
528   a_timer = NULL;
529   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
530   // TODO, avoid this recursion
531 }
532
533 void TestStepDelay::do_reset() throw() {
534   if (a_delay == 0) return; // special case
535   try {
536     TestManager::instantiate().cancelTimer(a_timer);
537   }
538   catch (anna::RuntimeException &ex) {
539     ex.trace();
540   }
541   a_timer = NULL;
542   //a_delay = 0; THIS IS CONFIGURATION INFO
543 }
544
545 ////////////////////////////////////////////////////////////////////////////////////////////////////////
546 // TestStepWait
547 ////////////////////////////////////////////////////////////////////////////////////////////////////////
548 void TestStepWait::setCondition(bool fromEntity,
549     const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
550     const std::string &sessionId, const std::string &resultCode,
551     const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
552
553   a_condition.setReceivedFromEntity(fromEntity);
554   a_condition.setCode(code);
555   a_condition.setBitR(bitR);
556   a_condition.setResultCode(resultCode);
557   a_condition.setSessionId(sessionId);
558   a_condition.setHopByHop(hopByHop);
559   a_condition.setMsisdn(msisdn);
560   a_condition.setImsi(imsi);
561   a_condition.setServiceContextId(serviceContextId);
562 }
563
564 void TestStepWait::setConditionRegexpHex(bool fromEntity, const std::string &regexp) throw() {
565   a_condition.setReceivedFromEntity(fromEntity);
566   a_condition.setRegexpHex(regexp);
567 }
568
569 void TestStepWait::setConditionRegexpXml(bool fromEntity, const std::string &regexp) throw() {
570   a_condition.setReceivedFromEntity(fromEntity);
571   a_condition.setRegexpXml(regexp);
572 }
573
574 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
575 throw() {
576   anna::xml::Node* result = TestStep::asXML(parent);
577   //parent->createChild("TestStepWait");
578   std::string msg = "", xmlmsg = "";
579
580   // Condition
581   a_condition.asXML(result);
582
583   // Message
584   if (TestManager::instantiate().getDumpHex()) {
585     if (a_message.isEmpty()) {
586       msg = "<empty>";
587     }
588     else {
589       msg = "\n"; msg += a_message.asString(); msg += "\n";
590     }
591   }
592
593   if (a_message.isEmpty()) {
594       xmlmsg = "<empty>";
595   }
596   else {
597     if (decodeMessage()) {
598       xmlmsg = "\n";
599       xmlmsg += a_messageCodec->asXMLString();
600       xmlmsg += "\n";
601     }
602     else {
603       xmlmsg = "<unable to decode, check traces>"; 
604     }
605   }
606
607   if (msg != "") result->createAttribute("MatchedMessage", msg);
608   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
609   if (a_clientSession) result->createAttribute("ClientSessionOrigin", anna::functions::asString("%p", a_clientSession));
610   if (a_serverSession) result->createAttribute("ServerSessionOrigin", anna::functions::asString("%p", a_serverSession));
611
612   return result;
613 }
614
615 bool TestStepWait::do_execute() throw() {
616   return a_completed;
617 }
618
619 void TestStepWait::do_complete() throw() {
620   //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
621   // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
622 }
623
624 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
625   if (a_condition.comply(db/*, matchSessionId*/)) {
626     a_message = db; // store matched
627     complete();
628     return true;
629   }
630
631   return false;
632 }
633
634 void TestStepWait::do_reset() throw() {
635   a_message.clear();
636   a_clientSession = NULL;
637   a_serverSession = NULL;
638 }
639
640 ////////////////////////////////////////////////////////////////////////////////////////////////////////
641 // TestStepCmd
642 ////////////////////////////////////////////////////////////////////////////////////////////////////////
643 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
644 throw() {
645   anna::xml::Node* result = TestStep::asXML(parent);
646   //parent->createChild("TestStepCmd");
647
648   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
649   if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
650   if (a_threadRunning) {
651     if (a_childPid != -1)
652       result->createAttribute("ChildPid", a_childPid);
653   }
654   else {
655     if (a_resultCode != -2) {
656       result->createAttribute("ResultCode", a_resultCode);
657       //if (a_output != "") result->createAttribute("Output", a_output);
658     }
659   }
660
661   return result;
662 }
663
664 bool TestStepCmd::do_execute() throw() {
665   if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
666     // Special tags to replace:
667     std::string cmd = getScript();
668     size_t index;
669     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
670       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
671     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
672       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
673     while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
674       cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
675
676     a_thread = std::thread(cmdRunOnThread, this, cmd);
677     //a_thread = std::thread(cmdRunOnThreadWithFork, this, cmd);
678
679     a_thread.detach();
680   }
681
682   return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
683   // We must implement a interrupt procedure for the thread on reset call... TODO !
684 }
685
686 void TestStepCmd::do_complete() throw() {
687
688   a_threadRunning = false;
689   if (a_threadDeprecated) {
690     a_threadDeprecated = false;
691     do_reset();
692     setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
693     a_testCase->setState(TestCase::State::Failed);
694     return; // ignore TODO: interrupt the thread to avoid execution of the script
695   }
696
697   if (getResultCode() != 0)
698     a_testCase->setState(TestCase::State::Failed);
699   else
700     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
701   // TODO, avoid this recursion
702 }
703
704 void TestStepCmd::do_reset() throw() {
705
706     if (a_threadRunning) {
707       std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
708       LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
709       a_threadDeprecated = true;
710     }
711 //  if (a_threadRunning) {
712 //    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());
713 //    LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
714 //    kill (a_childPid, SIGKILL);
715 //  }
716
717   a_resultCode = -2;
718   a_errorMsg = "";
719   //a_output = "";
720   a_childPid = -1;
721 }
722