Fix retransmission issues (order, tracing, etc.)
[anna.git] / example / diameter / launcher / Launcher.cpp
index edb1de0..afb8a96 100644 (file)
@@ -22,7 +22,7 @@
 
 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
-
+#define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine"
 
 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
   a_myDiameterEngine = new MyDiameterEngine();
@@ -58,16 +58,14 @@ void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
   a_commMessages.release(msg);
 }
 
-anna::diameter::codec::Message *Launcher::createCodecMessage() throw(anna::RuntimeException) {
-  return a_codecMessages.create();
-}
+void Launcher::baseProtocolSetupAsClient() throw(anna::RuntimeException) {
 
-void Launcher::releaseCodecMessage(anna::diameter::codec::Message *msg) throw() {
-  a_codecMessages.release(msg);
-}
+  anna::diameter::codec::Engine *codecEngine;
+
+  codecEngine = getCodecEngine();
+  // XXXXXXXXXXXXXXXXXXXX codecEngine = a_myDiameterEngine->getBaseProtocolCodecEngine();
 
 
-void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
   // Build CER
   //   <CER> ::= < Diameter Header: 257, REQ >
   //             { Origin-Host } 264 diameterIdentity
@@ -79,7 +77,7 @@ void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
   //           * [ Supported-Vendor-Id ]  265 Unsigned32
   //           * [ Auth-Application-Id ] 258 Unsigned32
   //           * [Acct-Application-Id]  259 Unsigned32
-  anna::diameter::codec::Message diameterCER;
+  anna::diameter::codec::Message diameterCER(codecEngine);
   int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
   std::string OH = a_myDiameterEngine->getHost();
   std::string OR = a_myDiameterEngine->getRealm();
@@ -111,7 +109,7 @@ void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
   //   <DWR>  ::= < Diameter Header: 280, REQ >
   //              { Origin-Host }
   //              { Origin-Realm }
-  anna::diameter::codec::Message diameterDWR;
+  anna::diameter::codec::Message diameterDWR(codecEngine);
   loadingError = false;
 
   try {
@@ -129,77 +127,14 @@ void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
   }
 
-//////////////////////////
-// IDEM FOR CEA AND DWA //
-//////////////////////////
-//            // Build CER
-//            //   <CER> ::= < Diameter Header: 257, REQ >
-//            //             { Origin-Host } 264 diameterIdentity
-//            //             { Origin-Realm } 296 idem
-//            //          1* { Host-IP-Address } 257, address
-//            //             { Vendor-Id } 266 Unsigned32
-//            //             { Product-Name } 269 UTF8String
-//            //             [Origin-State-Id] 278 Unsigned32
-//            //           * [ Supported-Vendor-Id ]  265 Unsigned32
-//            //           * [ Auth-Application-Id ] 258 Unsigned32
-//            //           * [Acct-Application-Id]  259 Unsigned32
-//            anna::diameter::codec::Message diameterCER;
-//            int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
-//            std::string OH = a_myDiameterEngine->getHost();
-//            std::string OR = a_myDiameterEngine->getRealm();
-//            std::string hostIP = anna::functions::getHostnameIP(); // Address
-//            int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
-//            std::string productName = "ANNA Diameter Launcher"; // UTF8String
-//            bool loadingError = false;
-//
-//            try {
-//               diameterCER.loadXML("cer.xml");
-//            } catch (anna::RuntimeException &ex) {
-//               ex.trace();
-//               loadingError = true;
-//            }
-//
-//            if (loadingError) {
-//               LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
-//               diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
-//               diameterCER.setApplicationId(applicationId);
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
-//               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
-//            }
-//
-//            // Build DWR
-//            //   <DWR>  ::= < Diameter Header: 280, REQ >
-//            //              { Origin-Host }
-//            //              { Origin-Realm }
-//            anna::diameter::codec::Message diameterDWR;
-//            loadingError = false;
-//
-//            try {
-//               diameterDWR.loadXML("dwr.xml");
-//            } catch (anna::RuntimeException &ex) {
-//               ex.trace();
-//               loadingError = true;
-//            }
-//
-//            if (loadingError) {
-//               LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
-//               diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
-//               diameterDWR.setApplicationId(applicationId);
-//               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
-//               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
-//            }
   // Assignment for CER/DWR and CEA/DWA:
   a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
   //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
 }
 
-void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
+void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail, anna::diameter::codec::Engine *codecEngine) const throw() {
 //   if (!logEnabled()) return;
-  anna::diameter::codec::Message codecMsg;
+  anna::diameter::codec::Message codecMsg(codecEngine);
   try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
   writeLogFile(codecMsg, logExtension, detail);
 
@@ -282,7 +217,7 @@ void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional
   if(anna::functions::isLike("^[0-9]+$", parameter)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
     int msecs = cl.getIntegerValue(commandLineParameter);
 
-    if(msecs > a_timeEngine->getMaxTimeout()) {
+    if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
       std::string msg = "Commandline parameter '";
       msg += commandLineParameter;
       msg += "' is greater than allowed max timeout for timming engine: ";
@@ -290,6 +225,13 @@ void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional
       throw RuntimeException(msg, ANNA_FILE_LOCATION);
     }
 
+    if(msecs > 300000) {
+      std::string msg = "Commandline parameter '";
+      msg += commandLineParameter;
+      msg += "' is perhaps very big (over 5 minutes). Take into account memory consumption issues.";
+      LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+    }
+
     if(msecs <= a_timeEngine->getResolution()) {
       std::string msg = "Commandline parameter '";
       msg += commandLineParameter;
@@ -320,6 +262,7 @@ void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::Runti
   //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
   a_diameterLocalServer = (MyLocalServer*)(a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions));
   a_diameterLocalServer->setDescription("Launcher diameter local server");
+  a_diameterLocalServer->setCodecEngine(getCodecEngine()); // this is for automatic answers (failed-avp) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX el del nodo correspondiente
   int allowedInactivityTime = 90000; // ms
 
   if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
@@ -335,7 +278,7 @@ throw(anna::RuntimeException) {
 //   if (cl.exists ("clone"))
 //      workMode = anna::comm::Communicator::WorkMode::Clone;
   a_communicator = new MyCommunicator(workMode);
-  a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
+  a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, (anna::Millisecond)150);
   // Counters record procedure:
   anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
 
@@ -395,7 +338,7 @@ throw(anna::RuntimeException) {
   }
 
   // Stack:
-  anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
+  a_codecEngine = new anna::diameter::codec::Engine(DIAMETER_CODEC_ENGINE_NAME_PREFIX);
   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
   anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
   // Analyze comma-separated list:
@@ -403,7 +346,7 @@ throw(anna::RuntimeException) {
   std::string dictionaryParameter = cl.getValue("dictionary");
   lst.apply(dictionaryParameter, ",");
 
-  if(lst.size() >= 1) {  // always true (at least one, because -dictionary is mandatory)
+  if(lst.size() >= 1) {  // always true (at least one, because --dictionary is mandatory)
     anna::Tokenizer::const_iterator tok_min(lst.begin());
     anna::Tokenizer::const_iterator tok_max(lst.end());
     anna::Tokenizer::const_iterator tok_iter;
@@ -416,8 +359,8 @@ throw(anna::RuntimeException) {
     }
   }
 
-  codecEngine->setDictionary(d);
-  LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
+  getCodecEngine()->setDictionary(d); // XXXX esto cambiara...
+  LOGDEBUG(anna::Logger::debug(getCodecEngine()->asString(), ANNA_FILE_LOCATION));
 
   if(lst.size() > 1) {
     std::string all_in_one = "./dictionary-all-in-one.xml";
@@ -563,8 +506,8 @@ throw(anna::RuntimeException) {
   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
   if(cl.exists("integrationAndDebugging")) {
-    codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
-    codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
+    getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // XXXXXXXXXXXXXXXXXXXXXXXXX
+    getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
   }
 
   // Fix mode
@@ -576,10 +519,14 @@ throw(anna::RuntimeException) {
     else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
     else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
     else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
-    codecEngine->setFixMode(fm);
+    getCodecEngine()->setFixMode(fm); // XXXXXXXXXXXXXXXXXXXXXXX
   }
 
-  codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
+  getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); // XXXXXXXXXXXXXXXXXXXXXXX
+
+  // Base protocol for internal use (CEA, DWA, DPA and tracing:
+  a_myDiameterEngine->setBaseProtocolCodecEngine(getCodecEngine());
+
 
   // Diameter Server:
   if(cl.exists("diameterServer"))
@@ -630,12 +577,13 @@ throw(anna::RuntimeException) {
     int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
 
     if(entityServerSessions > 0) {
-      baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
+      baseProtocolSetupAsClient();
       anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
       a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
       a_entity = (MyDiameterEntity*)(a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"));
       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
+      a_entity->setCodecEngine(getCodecEngine()); // XXXXXXXXXXXXXXXXXXXXXXX
       a_entity->bind();
     }
   }
@@ -892,7 +840,7 @@ bool Launcher::sendBurstMessage(bool anyway) throw() {
     anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
     anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
     std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
-    writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
+    writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail, getCodecEngine()); // el del nodo de trabajo
   }
 
   return result;
@@ -906,7 +854,7 @@ std::string Launcher::lookBurst(int order) const throw() {
 
   if(it != a_burstMessages.end()) {
     // Decode
-    anna::diameter::codec::Message codecMsg;
+    anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXXXX el del nodo de trabajo
     try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
     result = codecMsg.asXMLString();
   }
@@ -1019,21 +967,21 @@ std::string Launcher::help() const throw() {
   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
   result += "\n";
   result += "\nAs mandatory, the stack definition given through the xml dictionary:";
-  result += "\n   -dictionary <path to dictionary file>";
+  result += "\n   --dictionary <path to dictionary file>";
   result += "\n";
   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
-  result += "\n   -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0";
+  result += "\n   --diameterServer localhost:3868 --diameterServerSessions 10 --entityServerSessions 0";
   result += "\n";
   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
-  result += "\n   -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0";
+  result += "\n   --entity 192.168.12.11:3868,192.168.12.21:3868 --entityServerSessions 10 --diameterServerSessions 0";
   result += "\n";
   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
-  result += "\n traffic at your client side you shall use '-balance' and '-sessionBasedModelsClientSocketSelection'";
+  result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
   result += "\n arguments in order to define the balancing behaviour.";
   result += "\n";
   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
-  result += "\n customized ones using '-cer <xml message file>' and '-dwr <xml message file>'.";
+  result += "\n customized ones using '--cer <xml message file>' and '--dwr <xml message file>'.";
   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
   result += "\n customized ones using operations interface.";
   result += "\n";
@@ -1148,6 +1096,7 @@ std::string Launcher::help() const throw() {
   result += "\n                           has been logged)";
   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
   result += "\n                           has been logged)";
+  result += "\n   [retry]                Request retransmission";
   result += "\n";
   result += "\n-------------------------------------------------------------------------------------------- Load tests";
   result += "\n";
@@ -1223,7 +1172,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   response_content = "Operation processed with exception. See traces\n"; // supposed
   std::string result = "";
   anna::DataBlock db_aux(true);
-  anna::diameter::codec::Message codecMsg;
+  anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXX el del nodo de trabajo
 
   ///////////////////////////////////////////////////////////////////
   // Simple operations without arguments:
@@ -1366,6 +1315,8 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
 
     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
     anna::diameter::comm::Message *msg = createCommMessage();
+    //msg->setRetries(4);
+    //msg->setOnExpiry(anna::diameter::comm::Message::OnExpiry::Retransmit);
 
     if((opType == "sendxml") || (opType == "sendxml2e")) {
       codecMsg.loadXML(param1);
@@ -1554,8 +1505,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     } else if (param1 == "dump") {
       localServer->getReactingAnswers()->dump();
     } else {
-      anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
-      anna::diameter::codec::Message *message = engine->createMessage(param1);
+      anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1); // // XXXXXXXXXXXXXX el del nodo de trabajo
       LOGDEBUG
       (
         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
@@ -1587,8 +1537,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     } else if (param1 == "dump") {
       entity->getReactingAnswers()->dump();
     } else {
-      anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
-      anna::diameter::codec::Message *message = engine->createMessage(param1);
+      anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1); // XXXXXXXXXXXXXX el del nodo de trabajo
       LOGDEBUG
       (
         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
@@ -1700,10 +1649,12 @@ int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message,
 
       if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
     }
-    //case anna::diameter::helpers::dcca::ChargingContext::SMS:
-    //case anna::diameter::helpers::dcca::ChargingContext::MMS:
-    //default:
-    //   return -1; // IEC model and Unknown traffic types
+
+    case anna::diameter::helpers::dcca::ChargingContext::SMS:
+    case anna::diameter::helpers::dcca::ChargingContext::MMS:
+    case anna::diameter::helpers::dcca::ChargingContext::Unknown:
+    default:
+       return -1;
     }
   } catch(anna::RuntimeException &ex) {
     LOGDEBUG(
@@ -1724,7 +1675,7 @@ throw() {
   result->createAttribute("StartTime", a_start_time.asString());
   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
   // Diameter:
-  (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
+  getCodecEngine()->asXML(result); // XXXXXXXXXXXXXXX todos los nodos ...
   // OAM:
   anna::diameter::comm::OamModule::instantiate().asXML(result);
   anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);