Fix nswering procedure: have to use source resource.
[anna.git] / example / diameter / launcher / testing / TestStep.cpp
index bf56391..c8aef4e 100644 (file)
 #include <stdlib.h>    // exit
 #include <sys/wait.h>  // waitpid, pid_t, WNOHANG
 
-
 // Project
 #include <anna/xml/Compiler.hpp>
 #include <anna/core/util/Millisecond.hpp>
 #include <anna/diameter.comm/Message.hpp>
+#include <anna/diameter.comm/ClientSession.hpp>
+#include <anna/diameter.comm/ServerSession.hpp>
+#include <anna/diameter.comm/Server.hpp>
 #include <anna/core/tracing/Logger.hpp>
+#include <anna/diameter/codec/Message.hpp>
 #include <anna/diameter/codec/functions.hpp>
 #include <anna/diameter/helpers/base/functions.hpp>
 
@@ -39,7 +42,7 @@
 namespace {
 
   void handle_sigchld(int sig) {
-    while (waitpid((pid_t)(-1), 0, WNOHANG|WNOWAIT) > 0) {}
+    while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
   }
 
   void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
@@ -47,35 +50,71 @@ namespace {
     // Thread running:
     step->setThreadRunning(true);
 
-    // Result code:
-    int rc = 1;
+    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) {
-      rc = system(cmd.c_str());
+      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 (rc < 0) {
+    if (status < 0) {
       char buf[256];
       char const * str = strerror_r(errno, buf, 256);
-      step->setErrorMsg(anna::functions::asString("errno = %d(%s)", errno, str));
-      //std::terminate;
-    }
-    else {
-      rc >>= 8; // divide by 256
+      step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
     }
 
-    step->setResultCode(rc);
+    step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
     step->complete();
-    // TODO: timeout the system call
+    // TODO: terminate thread when deprecated (RT signal ?)
     // TODO: mutex the step while setting data here !!
   }
+
+  bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message *messageCodec) throw() {
+
+    if (message.isEmpty())
+      return false;
+
+    bool result = true;
+    try {
+      if (!messageCodec) {
+        Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
+        messageCodec = new anna::diameter::codec::Message(my_app.getCodecEngine());
+      }
+
+      messageCodec->decode(message);
+    }
+    catch (anna::RuntimeException &ex) {
+      ex.trace();
+      result = false;
+    }
+
+    return result;
+  }
+
 }
 
 
@@ -208,6 +247,11 @@ void TestStepTimeout::do_reset() throw() {
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 // TestStepSendxml
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
+TestStepSendxml::~TestStepSendxml() {
+  delete a_messageCodec;
+  a_messageCodec = NULL;
+}
+
 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
 throw() {
   anna::xml::Node* result = TestStep::asXML(parent);
@@ -224,16 +268,10 @@ throw() {
     }
   }
 
-  if (!a_message.isEmpty()) {
-    try {
-      Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
-      static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
-      codecMsg.decode(a_message);
-      xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
-    }
-    catch (anna::RuntimeException &ex) {
-      ex.trace();
-    }
+  if (decodeMessage(a_message, a_messageCodec)) {
+    xmlmsg = "\n";
+    xmlmsg += a_messageCodec->asXMLString();
+    xmlmsg += "\n";
   }
 
   if (msg != "") result->createAttribute("Message", msg);
@@ -246,15 +284,22 @@ throw() {
 }
 
 bool TestStepSendxml::do_execute() throw() {
-  anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
   bool success = false;
   std::string failReason, s_warn;
+  MyDiameterEntity *entity = a_realmNode->getEntity(); // by default
+  MyLocalServer *localServer = a_realmNode->getDiameterServer(); // by default
+  const TestStepWait *tsw = NULL;
+
+  // Create comm message:
+  anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
+  //msg->clearBody();
+  msg->setBody(a_message);
 
   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));
+      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);
@@ -273,31 +318,81 @@ bool TestStepSendxml::do_execute() throw() {
     }
 
     if (getType() == Type::Sendxml2e) {
-      MyDiameterEntity *entity = a_realmNode->getEntity();
-      if (entity) {
-        //msg->clearBody();
-        msg->setBody(a_message);
-        /* response = NULL =*/entity->send(msg);
-        success = true;
+      anna::diameter::comm::ClientSession *usedClientSession = NULL;
+
+      if (tsw) { // is an answer for a received request on wait condition
+        anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
+        if (clientSession) {
+          /* response NULL (is an answer) */clientSession->send(msg);
+          success = true;
+          usedClientSession = clientSession;
+        }
+        else {
+          failReason = "Reference wait step didn't store a valid client session. 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));
+        if (entity) {
+          success = entity->send(msg);
+          anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
+          usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
+        }
+        else {
+          failReason = "There is no diameter entity currently configured. Unable to send the message";
+          LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
+        }
+      } // else (normal sending)
+
+      // Detailed log:
+      if(a_realmNode->logEnabled()) {
+        if (!a_messageCodec)
+          decodeMessage(a_message, a_messageCodec);
+
+        if (a_messageCodec) {
+          std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
+          a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
+        }
       }
     }
     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;
+      anna::diameter::comm::ServerSession *usedServerSession = NULL;
+
+      if (tsw) { // is an answer for a received request on wait condition
+        anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
+        if (serverSession) {
+          /* response NULL (is an answer) */serverSession->send(msg);
+          success = true;
+          usedServerSession = serverSession;
+        }
+        else {
+          failReason = "Reference wait step didn't store a valid server session. 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));
+        if (localServer) {
+          success = localServer->send(msg);
+          usedServerSession = localServer->getLastUsedResource();
+        }
+        else {
+          failReason = "There is no diameter local server currently configured. Unable to send the message";
+          LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
+        }
+      } // else (normal sending)
+
+      // Detailed log:
+      if(a_realmNode->logEnabled()) {
+        if (!a_messageCodec)
+          decodeMessage(a_message, a_messageCodec);
+
+        if (a_messageCodec) {
+          std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
+          a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
+        }
       }
     }
+
   } catch(anna::RuntimeException &ex) {
     failReason = ex.asString();
   }
@@ -366,6 +461,11 @@ void TestStepDelay::do_reset() throw() {
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 // TestStepWait
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
+TestStepWait::~TestStepWait() {
+  delete a_messageCodec;
+  a_messageCodec = NULL;
+}
+
 void TestStepWait::setCondition(bool fromEntity,
                                   const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
                                   const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
@@ -406,16 +506,10 @@ throw() {
     }
   }
 
-  if (!a_message.isEmpty()) {
-    try {
-      Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
-      static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
-      codecMsg.decode(a_message);
-      xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
-    }
-    catch (anna::RuntimeException &ex) {
-      ex.trace();
-    }
+  if (decodeMessage(a_message, a_messageCodec)) {
+    xmlmsg = "\n";
+    xmlmsg += a_messageCodec->asXMLString();
+    xmlmsg += "\n";
   }
 
   if (msg != "") result->createAttribute("MatchedMessage", msg);
@@ -434,7 +528,8 @@ void TestStepWait::do_complete() throw() {
 
 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
   if (a_condition.comply(db/*, matchSessionId*/)) {
-    a_message = db; // store matched
+    //a_message = db; // store matched
+    a_message.assign(db);
     complete();
     return true;
   }
@@ -458,7 +553,6 @@ throw() {
 
   result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
   result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
-  result->createAttribute("CommandInProgress", a_threadRunning ? "yes":"no");
   if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
   if (!a_threadRunning && a_resultCode != -2) {
     result->createAttribute("ResultCode", a_resultCode);
@@ -469,7 +563,7 @@ throw() {
 }
 
 bool TestStepCmd::do_execute() throw() {
-  if (!a_threadRunning) {
+  if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
     // Special tags to replace:
     std::string cmd = getScript();
     cmd += " ";
@@ -486,7 +580,8 @@ bool TestStepCmd::do_execute() throw() {
     a_thread.detach();
   }
 
-  return false; // don't go next (wait complete)
+  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() {
@@ -495,6 +590,8 @@ void TestStepCmd::do_complete() throw() {
   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
   }