X-Git-Url: https://git.teslayout.com/public/public/public/?a=blobdiff_plain;f=example%2Fdiameter%2Flauncher%2FLauncher.cpp;h=a1b10752af54be02badf2cb95b00544b2c43df65;hb=74730c7d0e4f713c932d6b06a07644d1c3c6c6c1;hp=f5fac98dee32ddc8650a748b8f1ee0628e914404;hpb=431d322261ecfd6ef354abb392edbf8987e2407a;p=anna.git diff --git a/example/diameter/launcher/Launcher.cpp b/example/diameter/launcher/Launcher.cpp index f5fac98..a1b1075 100644 --- a/example/diameter/launcher/Launcher.cpp +++ b/example/diameter/launcher/Launcher.cpp @@ -6,7 +6,12 @@ // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // +// Standard +#include // std::istringstream +#include // std::cout + // Project +#include #include #include #include @@ -14,14 +19,17 @@ #include #include #include +#include // Process #include "Launcher.hpp" +#include "RealmNode.hpp" +#include "MyDiameterEngine.hpp" #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input" #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output" -#define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine" + const char *ServicesDTD = "\ \n\ @@ -34,276 +42,347 @@ const char *ServicesDTD = "\ \n\ \n\ \n\ -\n\ +\n\ \n\ \n\ "; Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) { - a_myDiameterEngine = new MyDiameterEngine(); - a_myDiameterEngine->setRealm("ADL.ericsson.com"); - a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts. - a_logFile = "launcher.log"; - a_burstLogFile = "launcher.burst"; - a_splitLog = false; - a_detailedLog = false; - a_dumpLog = false; + a_codecEngine = new anna::diameter::codec::Engine("MyCodecEngine"); a_timeEngine = NULL; a_counterRecorder = NULL; a_counterRecorderClock = NULL; - a_entity = NULL; - a_diameterLocalServer = NULL; - a_cerPathfile = "cer.xml"; - a_dwrPathfile = "dwr.xml"; - a_workingStackId = 0; - - // Burst - a_burstCycle = 1; - a_burstRepeat = false; - a_burstActive = false; - a_burstLoadIndx = 0; - a_burstDeliveryIt = a_burstMessages.begin(); - a_otaRequest = 0; - a_burstPopCounter = 0; -} -anna::diameter::comm::Message *Launcher::createCommMessage() throw(anna::RuntimeException) { - return a_commMessages.create(); -} + // a_nodes.clear(); + a_workingNode = NULL; -void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() { - a_commMessages.release(msg); + a_httpServerSocket = NULL; } -void Launcher::baseProtocolSetupAsClient() throw(anna::RuntimeException) { - - anna::diameter::codec::Engine *codecEngine; - - codecEngine = getCodecEngine(); - // XXXXXXXXXXXXXXXXXXXX codecEngine = a_myDiameterEngine->getBaseProtocolCodecEngine(); - - - // Build 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(codecEngine); - 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(a_cerPathfile); - } 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|" - 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 - // ::= < Diameter Header: 280, REQ > - // { Origin-Host } - // { Origin-Realm } - anna::diameter::codec::Message diameterDWR(codecEngine); - loadingError = false; +void Launcher::servicesFromXML(const anna::xml::Node* servicesNode) throw(anna::RuntimeException) { + // + const anna::xml::Attribute *id, *dictionary; - try { - diameterDWR.loadXML(a_dwrPathfile); - } catch(anna::RuntimeException &ex) { - //ex.trace(); - loadingError = true; - } + // + const anna::xml::Attribute *originRealm, *appId, *originHost, *cer, *dwr, *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 - 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); + // Stacks + anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate(); + anna::diameter::stack::Dictionary *d; + + for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) { + std::string nodeName = (*it)->getName(); + + if(nodeName == "stack") { + // Input data: + id = (*it)->getAttribute("id"); + dictionary = (*it)->getAttribute("dictionary"); + + try { + d = stackEngine.createDictionary(id->getIntegerValue(), dictionary->getValue()); + getCodecEngine()->setDictionary(d); + } catch(anna::RuntimeException &ex) { + //_exit(ex.asString()); + throw ex; + } + } } - // Assignment for CER/DWR and CEA/DWA: - a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code()); - //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code()); -} + // Codec engine adjustments: + // Auto stack selection based on Application-ID: + bool multistack = (stackEngine.stack_size() > 1); + if (multistack) getCodecEngine()->selectStackWithApplicationId(true); + + for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) { + std::string nodeName = (*it)->getName(); + + if(nodeName == "node") { + // Input data: + originRealm = (*it)->getAttribute("originRealm"); + appId = (*it)->getAttribute("applicationId"); + originHost = (*it)->getAttribute("originHost", false /* no exception */); + cer = (*it)->getAttribute("cer", false /* no exception */); + dwr = (*it)->getAttribute("dwr", false /* no exception */); + allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */); + tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */); + answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */); + ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */); + watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */); + entity = (*it)->getAttribute("entity", false /* no exception */); + entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */); + diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */); + diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */); + balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no) + sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin) + retries = (*it)->getAttribute("retries", false /* no exception */); + log = (*it)->getAttribute("log", false /* no exception */); + splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no) + detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no) + dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no) + burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no) + + // Basic checkings: + if (stackEngine.getDictionary(appId->getIntegerValue()) == NULL) { + std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue(); + throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); + } + 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(); + throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); + } -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(codecEngine); - try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); } - writeLogFile(codecMsg, logExtension, detail); + // Engine time measures checking & assignment: + anna::Millisecond allowedInactivityTimeMs(90000); + anna::Millisecond tcpConnectDelayMs(200); + anna::Millisecond answersTimeoutMs(10000); + anna::Millisecond ceaTimeoutMs(10000); + anna::Millisecond watchdogPeriodMs(30000); + + if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue()); + if (tcpConnectDelay) tcpConnectDelayMs = checkTimeMeasure("tcpConnectDelay", tcpConnectDelay->getValue()); + if (answersTimeout) answersTimeoutMs = checkTimeMeasure("answersTimeout", answersTimeout->getValue()); + if (ceaTimeout) ceaTimeoutMs = checkTimeMeasure("ceaTimeout", ceaTimeout->getValue()); + if (watchdogPeriod) watchdogPeriodMs = checkTimeMeasure("watchdogPeriod", watchdogPeriod->getValue()); + + // Checking command line parameters + std::string sessionBasedModelsType; + 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); + } + } -} + int retransmissions = retries ? retries->getIntegerValue() : 0; + if(retransmissions < 0) { + throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION); + } -// Si ya lo tengo decodificado: -void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() { -// if (!logEnabled()) return; - // Open target file: - std::string targetFile = a_logFile; + // Create new Node instance ///////////////////////////////////////////////////////////////// + a_workingNode = new RealmNode(originRealm->getValue(), appId->getIntegerValue(), a_codecEngine); + MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine(); + ///////////////////////////////////////////////////////////////////////////////////////////// + + // Assignments: + commEngine->setMaxConnectionDelay(tcpConnectDelayMs); + commEngine->setWatchdogPeriod(watchdogPeriodMs); + + // Realm information: + if (originHost) commEngine->setHost(originHost->getValue()); + commEngine->setRealm(originRealm->getValue()); + + // Diameter entity: + if(entity) { + int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1; + + if(sessions > 0) { + // Number of sessions: + commEngine->setNumberOfClientSessionsPerServer(sessions); + + // Client CER and DWR + std::string cerPathfile = cer ? cer->getValue() : ""; + std::string dwrPathfile = dwr ? dwr->getValue() : ""; + commEngine->setClientCERandDWR(cerPathfile, dwrPathfile); + + // 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()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings + } + } - if(a_splitLog) { - targetFile += "."; - targetFile += logExtension; - } + // Diameter Server: + if(diameterServer) { + int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1; + a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs); + } - std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app); - // Set text to dump: - std::string title = "["; - title += logExtension; - title += "]"; - // Build complete log: - std::string log = "\n"; - std::string xml = decodedMessage.asXMLString(); - - - if(a_detailedLog) { - anna::time::Date now; - now.setNow(); - title += " "; - title += now.asString(); - log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline); - log += xml; - log += "\n"; - log += anna::functions::highlight("Used resource"); - log += detail; - log += "\n"; - } else { - log += title; - log += "\n"; - log += xml; - log += "\n"; - } + // 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(a_dumpLog) { - std::string name = anna::functions::asString(decodedMessage.getHopByHop()); - name += "."; - name += anna::functions::asString(decodedMessage.getEndToEnd()); - name += "."; - name += anna::functions::asString(decodedMessage.getId().first); - name += "."; - name += ((decodedMessage.getId().second) ? "request.":"answer."); - name += logExtension; - name += ".xml"; - std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app); - outMsg.write(xml.c_str(), xml.size()); - outMsg.close(); - } - // Write and close - out.write(log.c_str(), log.size()); - out.close(); + // New Node assignment ////////////////////////////////////////////////////////////////////// + a_nodes[originRealm->getValue()] = a_workingNode; + ///////////////////////////////////////////////////////////////////////////////////////////// + } + } } -void Launcher::writeBurstLogFile(const std::string &buffer) throw() { - std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app); - out.write(buffer.c_str(), buffer.size()); - out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope). - // you'd call close() only if you indeed for some reason wanted to close the filestream - // earlier than it goes out of scope. -} -void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) { - CommandLine& cl(anna::CommandLine::instantiate()); +void Launcher::loadServices(const std::string & xmlPathFile) throw(anna::RuntimeException) { + + LOGDEBUG( + std::string trace = "Loading ADML services file '"; + trace += xmlPathFile; + trace += "'"; + anna::Logger::debug(trace, ANNA_FILE_LOCATION); + ); + anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy) + anna::xml::DTDMemory xmlDTD; + const anna::xml::Node *rootNode; + xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error + xmlDTD.initialize(ServicesDTD); + try { + rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd + } + catch (anna::RuntimeException &ex) { + LOGWARNING( + std::string msg = "Services DTD schema:\n\n"; + msg += ServicesDTD; + anna::Logger::warning(msg, ANNA_FILE_LOCATION); + ); + throw ex; + } + + LOGDEBUG( + std::string trace = "Loaded XML file ("; + trace += xmlPathFile; + trace += "):\n"; + trace += anna::xml::Compiler().apply(rootNode); + anna::Logger::debug(trace, ANNA_FILE_LOCATION); + ); + servicesFromXML(rootNode); +} - if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory - std::string parameter = cl.getValue(commandLineParameter); +anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const std::string &value) throw(anna::RuntimeException) { - if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$ - int msecs = cl.getIntegerValue(commandLineParameter); + if(anna::functions::isLike("^[0-9]+$", value)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$ + int msecs; + std::istringstream ( value ) >> msecs; if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms - std::string msg = "Commandline parameter '"; - msg += commandLineParameter; - msg += "' is greater than allowed max timeout for timming engine: "; + std::string msg = "Configuration value for '"; + msg += parameter; + msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: "; msg += anna::functions::asString(a_timeEngine->getMaxTimeout()); 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."; + std::string msg = "Configuration value for '"; + msg += parameter; + msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes)."; LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); } if(msecs <= a_timeEngine->getResolution()) { - std::string msg = "Commandline parameter '"; - msg += commandLineParameter; - msg += "' (and in general, all time measures) must be greater than timming engine resolution: "; + std::string msg = "Configuration value for '"; + msg += parameter; + msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: "; msg += anna::functions::asString(a_timeEngine->getResolution()); throw RuntimeException(msg, ANNA_FILE_LOCATION); } - return; // ok + return (anna::Millisecond)msecs; // ok } - // Excepcion (por no ser entero): - std::string msg = "Error at commandline parameter '"; - msg += commandLineParameter; - msg += "' = '"; + // Non-integer exception: + std::string msg = "Configuration error for '"; msg += parameter; + msg += "' = '"; + msg += value; msg += "': must be a non-negative integer number"; throw RuntimeException(msg, ANNA_FILE_LOCATION); } -void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) { - if(diameterServerSessions <= 0) return; +bool Launcher::setWorkingNode(const std::string &name) throw() { + bool result = false; - std::string address; - int port; - CommandLine& cl(anna::CommandLine::instantiate()); - anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port); - //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 + realm_nodes_nc_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 = nodeIt->second; + result = true; + } - if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime"); + return result; +} + +RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw() { + for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) + if(it->second->getMyDiameterEngine()->getRealm() == realmName) return it->second; - a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime); + return NULL; // this never happens } void Launcher::initialize() @@ -311,45 +390,41 @@ throw(anna::RuntimeException) { anna::comm::Application::initialize(); CommandLine& cl(anna::CommandLine::instantiate()); anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single); -// if (cl.exists ("clone")) -// workMode = anna::comm::Communicator::WorkMode::Clone; a_communicator = new MyCommunicator(workMode); + //a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, anna::timex::Engine::minResolution); a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, (anna::Millisecond)100); // puedo bajar hasta 10 - // Counters record procedure: - anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms - - if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod"); + // Counters record procedure: + const char *varname = "cntRecordPeriod"; + anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000; if(cntRecordPeriod != 0) { - checkTimeMeasure("cntRecordPeriod"); a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock std::string cntDir = "."; - if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir"); - a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid())); } + + // Load launcher services: + loadServices(cl.getValue("services")); // before run (have components to be created) + + // Show loaded stacks: + std::cout << "Stacks provided:" << std::endl; + std::cout << anna::functions::tab(anna::diameter::stack::Engine::instantiate().asString(false /* light */)); + std::cout << std::endl; } 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(); + // Start time: 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"))); @@ -374,53 +449,6 @@ throw(anna::RuntimeException) { 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(); - std::string stacks = cl.getValue("stacks"); - bool multistack = false; - try { - anna::Tokenizer stacksTok; - stacksTok.apply(stacks, "#"); - anna::Tokenizer::const_iterator stacks_it, stack_it; - - for(stacks_it = stacksTok.begin(); stacks_it != stacksTok.end(); stacks_it++) { - std::string stack = anna::Tokenizer::data(stacks_it); - anna::Tokenizer stackTok; - stackTok.apply(stack, ","); - - if(stackTok.size() == 1) { - if(stacksTok.size() != 1) - throw anna::RuntimeException("Application Id value is mandatory when more than one stack is going to be configured", ANNA_FILE_LOCATION); - - anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* no matter */, stack); // the stack is the dictionary - codecEngine->setDictionary(d); - break; - } - - if(stackTok.size() != 2) - throw anna::RuntimeException("Each stack must be in the form ','", ANNA_FILE_LOCATION); - - multistack = true; - stack_it = stackTok.begin(); - unsigned int stackId = atoll(anna::Tokenizer::data(stack_it)); - stack_it++; - std::string file = anna::Tokenizer::data(stack_it); - anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(stackId, file); - } - - // Auto stack selection based on Application-ID: - if (multistack) getCodecEngine()->selectStackWithApplicationId(true); - - std::cout << "Stacks provided: " << std::endl; - std::cout << anna::functions::tab(stackEngine.asString(false /* light */)); - std::cout << std::endl; - } catch(anna::RuntimeException &ex) { - _exit(ex.asString()); - } - //LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION)); - - /////////////////////////////// // Diameter library COUNTERS // /////////////////////////////// @@ -542,6 +570,7 @@ throw(anna::RuntimeException) { appMsgOamModule.enableCounters(); // this special module is disabled by default (the only) + ///////////////////////////////// // Counter recorder associated // ///////////////////////////////// @@ -556,7 +585,7 @@ 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")) { - getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // XXXXXXXXXXXXXXXXXXXXXXXXX + getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete); } @@ -569,85 +598,11 @@ 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)); - getCodecEngine()->setFixMode(fm); // XXXXXXXXXXXXXXXXXXXXXXX - } - - 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")) - startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1); - - // Optional command line parameters //////////////////////////////////////////////////////// - checkTimeMeasure("allowedInactivityTime"); - checkTimeMeasure("tcpConnectDelay"); - checkTimeMeasure("answersTimeout"); - checkTimeMeasure("ceaTimeout"); - checkTimeMeasure("watchdogPeriod"); - checkTimeMeasure("reconnectionPeriod"); - int tcpConnectDelay = 200; // ms - anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms - anna::Millisecond ceaTimeout; - anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms - int reconnectionPeriod = 10000; // ms - - if(cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay"); - - if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout"); - - if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout"); - else ceaTimeout = answersTimeout; - - if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod"); - - if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod"); - - a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay); - a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod); - std::string originHost = ""; - std::string originRealm = ""; - - if(cl.exists("cer")) a_cerPathfile = cl.getValue("cer"); - - if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr"); - - if(cl.exists("originHost")) originHost = cl.getValue("originHost"); - - if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm"); - - a_myDiameterEngine->setHost(originHost); - a_myDiameterEngine->setRealm(originRealm); - - // Diameter entity: - if(cl.exists("entity")) { - int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1; - - if(entityServerSessions > 0) { - 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(); - } + getCodecEngine()->setFixMode(fm); } - // Logs - if(cl.exists("log")) a_logFile = cl.getValue("log"); - - if(cl.exists("splitLog")) a_splitLog = true; - - if(cl.exists("detailedLog")) a_detailedLog = true; - - if(cl.exists("dumpLog")) a_dumpLog = true; + getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); - if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog"); // Log statistics concepts if(cl.exists("logStatisticSamples")) { @@ -677,10 +632,22 @@ throw(anna::RuntimeException) { } } - a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod); - if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP + // Start client connections ////////////////////////////////////////////////////////////////////////////////// + MyDiameterEntity *entity; + for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) { + entity = it->second->getEntity(); + if (entity) entity->bind(); + } + + // Go into communicator poll + // Reconnection period (tcp reconnect retry time): + const char *varname = "reconnectionPeriod"; + anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000; + + a_communicator->setRecoveryTime(reconnectionPeriod); + if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP a_communicator->accept(); } @@ -708,222 +675,8 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl return false; } -int Launcher::clearBurst() throw() { - int size = a_burstMessages.size(); - - if(size) { - std::map::const_iterator it; - std::map::const_iterator it_min(a_burstMessages.begin()); - std::map::const_iterator it_max(a_burstMessages.end()); - - for(it = it_min; it != it_max; it++) releaseCommMessage((*it).second); - - a_burstMessages.clear(); - } else { - std::string msg = "Burst list already empty. Nothing done"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - } - - a_burstActive = false; - a_burstLoadIndx = 0; - a_burstDeliveryIt = a_burstMessages.begin(); - return size; -} - -int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) { - anna::diameter::comm::Message *msg = createCommMessage(); - msg->setBody(db); - a_burstMessages[a_burstLoadIndx++] = msg; - return (a_burstLoadIndx - 1); -} - -int Launcher::stopBurst() throw() { - if(!a_burstActive) { - std::string msg = "Burst launch is already stopped. Nothing done"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -1; - } - - a_burstActive = false; - // Remaining on cycle: - return (a_burstMessages.size() - (*a_burstDeliveryIt).first); -} - -int Launcher::popBurst(int releaseAmount) throw() { - if(!a_burstActive) { - std::string msg = "Burst launch is stopped. Nothing done"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -1; - } - - if(releaseAmount < 1) { - std::string msg = "No valid release amount is specified. Ignoring burst pop"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -2; - } - - int currentOTArequests = a_entity->getOTARequests(); - a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount; - return a_burstPopCounter; -} - -int Launcher::pushBurst(int loadAmount) throw() { - if(a_burstMessages.size() == 0) { - std::string msg = "Burst data not found (empty list). Ignoring burst launch"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -1; - } - - if(loadAmount < 1) { - std::string msg = "No valid load amount is specified. Ignoring burst push"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -2; - } - - a_burstActive = true; - int count; - - for(count = 0; count < loadAmount; count++) - if(!sendBurstMessage()) break; - - return count; -} - -int Launcher::sendBurst(int loadAmount) throw() { - if(a_burstMessages.size() == 0) { - std::string msg = "Burst data not found (empty list). Ignoring burst launch"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -1; - } - - if(loadAmount < 1) { - std::string msg = "No valid load amount is specified. Ignoring burst send"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -2; - } - - int count; - - for(count = 0; count < loadAmount; count++) - if(!sendBurstMessage(true /* anyway */)) break; - - return count; -} - -int Launcher::startBurst(int initialLoad) throw() { - if(initialLoad < 1) { - std::string msg = "No initial load is specified. Ignoring burst start"; - std::cout << msg << std::endl; - LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); - return -2; - } - - a_burstActive = true; - a_burstCycle = 1; - a_burstDeliveryIt = a_burstMessages.begin(); - return (pushBurst(initialLoad)); -} - -bool Launcher::sendBurstMessage(bool anyway) throw() { - if(!anyway && !burstActive()) return false; - - if(a_burstPopCounter > 0) { - if(burstLogEnabled()) writeBurstLogFile("x"); - - a_burstPopCounter--; - return false; - } - - if(a_burstDeliveryIt == a_burstMessages.end()) { - a_burstDeliveryIt = a_burstMessages.begin(); - - if(!anyway) { - if(a_burstRepeat) { - a_burstCycle++; - - if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle)); - } else { - if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n"); - - stopBurst(); - return false; - } - } - } - - anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second; - int order = (*a_burstDeliveryIt).first + 1; - a_burstDeliveryIt++; - bool dot = true; - // sending - bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance")); - - if(burstLogEnabled()) { - if(a_burstMessages.size() >= 100) - dot = (order % (a_burstMessages.size() / 100)); - - if(dot) { - writeBurstLogFile("."); - } else { - writeBurstLogFile(anna::functions::asString(" %d", order)); - int otaReqs = a_entity->getOTARequests(); - - if(result && (otaReqs != a_otaRequest)) { - // false if was a sending after an answer received (no OTA change in this case) - // true after push and pop operations - a_otaRequest = otaReqs; - writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest)); - } - } - } - - // Detailed log: - if(logEnabled()) { - anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource(); - anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL; - std::string detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir - writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail, getCodecEngine()); // el del nodo de trabajo - } - - return result; -} - -std::string Launcher::lookBurst(int order) const throw() { - std::string result = "No message found for order provided ("; - result += anna::functions::asString(order); - result += ")"; - std::map::const_iterator it = a_burstMessages.find(order - 1); - - if(it != a_burstMessages.end()) { - // Decode - 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(); - } - - return result; -} - -std::string Launcher::gotoBurst(int order) throw() { - std::string result = "Position not found for order provided ("; - std::map::iterator it = a_burstMessages.find(order - 1); - - if(it != a_burstMessages.end()) { - a_burstDeliveryIt = it; - result = "Position updated for order provided ("; - } - - result += anna::functions::asString(order); - result += ")"; - return result; +void Launcher::resetStatistics() throw() { + getWorkingNode()->getMyDiameterEngine()->resetStatistics(); } void Launcher::resetCounters() throw() { @@ -978,18 +731,21 @@ std::string Launcher::help() const throw() { result += "\nOVERVIEW"; result += "\n--------"; result += "\n"; - result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server"; - result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server"; - result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),"; - result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary"; - result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and"; - result += "\n send it to another process."; - 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"; @@ -1016,7 +772,7 @@ std::string Launcher::help() const throw() { 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). Some of the more common parameters are:"; result += "\n"; - result += "\nAs mandatory, the stacks enabled given through the application-id and the xml dictionary:"; + result += "\nAs mandatory, the stacks enabled given through the applicationId and the xml dictionary:"; result += "\n --stacks "; result += "\n"; result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:"; @@ -1039,7 +795,7 @@ std::string Launcher::help() const throw() { result += "\nDYNAMIC OPERATIONS"; result += "\n------------------"; result += "\n"; - result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh."; + 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"; @@ -1047,10 +803,11 @@ std::string Launcher::help() const throw() { result += "\n"; result += "\nhelp This help. Startup information-level traces also dump this help."; result += "\n"; - result += "\n--------------------------------------------------------------------------------------- Stack selection"; + result += "\n---------------------------------------------------------------------------------------- Node selection"; result += "\n"; - result += "\nstack| Select current working stack id (node selection). Many operations"; - result += " could use this value if proceed, in multistack configurations."; + result += "\nnode[|] Select current working node by mean the registered name."; + result += "\n All the subsequent operations will be referred to this node."; + result += "\n Without argument, the current node is dumped on stdout."; result += "\n"; result += "\n------------------------------------------------------------------------------------ Parsing operations"; result += "\n"; @@ -1062,7 +819,7 @@ std::string Launcher::help() const throw() { 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 += "\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"; @@ -1071,7 +828,7 @@ std::string Launcher::help() const throw() { result += "\n or sending operation 'context|[target file]'."; result += "\nforceCountersRecord Forces dump to file the current counters of the process."; result += "\n"; - result += "\n|[
:]|[socket id]"; + 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)."; @@ -1088,13 +845,13 @@ std::string Launcher::help() const throw() { result += "\nsendxml2e| Sends xml source file (pathfile) through configured entity."; result += "\nsendxml2c| Sends xml source file (pathfile) to client."; result += "\nsendxml| Same as 'sendxml2e'."; - result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for incoming request with same code from entity."; + 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 += "\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|[source_file] Same as 'answerxml2c'."; + result += "\nanswerxml[|source_file] Same as 'answerxml2c'."; 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."; @@ -1155,7 +912,7 @@ std::string Launcher::help() const throw() { result += "\n"; result += "\n-------------------------------------------------------------------------------------------- Load tests"; result += "\n"; - result += "\nburst||[parameter] Used for performance testing, we first program diameter requests"; + 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"; @@ -1173,7 +930,7 @@ std::string Launcher::help() const throw() { 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 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"; @@ -1227,7 +984,10 @@ 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(getCodecEngine()); // XXXXXXXXXXXXXX el del nodo de trabajo + anna::diameter::codec::Message codecMsg(getCodecEngine()); + MyDiameterEntity *entity = getWorkingNode()->getEntity(); + MyDiameterEngine *commEngine = getWorkingNode()->getMyDiameterEngine(); + MyLocalServer *localServer = getWorkingNode()->getDiameterServer(); /////////////////////////////////////////////////////////////////// // Simple operations without arguments: @@ -1274,6 +1034,8 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons // Check the number of parameters: bool wrongBody = false; + if((opType == "node") && (numParams > 1)) wrongBody = true; + if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true; if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true; @@ -1305,6 +1067,17 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons return; } + // Realm switch: + if(opType == "node") { + if (param1 != "") { + if (setWorkingNode(param1)) response_content = anna::functions::asString("Current node is now '%s'\n", param1.c_str()); + } + else { + std::cout << getWorkingNode()->asXMLString() << std::endl; + } + return; + } + if(opType == "code") { codecMsg.loadXML(param1); std::string hexString = anna::functions::asHexString(codecMsg.code()); @@ -1326,8 +1099,6 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons outfile.write(xmlString.c_str(), xmlString.size()); outfile.close(); } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) { - MyDiameterEntity *entity = getEntity(); - if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION); if(param1 != "") { @@ -1336,25 +1107,25 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons key += "|"; key += param2; - if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide(); + if(opType == "hide") commEngine->findClientSession(key)->hide(); - if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show(); + if(opType == "show") commEngine->findClientSession(key)->show(); - if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false"; + if(opType == "hidden") result = commEngine->findClientSession(key)->hidden() ? "true" : "false"; - if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false"; + if(opType == "shown") result = commEngine->findClientSession(key)->shown() ? "true" : "false"; } else { std::string address; int port; anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port); - if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide(); + if(opType == "hide") commEngine->findServer(address, port)->hide(); - if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show(); + if(opType == "show") commEngine->findServer(address, port)->show(); - if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false"; + if(opType == "hidden") result = commEngine->findServer(address, port)->hidden() ? "true" : "false"; - if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false"; + if(opType == "shown") result = commEngine->findServer(address, port)->shown() ? "true" : "false"; } } else { if(opType == "hide") entity->hide(); @@ -1366,12 +1137,8 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(opType == "shown") result = entity->shown() ? "true" : "false"; } } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) { - MyDiameterEntity *entity = getEntity(); - 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); + anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage(); if((opType == "sendxml") || (opType == "sendxml2e")) { codecMsg.loadXML(param1); @@ -1388,18 +1155,16 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } bool success = entity->send(msg, cl.exists("balance")); - releaseCommMessage(msg); + getWorkingNode()->releaseCommMessage(msg); // Detailed log: - if(logEnabled()) { + if(getWorkingNode()->logEnabled()) { anna::diameter::comm::Server *usedServer = entity->getLastUsedResource(); anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL; std::string detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir - writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail); + getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail); } } else if((opType == "burst")) { - anna::diameter::comm::Entity *entity = getEntity(); - if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION); // burst|clear clears all loaded burst messages. @@ -1417,7 +1182,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(param1 == "clear") { result = "Removed "; - result += anna::functions::asString(clearBurst()); + result += anna::functions::asString(getWorkingNode()->clearBurst()); result += " elements."; } else if(param1 == "load") { if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION); @@ -1427,7 +1192,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION); try { codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher) - int position = loadBurstMessage(codecMsg.code()); + int position = getWorkingNode()->loadBurstMessage(codecMsg.code()); result = "Loaded '"; result += param2; result += "' file into burst list position "; @@ -1436,7 +1201,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION); int initialLoad = atoi(param2.c_str()); - int processed = startBurst(initialLoad); + int processed = getWorkingNode()->startBurst(initialLoad); if(processed > 0) { result = "Initial load completed for "; @@ -1446,7 +1211,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } else if(param1 == "push") { if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION); - int pushed = pushBurst(atoi(param2.c_str())); + int pushed = getWorkingNode()->pushBurst(atoi(param2.c_str())); if(pushed > 0) { result = "Pushed "; @@ -1457,7 +1222,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION); int releaseLoad = atoi(param2.c_str()); - int popped = popBurst(releaseLoad); + int popped = getWorkingNode()->popBurst(releaseLoad); if(popped > 0) { result = "Burst popped for "; @@ -1465,7 +1230,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons result += "."; } } else if(param1 == "stop") { - int left = stopBurst(); + int left = getWorkingNode()->stopBurst(); if(left != -1) { result += anna::functions::entriesAsString(left, "message"); @@ -1475,12 +1240,12 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons if(param2 == "") param2 = "yes"; bool repeat = (param2 == "yes"); - repeatBurst(repeat); + getWorkingNode()->repeatBurst(repeat); result += (repeat ? "Mode on." : "Mode off."); } else if(param1 == "send") { if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION); - int sent = sendBurst(atoi(param2.c_str())); + int sent = getWorkingNode()->sendBurst(atoi(param2.c_str())); if(sent > 0) { result = "Sent "; @@ -1490,22 +1255,20 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } else if(param1 == "goto") { if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION); - result = gotoBurst(atoi(param2.c_str())); + result = getWorkingNode()->gotoBurst(atoi(param2.c_str())); result += "."; } else if(param1 == "look") { if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION); result = "\n\n"; - result += lookBurst(atoi(param2.c_str())); + result += getWorkingNode()->lookBurst(atoi(param2.c_str())); result += "\n\n"; } else { throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION); } } else if((opType == "sendxml2c") || (opType == "sendhex2c")) { - MyLocalServer *localServer = getDiameterLocalServer(); - if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION); - anna::diameter::comm::Message *msg = createCommMessage(); + anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage(); if(opType == "sendxml2c") { codecMsg.loadXML(param1); @@ -1522,13 +1285,13 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } bool success = localServer->send(msg); - releaseCommMessage(msg); + getWorkingNode()->releaseCommMessage(msg); // Detailed log: - if(logEnabled()) { + if(getWorkingNode()->logEnabled()) { anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir - writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail); + getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail); } } else if(opType == "loadxml") { codecMsg.loadXML(param1); @@ -1537,13 +1300,12 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } else if(opType == "diameterServerSessions") { int diameterServerSessions = atoi(param1.c_str()); - if(!getDiameterLocalServer()) - startDiameterServer(diameterServerSessions); + if(localServer) + localServer->setMaxConnections(diameterServerSessions); else - getDiameterLocalServer()->setMaxConnections(diameterServerSessions); - } else if((opType == "answerxml") || (opType == "answerxml2c")) { - MyLocalServer *localServer = getDiameterLocalServer(); + LOGWARNING(anna::Logger::warning("To update the number of sessions, you must configure the process diameter local server: you could also launch it with no sessions (disabled)", ANNA_FILE_LOCATION)); + } else if((opType == "answerxml") || (opType == "answerxml2c")) { if(!localServer) throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION); @@ -1574,8 +1336,6 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons localServer->getReactingAnswers()->addMessage(code, message); } } else if(opType == "answerxml2e") { - MyDiameterEntity *entity = getEntity(); - if(!entity) throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION); @@ -1677,51 +1437,6 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons } } -int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() { - CommandLine& cl(anna::CommandLine::instantiate()); - std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart"); - - if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1 - - try { - // Service-Context-Id: - anna::diameter::helpers::dcca::ChargingContext::_v chargingContext; - std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext); - - switch(chargingContext) { - case anna::diameter::helpers::dcca::ChargingContext::Data: - case anna::diameter::helpers::dcca::ChargingContext::Voice: - case anna::diameter::helpers::dcca::ChargingContext::Content: { - // Session-Id: ';;[;="">]' - std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody()); - std::string diameterIdentity, optional; - anna::U32 high, low; - anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional); - - if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions); - - if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions); - - if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions); - } - - 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( - std::string msg = ex.getText(); - msg += " | Round-robin between sessions will be used to send"; - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - } - - return -1; -} - anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const throw() { anna::xml::Node* result = parent->createChild("launcher"); @@ -1730,7 +1445,11 @@ throw() { result->createAttribute("StartTime", a_start_time.asString()); result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000); // Diameter: - getCodecEngine()->asXML(result); // XXXXXXXXXXXXXXX todos los nodos ... + getCodecEngine()->asXML(result); + for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) { + it->second->asXML(result); + } + // OAM: anna::diameter::comm::OamModule::instantiate().asXML(result); anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result); @@ -1739,4 +1458,3 @@ throw() { anna::statistics::Engine::instantiate().asXML(result); return result; } -