Comments and popen solution (commented)
[anna.git] / example / diameter / launcher / testing / TestStep.cpp
index 076a227..491ec65 100644 (file)
@@ -8,6 +8,13 @@
 
 // Standard
 #include <string>
+#include <iostream>
+#include <errno.h>
+
+#include <signal.h>    // sigaction, sigemptyset, struct sigaction, SIGCHLD, SA_RESTART, SA_NOCLDSTOP
+#include <stdio.h>     // perror
+#include <stdlib.h>    // exit
+#include <sys/wait.h>  // waitpid, pid_t, WNOHANG
 
 // Project
 #include <anna/xml/Compiler.hpp>
 #include <TestTimer.hpp>
 
 
+namespace {
+
+  void handle_sigchld(int sig) {
+    while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
+  }
+
+  void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
+
+    // Thread running:
+    step->setThreadRunning(true);
+
+    int status = -2;
+
+    struct sigaction sa;
+    sa.sa_handler = &handle_sigchld;
+    sigemptyset(&sa.sa_mask);
+    sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
+    if (sigaction(SIGCHLD, &sa, 0) != -1) {
+      status = system(cmd.c_str());
+     /* POPEN version:
+      char readbuf[256];
+      FILE *fp = popen(cmd.c_str(), "r");
+      if (fp) {
+        while(fgets(readbuf, sizeof(readbuf), fp))
+          step->appendOutput("\n");
+          step->appendOutput(readbuf);
+          status = pclose(fp);
+      }
+      else {
+        status = -1;
+      }
+      */
+    }
+    else {
+      perror(0);
+    }
+    // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
+    // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
+    //   perror(0);
+    //   exit(1);
+    // }
+
+    if (status < 0) {
+      char buf[256];
+      char const * str = strerror_r(errno, buf, 256);
+      step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
+    }
+
+    step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
+    step->complete();
+    // TODO: terminate thread when deprecated (RT signal ?)
+    // TODO: mutex the step while setting data here !!
+  }
+}
+
+
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 // TestStep
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -42,7 +105,7 @@ void TestStep::initialize(TestCase *testCase) {
 
 const char* TestStep::asText(const Type::_v type)
 throw() {
-  static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait" };
+  static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
   return text [type];
 }
 
@@ -75,20 +138,20 @@ std::string TestStep::asXMLString() const throw() {
 }
 
 bool TestStep::execute() throw() {
-  LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s for Test Case %llu (%p) (%p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
+  LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
   setBeginTimestamp(anna::functions::millisecond());
   return do_execute();
 }
 
 void TestStep::complete() throw() {
-  LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s for Test Case %llu (%p) (%p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
+  LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
   a_completed = true;
   setEndTimestamp(anna::functions::millisecond());
   do_complete();
 }
 
 void TestStep::reset() throw() {
-  LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s for Test Case %llu (%p) (%p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
+  LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
   // type and testCase kept
   a_completed = false;
   a_beginTimestamp = 0;
@@ -161,15 +224,19 @@ anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
 throw() {
   anna::xml::Node* result = TestStep::asXML(parent);
   //parent->createChild("TestStepSendxml");
+  std::string msg = "", xmlmsg = "";
 
   // Message
-  std::string msg = "", xmlmsg = "";
-  if (a_message.isEmpty()) {
-    msg = "<empty>";
+  if (TestManager::instantiate().getDumpHex()) {
+    if (a_message.isEmpty()) {
+      msg = "<empty>";
+    }
+    else {
+      msg = "\n"; msg += a_message.asString(); msg += "\n";
+    }
   }
-  else {
-    msg = "\n"; msg += a_message.asString(); msg += "\n";
-    // Helper
+
+  if (!a_message.isEmpty()) {
     try {
       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
@@ -181,9 +248,11 @@ throw() {
     }
   }
 
-  result->createAttribute("Message", msg);
+  if (msg != "") result->createAttribute("Message", msg);
   if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
   result->createAttribute("Expired", (a_expired ? "yes":"no"));
+  if (a_waitForRequestStepNumber != -1)
+    result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
 
   return result;
 }
@@ -193,62 +262,56 @@ bool TestStepSendxml::do_execute() throw() {
   bool success = false;
   std::string failReason, s_warn;
 
-  // Update sequence for answers:
-  if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
-    // Request which was received:
-    const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
-    const anna::DataBlock &request = tsw->getMsgDataBlock();
-    anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
-    anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
-    // Update sequence:
-    anna::diameter::codec::functions::setHopByHop(a_message, hbh);
-    anna::diameter::codec::functions::setEndToEnd(a_message, ete);
-
-    // Check Session-Id for warning ...
-    std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
-    std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
-    if (sessionIdRequest != sessionIdAnswer) {
-      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());
-      LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
-      a_testCase->addDebugSummaryHint(s_warn);
+  try {
+    // Update sequence for answers:
+    if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
+      // Request which was received:
+      const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
+      const anna::DataBlock &request = tsw->getMsgDataBlock();
+      anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
+      anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
+      // Update sequence:
+      anna::diameter::codec::functions::setHopByHop(a_message, hbh);
+      anna::diameter::codec::functions::setEndToEnd(a_message, ete);
+
+      // Check Session-Id for warning ...
+      std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
+      std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
+      if (sessionIdRequest != sessionIdAnswer) {
+        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());
+        LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
+        a_testCase->addDebugSummaryHint(s_warn);
+      }
     }
-  }
 
-  if (getType() == Type::Sendxml2e) {
-    MyDiameterEntity *entity = a_realmNode->getEntity();
-    if (entity) {
-      try {
+    if (getType() == Type::Sendxml2e) {
+      MyDiameterEntity *entity = a_realmNode->getEntity();
+      if (entity) {
         //msg->clearBody();
         msg->setBody(a_message);
         /* response = NULL =*/entity->send(msg);
         success = true;
-      } catch(anna::RuntimeException &ex) {
-        ex.trace();
-        failReason = ex.asString();
+      }
+      else {
+        failReason = "There is no diameter entity currently configured. Unable to send the message";
+        LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
       }
     }
-    else {
-      failReason = "There is no diameter entity currently configured. Unable to send the message";
-      LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
-    }
-  }
-  else if (getType() == Type::Sendxml2c) {
-    MyLocalServer *localServer = a_realmNode->getDiameterServer();
-    if (localServer) {
-      try {
+    else if (getType() == Type::Sendxml2c) {
+      MyLocalServer *localServer = a_realmNode->getDiameterServer();
+      if (localServer) {
         //msg->clearBody();
         msg->setBody(a_message);
         /* response = NULL =*/localServer->send(msg);
         success = true;
-      } catch(anna::RuntimeException &ex) {
-        ex.trace();
-        failReason = ex.asString();
+      }
+      else {
+        failReason = "There is no diameter local server currently configured. Unable to send the message";
+        LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
       }
     }
-    else {
-      failReason = "There is no diameter local server currently configured. Unable to send the message";
-      LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
-    }
+  } catch(anna::RuntimeException &ex) {
+    failReason = ex.asString();
   }
 
   // release msg
@@ -265,10 +328,6 @@ bool TestStepSendxml::do_execute() throw() {
   return success; // go next if sent was OK
 }
 
-void TestStepSendxml::do_complete() throw() {
-  next();
-}
-
 void TestStepSendxml::do_reset() throw() {
   a_expired = false;
   //a_message.clear();
@@ -302,7 +361,7 @@ bool TestStepDelay::do_execute() throw() {
 
 void TestStepDelay::do_complete() throw() {
   a_timer = NULL;
-  next();
+  next(); // next() invoked here because execute() is always false for delay and never advance the iterator
 }
 
 void TestStepDelay::do_reset() throw() {
@@ -344,25 +403,36 @@ anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
 throw() {
   anna::xml::Node* result = TestStep::asXML(parent);
   //parent->createChild("TestStepWait");
+  std::string msg = "", xmlmsg = "";
 
   // Condition
   a_condition.asXML(result);
 
+  // Message
+  if (TestManager::instantiate().getDumpHex()) {
+    if (a_message.isEmpty()) {
+      msg = "<empty>";
+    }
+    else {
+      msg = "\n"; msg += a_message.asString(); msg += "\n";
+    }
+  }
+
   if (!a_message.isEmpty()) {
-    // Message
-    result->createAttribute("MatchedMessage", a_message.asString());
-    // Helper
     try {
       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
       static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
       codecMsg.decode(a_message);
-      result->createAttribute("MatchedXMLMessage", codecMsg.asXMLString());
+      xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
     }
     catch (anna::RuntimeException &ex) {
       ex.trace();
     }
   }
 
+  if (msg != "") result->createAttribute("MatchedMessage", msg);
+  if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
+
   return result;
 }
 
@@ -371,7 +441,7 @@ bool TestStepWait::do_execute() throw() {
 }
 
 void TestStepWait::do_complete() throw() {
-  next();
+  a_testCase->process(); // next() not invoked; we only want to reactivate the test case
 }
 
 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
@@ -390,3 +460,73 @@ void TestStepWait::do_reset() throw() {
   a_serverSession = NULL;
 }
 
+////////////////////////////////////////////////////////////////////////////////////////////////////////
+// TestStepCmd
+////////////////////////////////////////////////////////////////////////////////////////////////////////
+anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent) const
+throw() {
+  anna::xml::Node* result = TestStep::asXML(parent);
+  //parent->createChild("TestStepCmd");
+
+  result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
+  result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
+  if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
+  if (!a_threadRunning && a_resultCode != -2) {
+    result->createAttribute("ResultCode", a_resultCode);
+    //if (a_output != "") result->createAttribute("Output", a_output);
+  }
+
+  return result;
+}
+
+bool TestStepCmd::do_execute() throw() {
+  if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
+    // Special tags to replace:
+    std::string cmd = getScript();
+    cmd += " ";
+    cmd += getParameters();
+    size_t index;
+    while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
+      cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
+    while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
+      cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
+    while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
+      cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
+
+    a_thread = std::thread(cmdRunOnThread, this, cmd);
+    a_thread.detach();
+  }
+
+  return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
+                // We must implement a interrupt procedure for the thread on reset call... TODO !      
+}
+
+void TestStepCmd::do_complete() throw() {
+
+  a_threadRunning = false;
+  if (a_threadDeprecated) {
+    a_threadDeprecated = false;
+    do_reset();
+    setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
+    a_testCase->setState(TestCase::State::Failed);
+    return; // ignore TODO: interrupt the thread to avoid execution of the script
+  }
+
+  if (getResultCode() != 0)
+    a_testCase->setState(TestCase::State::Failed);
+  else
+    next(); // next() invoked here because execute() is always false for delay and never advance the iterator
+}
+
+void TestStepCmd::do_reset() throw() {
+
+  if (a_threadRunning) {
+    std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
+    LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
+    a_threadDeprecated = true;
+  }
+
+  a_resultCode = -2;
+  //a_output = "";
+}
+