Allow values lesser than 600000 msecs in launcher timex Engine. Warning over 5 minute...
[anna.git] / example / diameter / launcher / Launcher.cpp
index e4ea4ca..8804736 100644 (file)
@@ -14,6 +14,7 @@
 #include <anna/diameter/helpers/base/functions.hpp>
 #include <anna/diameter/helpers/dcca/functions.hpp>
 #include <anna/time/functions.hpp>
+#include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
 
 // Process
 #include "Launcher.hpp"
@@ -21,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();
@@ -281,7 +282,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: ";
@@ -289,6 +290,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;
@@ -319,6 +327,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->setProgrammedAnswersCodecEngine(getCodecEngine());
   int allowedInactivityTime = 90000; // ms
 
   if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
@@ -334,7 +343,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
 
@@ -359,13 +368,85 @@ throw(anna::RuntimeException) {
   a_start_time.setNow();
   // Statistics:
   anna::statistics::Engine::instantiate().enable();
+
+  // Checking command line parameters
+  if(cl.exists("sessionBasedModelsClientSocketSelection")) {
+    std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
+
+    if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
+      throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
+    }
+  }
+
+  // Tracing:
+  if(cl.exists("trace"))
+    anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
+
+  LOGINFORMATION(
+    // Help on startup traces:
+    anna::Logger::information(help(), ANNA_FILE_LOCATION);
+    // Test messages dtd:
+    std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
+    msg += anna::diameter::codec::MessageDTD;
+    anna::Logger::information(msg, ANNA_FILE_LOCATION);
+  );
+
+  // HTTP Server:
+  if(cl.exists("httpServer")) {
+    anna::comm::Network& network = anna::comm::Network::instantiate();
+    std::string address;
+    int port;
+    anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
+    //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
+    const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
+    a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
+  }
+
+  // Stack:
+  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:
+  anna::Tokenizer lst;
+  std::string dictionaryParameter = cl.getValue("dictionary");
+  lst.apply(dictionaryParameter, ",");
+
+  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;
+    std::string pathFile;
+    d->allowUpdates();
+
+    for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
+      pathFile = anna::Tokenizer::data(tok_iter);
+      d->load(pathFile);
+    }
+  }
+
+  getCodecEngine()->setDictionary(d);
+  LOGDEBUG(anna::Logger::debug(getCodecEngine()->asString(), ANNA_FILE_LOCATION));
+
+  if(lst.size() > 1) {
+    std::string all_in_one = "./dictionary-all-in-one.xml";
+    std::ofstream out(all_in_one.c_str(), std::ifstream::out);
+    std::string buffer = d->asXMLString();
+    out.write(buffer.c_str(), buffer.size());
+    out.close();
+    std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
+  }
+
   ///////////////////////////////
   // Diameter library COUNTERS //
   ///////////////////////////////
   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
+  oamDiameterComm.enableCounters();
+  oamDiameterComm.enableAlarms();
   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
+  oamDiameterCodec.enableCounters();
+  oamDiameterCodec.enableAlarms();
   /////////////////
   // COMM MODULE //
   /////////////////
@@ -463,6 +544,18 @@ throw(anna::RuntimeException) {
   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
+  ///////////////////////////////////////////
+  // APPLICATION MESSAGE OAM MODULE SCOPES //
+  ///////////////////////////////////////////
+  // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
+  anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
+  int scope_id = 3;
+  for (anna::diameter::stack::Engine::const_stack_iterator it = stackEngine.stack_begin(); it != stackEngine.stack_end(); it++) {
+    appMsgOamModule.createStackCounterScope(scope_id, it->first);
+    scope_id++;
+  }
+  appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
+
 
   /////////////////////////////////
   // Counter recorder associated //
@@ -470,83 +563,16 @@ throw(anna::RuntimeException) {
   if(a_counterRecorderClock) {
     oamDiameterComm.setCounterRecorder(a_counterRecorder);
     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
+    appMsgOamModule.setCounterRecorder(a_counterRecorder);
     a_timeEngine->activate(a_counterRecorderClock); // start clock
   }
 
-  // Checking command line parameters
-  if(cl.exists("sessionBasedModelsClientSocketSelection")) {
-    std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
-
-    if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
-      throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
-    }
-  }
-
-  // Tracing:
-  if(cl.exists("trace"))
-    anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
-
-  LOGINFORMATION(
-    // Help on startup traces:
-    anna::Logger::information(help(), ANNA_FILE_LOCATION);
-    // Test messages dtd:
-    std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
-    msg += anna::diameter::codec::MessageDTD;
-    anna::Logger::information(msg, ANNA_FILE_LOCATION);
-  );
-
-  // HTTP Server:
-  if(cl.exists("httpServer")) {
-    anna::comm::Network& network = anna::comm::Network::instantiate();
-    std::string address;
-    int port;
-    anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
-    //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
-    const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
-    a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
-  }
-
-  // Stack:
-  anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
-  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:
-  anna::Tokenizer lst;
-  std::string dictionaryParameter = cl.getValue("dictionary");
-  lst.apply(dictionaryParameter, ",");
-
-  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;
-    std::string pathFile;
-    d->allowUpdates();
-
-    for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
-      pathFile = anna::Tokenizer::data(tok_iter);
-      d->load(pathFile);
-    }
-  }
-
-  codecEngine->setDictionary(d);
-  LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
-
-  if(lst.size() > 1) {
-    std::string all_in_one = "./dictionary-all-in-one.xml";
-    std::ofstream out(all_in_one.c_str(), std::ifstream::out);
-    std::string buffer = d->asXMLString();
-    out.write(buffer.c_str(), buffer.size());
-    out.close();
-    std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
-  }
-
-
 
   // 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);
+    getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
   }
 
   // Fix mode
@@ -558,10 +584,10 @@ 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);
   }
 
-  codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
+  getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
 
   // Diameter Server:
   if(cl.exists("diameterServer"))
@@ -618,6 +644,7 @@ throw(anna::RuntimeException) {
       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->setProgrammedAnswersCodecEngine(getCodecEngine());
       a_entity->bind();
     }
   }
@@ -911,9 +938,9 @@ std::string Launcher::gotoBurst(int order) throw() {
 }
 
 void Launcher::resetCounters() throw() {
-  // Diameter::comm module:
-  anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
-  oamDiameterComm.resetCounters();
+  anna::diameter::comm::OamModule::instantiate().resetCounters();
+  anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
+  anna::diameter::codec::OamModule::instantiate().resetCounters();
 }
 
 void Launcher::signalUSR2() throw(anna::RuntimeException) {
@@ -1001,21 +1028,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";
@@ -1041,9 +1068,13 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
   result += "\n                                      server socket.";
+  result += "\ncontext|[target file]                Application context could also be written by mean this operation,";
+  result += "\n                                      and not only through SIGUSR1. If optional path file is missing,";
+  result += "\n                                      default '/var/tmp/anna.context.<pid>' will be used.";
   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
-  result += "\n                                      performance measurement. Context data is written at";
-  result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
+  result += "\n                                      performance measurement. Context data can be written at";
+  result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
+  result += "\n                                      or sending operation 'context|[target file]'.";
   result += "\nforceCountersRecord                  Forces dump to file the current counters of the process.";
   result += "\n";
   result += "\n<visibility action>|[<address>:<port>]|[socket id]";
@@ -1272,6 +1303,13 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
 
   // Operations:
+  if(opType == "context") {
+    std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
+    writeContext(contextFile);
+    response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
+    return;
+  }
+
   if(opType == "code") {
     codecMsg.loadXML(param1);
     std::string hexString = anna::functions::asHexString(codecMsg.code());
@@ -1525,8 +1563,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);
       LOGDEBUG
       (
         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
@@ -1558,8 +1595,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);
       LOGDEBUG
       (
         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
@@ -1695,9 +1731,10 @@ 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);
   // OAM:
   anna::diameter::comm::OamModule::instantiate().asXML(result);
+  anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
   anna::diameter::codec::OamModule::instantiate().asXML(result);
   // Statistics:
   anna::statistics::Engine::instantiate().asXML(result);