X-Git-Url: https://git.teslayout.com/public/public/public/?p=anna.git;a=blobdiff_plain;f=example%2Fdiameter%2Flauncher%2FLauncher.cpp;h=60a9cb0cfb7a0fec3dcc13f668d50713fc9af26c;hp=ff86f46449320a2f3b6936f635231e6a0b800937;hb=415985b3f67878c2e3cee785a0b1cb36f4eff901;hpb=603b76b5dc02acdfd87c58c51b6d48ae1858f58d diff --git a/example/diameter/launcher/Launcher.cpp b/example/diameter/launcher/Launcher.cpp index ff86f46..60a9cb0 100644 --- a/example/diameter/launcher/Launcher.cpp +++ b/example/diameter/launcher/Launcher.cpp @@ -11,6 +11,9 @@ #include // std::cout #include // ceil #include +#include // chdir +//#include TODO: use this from gcc4.9.0: http://stackoverflow.com/questions/8060025/is-this-c11-regex-error-me-or-the-compiler +#include // Project #include @@ -23,18 +26,22 @@ #include #include #include +#include #include +#include +#include // Process #include -#include +#include +#include #include -#include -#include +#include +#include -#define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.in" -#define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.out" +#define SIGUSR2_TASKS_INPUT_FILENAME "sigusr2.in" +#define SIGUSR2_TASKS_OUTPUT_FILENAME "sigusr2.out" const char *ServicesDTD = "\ @@ -59,56 +66,70 @@ const char *ServicesDTD = "\ -->\n\ \n\ \n\ -\n\ +\n\ \n\ \n\ @@ -122,25 +143,34 @@ Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", " //a_admlMinResolution = (anna::Millisecond)100; a_counterRecorderClock = NULL; - // a_nodes.clear(); a_workingNode = NULL; a_httpServerSocket = NULL; } +std::string Launcher::getSignalUSR2InputFile() const throw() { + return (a_initialWorkingDirectory + "/" + SIGUSR2_TASKS_INPUT_FILENAME); +} + +std::string Launcher::getSignalUSR2OutputFile() const throw() { + return (a_initialWorkingDirectory + "/" + SIGUSR2_TASKS_OUTPUT_FILENAME); +} void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) { - // + + CommandLine& cl(anna::CommandLine::instantiate()); + bool allLogsDisabled = cl.exists("disableLogs"); + + // const anna::xml::Attribute *id, *dictionary; - // - const anna::xml::Attribute *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay, + // + const anna::xml::Attribute *originHost, *appId, *originRealm, *cer, *dwr, *cea, *allowedInactivityTime, *tcpConnectDelay, *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions, *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection, *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog; - // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process // Stacks @@ -159,7 +189,6 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate(); appMsgOamModule.enableCounters(); // this special module is disabled by default (the only) static int scope_id = 3; - bool id_0_registered = false; unsigned int id_value; std::string codecEngineName; @@ -172,6 +201,11 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp dictionary = (*it)->getAttribute("dictionary"); id_value = id->getIntegerValue(); + if (stackEngine.getDictionary(id_value)) { // Ignore (but don't fail) dictionary load with same stack id already registered + LOGWARNING(anna::Logger::warning(anna::functions::asString("Ignore dictionary load for stack id already registered: %llu", id_value), ANNA_FILE_LOCATION)); + continue; + } + try { d = stackEngine.createDictionary(id_value, dictionary->getValue()); LOGDEBUG(anna::Logger::debug(anna::functions::asString("Created dictionary (%p) for stack id %llu", d, id_value), ANNA_FILE_LOCATION)); @@ -185,10 +219,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp throw ex; } - if (id_value == 0) { - id_0_registered = true; - bpd = d; - } + bpd = d; // base protocol dictionary in case of monostack. If multistack, will be calculated later // Create codec engine and register it in the codec engine manager: codecEngineName = anna::functions::asString("CodecEngineForStackId_%llu", id_value); @@ -199,7 +230,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp const anna::xml::Attribute *vm_attr = (*it)->getAttribute("validationMode", false /* no exception */); const anna::xml::Attribute *vd_attr = (*it)->getAttribute("validationDepth", false /* no exception */); const anna::xml::Attribute *fm_attr = (*it)->getAttribute("fixMode", false /* no exception */); - const anna::xml::Attribute *if_attr = (*it)->getAttribute("ignoreFlags", false /* no exception */); + const anna::xml::Attribute *if_attr = (*it)->getAttribute("ignoreFlagsOnValidation", false /* no exception */); std::string vm_value = vm_attr ? vm_attr->getValue() : "AfterDecoding"; std::string vd_value = vd_attr ? vd_attr->getValue() : "FirstError"; @@ -236,14 +267,10 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp // Basic checking for multistack: bool multistack = (stackEngine.stack_size() > 1); if (multistack) { - if(!id_0_registered) + bpd = stackEngine.getDictionary(0); + if(!bpd) throw anna::RuntimeException("In multistack applications is mandatory register a stack id = 0 using a dictionary which contains the needed elements to build base protocol messages (CER/A, DWR/A, DPR/A, STR/A, etc.)", ANNA_FILE_LOCATION); } - else { // monostack - if (!bpd) - bpd = ce->getDictionary(); // in mono-stack applications, we understand the existing stack as the used - // for base protocol, regardless if it is registered with stack id 0 or not - } // REALMS: for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) { @@ -251,11 +278,12 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp if(nodeName == "node") { // Input data: - originRealm = (*it)->getAttribute("originRealm"); + originHost = (*it)->getAttribute("originHost"); appId = (*it)->getAttribute("applicationId"); - originHost = (*it)->getAttribute("originHost", false /* no exception */); + originRealm = (*it)->getAttribute("originRealm", false /* no exception */); cer = (*it)->getAttribute("cer", false /* no exception */); dwr = (*it)->getAttribute("dwr", false /* no exception */); + cea = (*it)->getAttribute("cea", false /* no exception */); allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */); tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */); answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */); @@ -275,9 +303,10 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no) // Basic checkings: - realm_nodes_it nodeIt = a_nodes.find(originRealm->getValue()); - if (nodeIt != a_nodes.end()) { - std::string msg = "Already registered node name (Origin-Realm): "; msg += originRealm->getValue(); + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + anna::diameter::comm::OriginHost *oh = ohm.getOriginHost(originHost->getValue()); + if (oh) { + std::string msg = "Already registered such Origin-Host: "; msg += originHost->getValue(); throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); } @@ -302,11 +331,24 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp // Checking command line parameters std::string sessionBasedModelsType; + anna::diameter::comm::Entity::SessionBasedModelsType::_v sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdLowPart; if(sessionBasedModelsClientSocketSelection) { sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue(); - if((sessionBasedModelsType != "SessionIdHighPart") && (sessionBasedModelsType != "SessionIdOptionalPart") && (sessionBasedModelsType != "RoundRobin")) { - throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION); - } + if (sessionBasedModelsType == "RoundRobin") { + sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::RoundRobin; + } + else if (sessionBasedModelsType == "SessionIdOptionalPart") { + sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdOptionalPart; + } + else if (sessionBasedModelsType == "SessionIdHighPart") { + sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdHighPart; + } + else if (sessionBasedModelsType == "SessionIdLowPart") { + sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdLowPart; + } + else { + throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdLowPart'/'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION); + } } int retransmissions = retries ? retries->getIntegerValue() : 0; @@ -314,18 +356,21 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION); } - // Create new Node instance ///////////////////////////////////////////////////////////////// - a_workingNode = new RealmNode(originRealm->getValue(), applicationId, bpd); - MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine(); ///////////////////////////////////////////////////////////////////////////////////////////// - - // Assignments: + // Diameter communication engine: + std::string commEngineName = originHost->getValue() + "_DiameterCommEngine"; + MyDiameterEngine *commEngine = new MyDiameterEngine(commEngineName.c_str(), bpd); + commEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts. commEngine->setMaxConnectionDelay(tcpConnectDelayMs); commEngine->setWatchdogPeriod(watchdogPeriodMs); + commEngine->setOriginHostName(originHost->getValue()); + if (originRealm) commEngine->setOriginRealmName(originRealm->getValue()); + + // Origin host node: + a_workingNode = new anna::diameter::comm::OriginHost((anna::diameter::comm::Engine*)commEngine, applicationId); + a_workingNode->setRequestRetransmissions(retransmissions); + ///////////////////////////////////////////////////////////////////////////////////////////// - // Realm information: - if (originHost) commEngine->setHost(originHost->getValue()); - commEngine->setRealm(originRealm->getValue()); // Diameter entity: if(entity) { @@ -342,8 +387,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp // Register one entity for this engine: a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs); - a_workingNode->setRequestRetransmissions(retransmissions); - a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsType); + a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsTypeEnum); a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings if (eventOperation) a_workingNode->getEntity()->bind(); } @@ -351,30 +395,35 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp // Diameter Server: if(diameterServer) { + // Server CEA + std::string ceaPathfile = cea ? cea->getValue() : ""; + int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1; - a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs); + a_workingNode->createDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs, answersTimeoutMs, ceaPathfile); } // Logs: - std::string realm = commEngine->getRealm(); - std::string s_log = realm + ".launcher.log"; if (log) s_log = log->getValue(); - bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false); - bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false); - bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false); - std::string s_burstLog = realm + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue(); - a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog); + if (!allLogsDisabled) { + std::string host = commEngine->getOriginHostName(); + std::string s_log = host + ".launcher.log"; if (log) s_log = log->getValue(); + bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false); + bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false); + bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false); + std::string s_burstLog = host + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue(); + a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog); + } // Lazy initialization for comm engine: if (eventOperation) commEngine->lazyInitialize(); // Node and Codec Engine registration /////////////////////////////////////////////////////// - a_nodes[originRealm->getValue()] = a_workingNode; + ohm.registerOriginHost(originHost->getValue(), a_workingNode); ///////////////////////////////////////////////////////////////////////////////////////////// } } - if (!uniqueRealm()) + if (!uniqueOriginHost()) a_workingNode = NULL; // by default, mode auto // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started, @@ -468,60 +517,73 @@ anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const bool Launcher::setWorkingNode(const std::string &name) throw() { bool result = false; - realm_nodes_it nodeIt = a_nodes.find(name); - if (nodeIt == a_nodes.end()) { - LOGWARNING( - std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ..."; - anna::Logger::warning(msg, ANNA_FILE_LOCATION); - ); - } - else { - a_workingNode = const_cast(nodeIt->second); + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + anna::diameter::comm::OriginHost *oh = ohm.getOriginHost(name); + + if (oh) { + a_workingNode = const_cast(oh); result = true; } return result; } -RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw(anna::RuntimeException) { - realm_nodes_it it = a_nodes.find(realmName); - if (it != a_nodes.end()) return it->second; - throw anna::RuntimeException(anna::functions::asString("There is no realm node registered as '%s' (set Origin-Realm avp correctly or force a specific realm with 'node' operation)", realmName.c_str()), ANNA_FILE_LOCATION); +anna::diameter::comm::OriginHost *Launcher::getOriginHost(const std::string &name) const throw(anna::RuntimeException) { + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + anna::diameter::comm::OriginHost *result = ohm.getOriginHost(name); + + if (!result) + throw anna::RuntimeException(anna::functions::asString("There is no origin host registered as '%s' (set Origin-Host avp correctly or force a specific host with 'node' operation)", name.c_str()), ANNA_FILE_LOCATION); + + return result; +} + +anna::diameter::comm::OriginHost *Launcher::getOriginHost(const anna::diameter::codec::Message &message) const throw(anna::RuntimeException) { + std::string originHost = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue(); + return (getOriginHost(originHost)); } -RealmNode *Launcher::getRealmNode(const anna::diameter::codec::Message &message) const throw(anna::RuntimeException) { - std::string originRealm = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue(); - return (getRealmNode(originRealm)); +bool Launcher::uniqueOriginHost() const throw() { + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + return (ohm.size() == 1); +} + + +void Launcher::updateOperatedOriginHostWithMessage(const anna::diameter::codec::Message &message) throw(anna::RuntimeException) { + if (!a_operatedHost) // priority for working node by mean 'node' operation + a_operatedHost = getOriginHost(message); } -void Launcher::updateOperatedRealmNodeWithMessage(const anna::diameter::codec::Message &message) throw(anna::RuntimeException) { - if (!a_operatedRealm) // priority for working node by mean 'node' operation - a_operatedRealm = getRealmNode(message); +anna::diameter::comm::OriginHost *Launcher::getWorkingNode() const throw(anna::RuntimeException) { + if(!a_workingNode) + throw anna::RuntimeException("Working node not identified (try to load services)", ANNA_FILE_LOCATION); + + return a_workingNode; } -RealmNode *Launcher::getOperatedRealm() const throw(anna::RuntimeException) { - if(!a_operatedRealm) - throw anna::RuntimeException("Realm Node not identified (try to force a specific realm with 'node' operation)", ANNA_FILE_LOCATION); +anna::diameter::comm::OriginHost *Launcher::getOperatedHost() const throw(anna::RuntimeException) { + if(!a_operatedHost) + throw anna::RuntimeException("Node not identified (try to force a specific Origin-Host with 'node' operation)", ANNA_FILE_LOCATION); - return a_operatedRealm; + return a_operatedHost; } MyDiameterEntity *Launcher::getOperatedEntity() const throw(anna::RuntimeException) { - MyDiameterEntity *result = getOperatedRealm()->getEntity(); + MyDiameterEntity *result = (MyDiameterEntity *)(getOperatedHost()->getEntity()); if (!result) - throw anna::RuntimeException("No entity configured for the operated Realm Node", ANNA_FILE_LOCATION); + throw anna::RuntimeException("No entity configured for the operated node", ANNA_FILE_LOCATION); return result; } MyLocalServer *Launcher::getOperatedServer() const throw(anna::RuntimeException) { - MyLocalServer *result = getOperatedRealm()->getDiameterServer(); + MyLocalServer *result = (MyLocalServer *)(getOperatedHost()->getDiameterServer()); if (!result) - throw anna::RuntimeException("No local server configured for the operated Realm Node", ANNA_FILE_LOCATION); + throw anna::RuntimeException("No local server configured for the operated node", ANNA_FILE_LOCATION); return result; } MyDiameterEngine *Launcher::getOperatedEngine() const throw(anna::RuntimeException) { - return getOperatedRealm()->getMyDiameterEngine(); // never will be NULL + return (MyDiameterEngine *)getOperatedHost()->getCommEngine(); // never will be NULL } void Launcher::initialize() @@ -531,11 +593,18 @@ throw(anna::RuntimeException) { anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single); a_communicator = new MyCommunicator(workMode); a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, a_admlMinResolution); - TestManager::instantiate().setTimerController(a_timeEngine); + anna::testing::TestManager::instantiate().setTimerController(a_timeEngine); // Counters record procedure: const char *varname = "cntRecordPeriod"; - anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000; + anna::Millisecond cntRecordPeriod; + try { + cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000; + } + catch(anna::RuntimeException &ex) { + if (cntRecordPeriod != 0) throw ex; + } + if(cntRecordPeriod != 0) { a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock std::string cntDir = "."; @@ -546,7 +615,7 @@ throw(anna::RuntimeException) { // Testing framework: std::string tmDir = "."; if(cl.exists("tmDir")) tmDir = cl.getValue("tmDir"); - TestManager::instantiate().setReportsDirectory(tmDir); + anna::testing::TestManager::instantiate().setReportsDirectory(tmDir); // Tracing: if(cl.exists("trace")) @@ -560,16 +629,21 @@ void Launcher::run() throw(anna::RuntimeException) { LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION)); CommandLine& cl(anna::CommandLine::instantiate()); - anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate(); + anna::diameter::stack::Engine::instantiate(); // Start time: a_start_time.setNow(); + + // Initial working directory: + char cwd[1024]; + if (getcwd(cwd, sizeof(cwd)) == NULL) + throw anna::RuntimeException("Cannot retrieve initial working directory !!", ANNA_FILE_LOCATION); + a_initialWorkingDirectory = cwd; + // Statistics: anna::statistics::Engine::instantiate().enable(); 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; @@ -710,39 +784,17 @@ throw(anna::RuntimeException) { a_timeEngine->activate(a_counterRecorderClock); // start clock } - // Log statistics concepts - if(cl.exists("logStatisticSamples")) { - std::string list = cl.getValue("logStatisticSamples"); - anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate(); - - if(list == "all") { - if(statEngine.enableSampleLog(/* -1: all concepts */)) - LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION)); - } else { - anna::Tokenizer lst; - lst.apply(cl.getValue("logStatisticSamples"), ","); - - if(lst.size() >= 1) { - anna::Tokenizer::const_iterator tok_min(lst.begin()); - anna::Tokenizer::const_iterator tok_max(lst.end()); - anna::Tokenizer::const_iterator tok_iter; - int conceptId; - - for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) { - conceptId = atoi(anna::Tokenizer::data(tok_iter)); - - if(statEngine.enableSampleLog(conceptId)) - LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION)); - } - } - } - } - + ///////////////////////////// + // Log statistics concepts // + ///////////////////////////// + if(cl.exists("logStatisticSamples")) + logStatisticsSamples(cl.getValue("logStatisticSamples")); // Start client connections ////////////////////////////////////////////////////////////////////////////////// MyDiameterEntity *entity; - for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) { - entity = it->second->getEntity(); + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + for (diameter::comm::origin_hosts_it it = ohm.begin(); it != ohm.end(); it++) { + entity = (MyDiameterEntity *)(it->second->getEntity()); if (entity) entity->bind(); } @@ -756,8 +808,7 @@ throw(anna::RuntimeException) { a_communicator->accept(); } - -bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() { +bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw(anna::RuntimeException) { // Get hex string static char buffer[8192]; std::ifstream infile(pathfile.c_str(), std::ifstream::in); @@ -772,7 +823,8 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl msg += hexString; anna::Logger::debug(msg, ANNA_FILE_LOCATION); ); - anna::functions::fromHexString(hexString, db); + + anna::functions::fromHexString(hexString, db); // could launch exception // Close file infile.close(); return true; @@ -783,11 +835,12 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl void Launcher::resetStatistics() throw() { if (a_workingNode) { - a_workingNode->getMyDiameterEngine()->resetStatistics(); + a_workingNode->getCommEngine()->resetStatistics(); } else { - for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) { - it->second->getMyDiameterEngine()->resetStatistics(); + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + for (diameter::comm::origin_hosts_it it = ohm.begin(); it != ohm.end(); it++) { + it->second->getCommEngine()->resetStatistics(); } } } @@ -798,12 +851,25 @@ void Launcher::resetCounters() throw() { anna::diameter::codec::OamModule::instantiate().resetCounters(); } +void Launcher::signalTerminate() throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "signalTerminate", ANNA_FILE_LOCATION)); + + forceCountersRecord(); + + a_communicator->terminate (); + comm::Application::signalTerminate (); +} + void Launcher::signalUSR2() throw(anna::RuntimeException) { + + std::string inputFile = getSignalUSR2InputFile(); + std::string outputFile = getSignalUSR2OutputFile(); + LOGNOTICE( - std::string msg = "Captured signal SIGUSR2. Reading tasks at '"; - msg += SIGUSR2_TASKS_INPUT_FILENAME; + std::string msg = "Captured signal SIGUSR2. Reading tasks at '"; + msg += inputFile; msg += "' (results will be written at '"; - msg += SIGUSR2_TASKS_OUTPUT_FILENAME; + msg += outputFile; msg += "')"; anna::Logger::notice(msg, ANNA_FILE_LOCATION); ); @@ -811,14 +877,18 @@ void Launcher::signalUSR2() throw(anna::RuntimeException) { // Operation: std::string line; std::string response_content; - std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME); - std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME); + std::ifstream in_file(inputFile); + std::ofstream out_file(outputFile); if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION); - if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION); while(getline(in_file, line)) { + + // Ignore comments and blank lines: + if (line[0] == '#') continue; + if (std::string::npos == line.find_first_not_of(" \t")) continue; + LOGDEBUG( std::string msg = "Processing line: "; msg += line; @@ -835,590 +905,80 @@ void Launcher::signalUSR2() throw(anna::RuntimeException) { } in_file.close(); + out_file << "EOF\n"; out_file.close(); } -std::string Launcher::help() const throw() { - std::string result = "\n"; - result += "\n ------------- HELP -------------\n"; - result += "\n"; - result += "\nOVERVIEW"; - result += "\n--------"; - result += "\n"; - result += "\nThe ADML (ANNA Diameter Multirealm Launcher) process is a multi-realm node with client and server"; - result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server (i.e. to"; - result += "\n simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.), and balancer"; - result += "\n systems to provide failover to external round-robin launchers. Also, auxiliary encoder/decoder/loader"; - result += "\n function could be deployed to reinterpret certain external flow and send it to another process."; - result += "\n "; - result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections"; - result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard"; - result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA"; - result += "\n generation, expiration control and many more features."; - result += "\n"; - result += "\nThe ADML process can easily configure a many realm nodes as needed, which will have own endpoints."; - result += "\nYou should avoid loop configurations (client and server for that client) because automatic forwarding,"; - result += "\n is implemented and this would get in a never ending cycle when a request is sent."; - result += "\n"; - result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually"; - result += "\n 'debug' or 'warning'. See ANNA documentation for more details."; - result += "\n"; - result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:"; - result += "\n kill -10 "; - result += "\n or"; - result += "\n kill -s SIGUSR1 "; - result += "\n and then"; - result += "\n vi /var/tmp/anna.context."; - result += "\n"; - result += "\nA complete xml report will show all the context information (counters, alarms, statistics,"; - result += "\n handlers, diameter stacks, etc.), and a powerful log module could dump all the events"; - result += "\n processed and flow information. Statistics could be analized at context dump and optionally"; - result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the"; - result += "\n measurements."; - result += "\n"; - result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this."; - result += "\n"; - result += "\n"; - result += "\nCOMMAND LINE"; - result += "\n------------"; - result += "\n"; - result += "\nStart the launcher process without arguments in order to see all the startup configuration"; - result += "\n posibilities, many of which could be modified on the air through the management interface"; - result += "\n (we will talk later about this great feature). There is only one mandatory parameter which"; - result += "\n is the services definition: --services . You must follow the dtd schema"; - result += "\n to build a valid services xml file. Some basic examples are:"; - result += "\n"; - result += "\nClient configuration:"; - result += "\n"; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n"; - result += "\n"; - result += "\nServer configuration:"; - result += "\n"; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n"; - 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 arguments in order to define the balancing behaviour. To make hybrid setups you only must mix the realms:"; - result += "\n"; - result += "\nClient and server configuration:"; - result += "\n"; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n "; - result += "\n "; - result += "\n"; - result += "\n "; - result += "\n "; - result += "\n "; - result += "\n"; - result += "\n"; - result += "\n"; - result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own"; - result += "\n as shown in the hybrid former example. Note that the base protocol stack must be registered because"; - result += "\n the configuration corresponds to a multistack process which change the stack using the application-id"; - result += "\n processed (0 in the case of base protocol messages: CER, CEA, DWR, DWA, DPR, DPA)."; - result += "\n"; - result += "\nDYNAMIC OPERATIONS"; - result += "\n------------------"; - result += "\n"; - result += "\nADML supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh."; - result += "\nAn operation is specified by mean a string containing the operation name and needed arguments"; - result += "\n separated by pipes. These are the available commands:"; - result += "\n"; - result += "\n--------------------------------------------------------------------------------------- General purpose"; - result += "\n"; - result += "\nhelp This help."; - result += "\n"; - result += "\n--------------------------------------------------------------------------------------- Node management"; - result += "\n"; - result += "\nnode[|] Selects a context working node by mean a registered name."; - result += "\n All the subsequent operations will be forced to work with"; - result += "\n this node, which makes possible some rare scenarios like"; - result += "\n sending unexpected messages on remote peers. This is also"; - result += "\n useful for some operations in order to restrict the scope"; - result += "\n of action (statistics, communication visibility, etc.)."; - result += "\n Empty parameter will show the current configuration."; - result += "\n"; - result += "\nnode_auto Returns to the default behaviour (smart node selection)."; - result += "\n Depending on the operation, this could imply a global"; - result += "\n action scope, affecting to all the registered realms."; - result += "\n This should be the normal configuration. Take into"; - result += "\n account that if you fix the working node, this could"; - result += "\n affect to things like test programming: communication"; - result += "\n resources will override those which would be inferred"; - result += "\n from programmed messages Origin-Realm avps."; - result += "\n"; - result += "\n------------------------------------------------------------------------------------ Parsing operations"; - result += "\n"; - result += "\ncode|| Encodes source file (pathfile) into target file (pathfile)."; - result += "\ndecode|| Decodes source file (pathfile) into target file (pathfile)."; - result += "\nloadxml| Reinterpret xml source file (pathfile)."; - result += "\n"; - result += "\n------------------------------------------------------------------------------------------- Hot changes"; - result += "\n"; - result += "\nservices[|source file] Adds and starts the services specified in the xml file provided."; - result += "\n (if missing, the file 'services.xml' will be used)."; - result += "\n The last loaded realm node will be automatically the new current"; - result += "\n working node. This is used to load new nodes once the ADML is"; - result += "\n started, regardless if '--services' command line parameter was"; - result += "\n used or not. Those services which are not correctly loaded, will"; - result += "\n be ignored, keeping the process alive."; - result += "\n"; - result += "\ndiameterServerSessions| 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.' will be used."; - result += "\ncollect Reset statistics and counters to start a new test stage of"; - result += "\n performance measurement. Context data can be written at"; - result += "\n '/var/tmp/anna.context.' by mean 'kill -10 '."; - result += "\n or sending operation 'context|[target file]'."; - result += "\n This operation applies over all the registered realm nodes"; - result += "\n except if one specific working node has been set."; - result += "\nforceCountersRecord Forces dump to file the current counters of the process."; - result += "\n"; - result += "\n[|
:][|socket id]"; - result += "\n"; - result += "\n Actions: hide, show (update state) and hidden, shown (query state)."; - result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A)."; - result += "\n If missing server (first parameter) all applications sockets will be affected."; - result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected."; - result += "\n"; - result += "\n All application client sessions are shown on startup, but standard delivery only use primary"; - result += "\n server ones except if fails. Balance configuration use all the allowed sockets. You could also"; - result += "\n use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain"; - result += "\n client sessions, but for this, hide/show feature seems easier."; - result += "\n"; - result += "\n--------------------------------------------------------------------------------------- Flow operations"; - result += "\n"; - result += "\nsendxml2e| Sends xml source file (pathfile) through configured entity."; - result += "\nsendxml2c| Sends xml source file (pathfile) to client."; - result += "\nanswerxml2e[|source_file] Answer xml source file (pathfile) for incoming request with same code from entity."; - result += "\n The answer is stored in a FIFO queue for a specific message code, then there are"; - result += "\n as many queues as different message codes have been programmed."; - result += "\nanswerxml2c[|source_file] Answer xml source file (pathfile) for incoming request with same code from client."; - result += "\n The answer is stored in a FIFO queue for a specific message code, then there are"; - result += "\n as many queues as different message codes have been programmed."; - result += "\nanswerxml<2e/2c> List programmed answers (to entity/client) if no parameter provided."; - result += "\nanswerxml<2e/2c>|dump Write programmed answers (to entity/client) to file 'programmed_answer..',"; - result += "\n where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers."; - result += "\nanswerxml<2e/2c>|clear Clear programmed answers (to entity/client)."; - result += "\nanswerxml<2e/2c>|exhaust Disable the corresponding queue rotation, which is the default behaviour."; - result += "\nanswerxml<2e/2c>|rotate Enable the corresponding queue rotation, useful in performance tests."; - result += "\n Rotation consists in add again to the queue, each element retrieved for answering."; - result += "\n"; - result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test"; - result += "\nspecial scenarios (protocol errors):"; - result += "\n"; - result += "\nsendhex2e| Sends hex source file (pathfile) through configured entity."; - result += "\nsendhex2c| Sends hex source file (pathfile) to client."; - result += "\n"; - result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also"; - result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,"; - result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created."; - result += "\n"; - result += "\nIf a request is received, answer map (built with 'answerxml<2e/2c>' operations) will be"; - result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,"; - result += "\n or answer message was received, the message is forwarded to the other side (entity or client),"; - result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when"; - result += "\n diameter server socket is configured, answer to entity have sense when entity does."; - result += "\n"; - result += "\nIn the most complete situation (process with both client and server side) there are internally"; - result += "\n two maps with N FIFO queues, one for each different message code within programmed answers."; - result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in"; - result += "\n each one we could program different answers corresponding to different request codes received."; - result += "\n"; - result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored"; - result += "\n to the peer which sent the request. If user wants to test a specific answer without changing it,"; - result += "\n use sendxml<2e/2c>/sendhex<2e/2c> operations better than programming."; - result += "\n"; - result += "\nBalance ('--balance' command line parameter) could be used to forward server socket receptions through"; - result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should"; - result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an"; - result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc."; - result += "\n"; - result += "\n--------------------------------------------------------------------------- Processing types (log tags)"; - result += "\n"; - result += "\nUsed as log file extensions (when '--splitLog' is provided on command line) and context preffixes on log"; - result += "\n details when unique log file is dumped:"; - result += "\n"; - result += "\n [sent2e/send2eError] Send to entity (success/error)"; - result += "\n [sent2c/send2cError] Send to client (success/error)"; - result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)"; - result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)"; - result += "\n [recvfc] Reception from client"; - result += "\n [recvfe] Reception from entity"; - result += "\n [req2c-expired] A request sent to client has been expired"; - result += "\n [req2e-expired] A request sent to entity has been expired"; - result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired]"; - 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------------------------------------------------------------------------------------------- Burst tests"; - result += "\n"; - result += "\nIn order to simplify user experience, burst category operations are only allowed in single realm node"; - result += "\n configuration. Indeed, you could send messages with incorrect Origin-Realm, and no warning is shown."; - result += "\nAll the operations are performed through the unique realm: if you need to use more interfaces, you may"; - result += "\n launch different ADML instances. Is nonsense to allow burst in a multi-realm configured ADML, because"; - result += "\n this feature is not able to coordinate the messages."; - result += "\n"; - result += "\nburst|[|parameter] Used for performance testing, we first program diameter requests"; - result += "\n messages in order to launch them from client side to the configured"; - result += "\n diameter entity. We could start the burst with an initial load"; - result += "\n (non-asynchronous sending), after this, a new request will be sent"; - result += "\n per answer received or expired context. There are 10 actions: clear,"; - result += "\n load, start, push, pop, stop, repeat, send, goto and look."; - result += "\n"; - result += "\n burst|clear Clears all loaded burst messages."; - result += "\n burst|load| Loads the next diameter message into launcher burst."; - result += "\n burst|start| Starts (or restarts if already in progress) the message sending with"; - result += "\n a certain initial load."; - result += "\n burst|push| Sends specific non-aynchronous load."; - result += "\n burst|pop| Skip send burst messages in order to reduce over-the-air requests."; - result += "\n Popping all OTA requests implies burst stop because no more answer"; - result += "\n will arrive to the process. Burst output file (--burstLog command"; - result += "\n line parameter) shows popped messages with crosses (x). Each cross"; - result += "\n represents one received answer for which no new request is sent."; - result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount."; - result += "\n burst|repeat[|[yes]|no] Restarts the burst launch when finish. If initial load or push load"; - result += "\n amount is greater than burst list size, they will be limited when"; - result += "\n the list is processed except when repeat mode is enabled."; - result += "\n burst|send| Sends messages from burst list. The main difference with start/push"; - result += "\n operations is that burst won't be awaken. Externally we could control"; - result += "\n sending time (no request will be sent for answers)."; - result += "\n burst|goto| Updates current burst pointer position."; - result += "\n burst|look[|order] Show programmed burst message for order provided, current when missing."; - result += "\n"; - result += "\n-------------------------------------------------------------------------------------- Advanced testing"; - result += "\n"; - result += "\n Burst mode only allows single interface interaction. For multiple interface"; - result += "\n (realm) coordination, you could use the advanced test cases programming:"; - result += "\n"; - result += "\n"; - result += "\n test||[|parameters]"; - result += "\n"; - result += "\n Adds a new step to the test case with provided identifier. If provided identifier"; - result += "\n is not registered yet, a new test case will be created with that value and the"; - result += "\n step will be added as the first. For a specific 'id', the steps are stored in"; - result += "\n order as they are programmed. Check possible runtime exceptions when adding a"; - result += "\n new step because those which fail, will be ignored/skipped during test case"; - result += "\n programming giving an incomplete sequence invalid for the testing purpose."; - result += "\n"; - result += "\n : integer number, normally monotonically increased for each test case. Some external"; - result += "\n script/procedure shall clone a test case template in order to build a collection"; - result += "\n of independent and coherent test cases (normally same type) with different context"; - result += "\n values (Session-Id, Subscriber-Id, etc.)."; - result += "\n"; - result += "\n : commands to be executed for the test id provided. Each command programmed"; - result += "\n constitutes a test case 'step', numbered from 1 to N."; - result += "\n"; - result += "\n timeout| Sets an asynchronous timer to restrict the maximum timeout"; - result += "\n until last test step. Normally, this command is invoked"; - result += "\n in the first step, anyway it measures the time from the"; - result += "\n execution point whatever it is. The expiration will abort"; - result += "\n the test if still running. One or more timeouts could be"; - result += "\n programmed (not usual), but the more restrict will apply."; - result += "\n It is highly recommended to program a initial timeout step,"; - result += "\n or the test case could be eternally in-progress."; - result += "\n"; - result += "\n sendxml2e|[|]"; - result += "\n Sends xml source file (pathfile) to entity (it would be a"; - result += "\n 'forward' event if it came through local server endpoint)."; - result += "\n The step number should be provided for answers to indicate"; - result += "\n the 'wait for request' corresponding step. If you miss this"; - result += "\n reference, the sequence information (hop-by-hop, end-to-end)"; - result += "\n will be sent as they are in the answer xml message (realize"; - result += "\n the difficulty of predicting these information). Be sure to"; - result += "\n refer to a 'wait for request' step. Conditions like 'regexp'"; - result += "\n (as we will see later) are not verified."; - result += "\n"; - result += "\n sendxml2c|[|]"; - result += "\n Sends xml source file (pathfile) to client (it would be a"; - result += "\n 'forward' event if it came through remote server endpoint)."; - result += "\n Same commented for 'sendxml2e' regarding the step number."; - result += "\n"; - result += "\n delay| Blocking step until the time lapse expires. Useful to give "; - result += "\n some cadence control and time schedule for a specific case."; - result += "\n wait| Blocking step until condition is fulfilled. The message could"; - result += "\n received from entity (waitfe) or from client (waitfc)."; - result += "\n"; - result += "\n wait-regexp|"; - result += "\n Wait condition, from entity (waitfe-regexp) or client (waitfc-regexp)"; - result += "\n to match the serialized xml content for received messages. CPU cost"; - result += "\n is bigger than the former ones because the whole message must be"; - result += "\n decoded and converted to xml instead of doing a direct hexadecimal"; - result += "\n buffer search. The main advantage is the great flexibility to identify"; - result += "\n any content with a regular expression."; - result += "\n"; - result += "\n sh-command|