X-Git-Url: https://git.teslayout.com/public/public/public/?a=blobdiff_plain;f=example%2Fdiameter%2Flauncher%2FLauncher.cpp;h=7e16c90c5f9bc4f0dbab0dc2fc0514d78212d14d;hb=752438861433c3789eb1b0d9f2c15e15037595e6;hp=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391;hpb=68a8fe342d8337ec1a86b57920bc7dcf7faf2413;p=anna.git diff --git a/example/diameter/launcher/Launcher.cpp b/example/diameter/launcher/Launcher.cpp index e69de29..7e16c90 100644 --- a/example/diameter/launcher/Launcher.cpp +++ b/example/diameter/launcher/Launcher.cpp @@ -0,0 +1,1690 @@ +// ANNA - Anna is Not Nothingness Anymore // +// // +// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo // +// // +// See project site at http://redmine.teslayout.com/projects/anna-suite // +// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // + + +// Project +#include +#include +#include +#include +#include +#include +#include + +// Process +#include "Launcher.hpp" + + +#define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input" +#define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output" + + +// Auxiliary message for sendings +anna::diameter::comm::Message G_commMsgSent2c, G_commMsgSent2e, G_commMsgFwd2c, G_commMsgFwd2e; +anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg; +anna::Recycler G_commMessages; // create on requests forwards without programmed answer / release in answers forward + + +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_timeEngine = NULL; + a_counterRecorder = NULL; + a_counterRecorderClock = NULL; + a_entity = NULL; + a_diameterLocalServer = NULL; + a_cerPathfile = "cer.xml"; + a_dwrPathfile = "dwr.xml"; + // Burst + a_burstCycle = 1; + a_burstRepeat = false; + a_burstActive = false; + a_burstLoadIndx = 0; + a_burstDeliveryIt = a_burstMessages.begin(); + a_otaRequest = 0; + a_burstPopCounter = 0; +} + +void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) { + // 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; + 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; + loadingError = false; + + try { + diameterDWR.loadXML(a_dwrPathfile); + } catch(anna::RuntimeException &ex) { + //ex.trace(); + loadingError = true; + } + + if(loadingError) { + LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION)); + diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request); + diameterDWR.setApplicationId(applicationId); + diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); + diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); + } + +////////////////////////// +// IDEM FOR CEA AND DWA // +////////////////////////// +// // 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; +// int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32 +// std::string OH = a_myDiameterEngine->getHost(); +// std::string OR = a_myDiameterEngine->getRealm(); +// std::string hostIP = anna::functions::getHostnameIP(); // Address +// int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32 +// std::string productName = "ANNA Diameter Launcher"; // UTF8String +// bool loadingError = false; +// +// try { +// diameterCER.loadXML("cer.xml"); +// } catch (anna::RuntimeException &ex) { +// ex.trace(); +// loadingError = true; +// } +// +// if (loadingError) { +// LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION)); +// diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request); +// diameterCER.setApplicationId(applicationId); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|" +// 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; +// loadingError = false; +// +// try { +// diameterDWR.loadXML("dwr.xml"); +// } catch (anna::RuntimeException &ex) { +// ex.trace(); +// loadingError = true; +// } +// +// if (loadingError) { +// LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION)); +// diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request); +// diameterDWR.setApplicationId(applicationId); +// diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); +// diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); +// } + // Assignment for CER/DWR and CEA/DWA: + a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code()); + //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code()); +} + +void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() { +// if (!logEnabled()) return; + + // Decode + try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); } + + writeLogFile(G_codecMsg, logExtension, detail); +} + +// 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; + + if(a_splitLog) { + targetFile += "."; + targetFile += logExtension; + } + + 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"; + } + + 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(); +} + +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()); + + if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory + + std::string parameter = cl.getValue(commandLineParameter); + + if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$ + int msecs = cl.getIntegerValue(commandLineParameter); + + if(msecs > a_timeEngine->getMaxTimeout()) { + std::string msg = "Commandline parameter '"; + msg += commandLineParameter; + msg += "' is greater than allowed max timeout for timming engine: "; + msg += anna::functions::asString(a_timeEngine->getMaxTimeout()); + throw RuntimeException(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: "; + msg += anna::functions::asString(a_timeEngine->getResolution()); + throw RuntimeException(msg, ANNA_FILE_LOCATION); + } + + return; // ok + } + + // Excepcion (por no ser entero): + std::string msg = "Error at commandline parameter '"; + msg += commandLineParameter; + msg += "' = '"; + msg += parameter; + 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; + + 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"); + int allowedInactivityTime = 90000; // ms + + if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime"); + + a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime); +} + +void Launcher::initialize() +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)300000, (anna::Millisecond)150); + // Counters record procedure: + anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms + + if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod"); + + 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())); + } +} + +void Launcher::run() +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION)); + CommandLine& cl(anna::CommandLine::instantiate()); + // Start time: + a_start_time.setNow(); + // Statistics: + anna::statistics::Engine::instantiate().enable(); + /////////////////////////////// + // Diameter library COUNTERS // + /////////////////////////////// + anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate(); + oamDiameterComm.initializeCounterScope(1); // 1000 - 1999 + anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate(); + oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999 + ///////////////// + // COMM MODULE // + ///////////////// + /* Main events */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17); + /* Diameter Base (capabilities exchange & keep alive) */ + // as client + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26); + // as server + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35); + /* server socket operations (enable/disable listening port for any local server) */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37); + /* Connectivity */ + // clients + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46); + // servers + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 58); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 59); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 60); + ////////////////// + // CODEC MODULE // + ////////////////// + /* Avp decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/); + /* Message decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/); + /* Avp validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/); + /* Message validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/); + /* Level validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/); + + ///////////////////////////////// + // Counter recorder associated // + ///////////////////////////////// + if(a_counterRecorderClock) { + oamDiameterComm.setCounterRecorder(a_counterRecorder); + oamDiameterCodec.setCounterRecorder(a_counterRecorder); + a_timeEngine->activate(a_counterRecorderClock); // start clock + } + + // Checking command line parameters + if(cl.exists("sessionBasedModelsClientSocketSelection")) { + std::string type = cl.getValue("sessionBasedModelsClientSocketSelection"); + + if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) { + throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION); + } + } + + // Tracing: + if(cl.exists("trace")) + anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace"))); + + LOGINFORMATION( + // Help on startup traces: + anna::Logger::information(help(), ANNA_FILE_LOCATION); + // Test messages dtd: + std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n"; + msg += anna::diameter::codec::MessageDTD; + anna::Logger::information(msg, ANNA_FILE_LOCATION); + ); + + // HTTP Server: + if(cl.exists("httpServer")) { + anna::comm::Network& network = anna::comm::Network::instantiate(); + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port); + //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP + const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve + a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory()); + } + + // Stack: + anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine(); + anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate(); + anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */); + // Analyze comma-separated list: + anna::Tokenizer lst; + std::string dictionaryParameter = cl.getValue("dictionary"); + lst.apply(dictionaryParameter, ","); + + if(lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory) + anna::Tokenizer::const_iterator tok_min(lst.begin()); + anna::Tokenizer::const_iterator tok_max(lst.end()); + anna::Tokenizer::const_iterator tok_iter; + std::string pathFile; + d->allowUpdates(); + + for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) { + pathFile = anna::Tokenizer::data(tok_iter); + d->load(pathFile); + } + } + + codecEngine->setDictionary(d); + LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION)); + + if(lst.size() > 1) { + std::string all_in_one = "./dictionary-all-in-one.xml"; + std::ofstream out(all_in_one.c_str(), std::ifstream::out); + std::string buffer = d->asXMLString(); + out.write(buffer.c_str(), buffer.size()); + out.close(); + std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl; + } + + + + // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always'). + // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError': + if(cl.exists("integrationAndDebugging")) { + codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); + codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete); + } + + // Fix mode + if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never + std::string fixMode = cl.getValue("fixMode"); + anna::diameter::codec::Engine::FixMode::_v fm; + if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding; + else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding; + else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always; + else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never; + else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION)); + codecEngine->setFixMode(fm); + } + + codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); + + // 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(); // Same CER/CEA, DWR/DWA for all diameter servers + 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->bind(); + } + } + + // 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; + + if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog"); + + // 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)); + } + } + } + } + + a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod); + + if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP + + a_communicator->accept(); +} + +bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() { + // Get hex string + static char buffer[8192]; + std::ifstream infile(pathfile.c_str(), std::ifstream::in); + + if(infile.is_open()) { + infile >> buffer; + std::string hexString(buffer, strlen(buffer)); + // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString': + hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end()); + LOGDEBUG( + std::string msg = "Hex string (remove colons if exists): "; + msg += hexString; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + anna::functions::fromHexString(hexString, db); + // Close file + infile.close(); + return true; + } + + 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++) G_commMessages.release((*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 = G_commMessages.create(); + 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); + } + + 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 + try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); } + + result = G_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::resetCounters() throw() { + // Diameter::comm module: + anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate(); + oamDiameterComm.resetCounters(); +} + +void Launcher::signalUSR2() throw(anna::RuntimeException) { + LOGNOTICE( + std::string msg = "Captured signal SIGUSR2. Reading tasks at '"; + msg += SIGUSR2_TASKS_INPUT_FILENAME; + msg += "' (results will be written at '"; + msg += SIGUSR2_TASKS_OUTPUT_FILENAME; + msg += "')"; + anna::Logger::notice(msg, ANNA_FILE_LOCATION); + ); + // Operation: + std::string line; + std::string response_content; + std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME); + std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME); + + 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)) { + LOGDEBUG( + std::string msg = "Processing line: "; + msg += line; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + try { + eventOperation(line, response_content); + } catch(RuntimeException &ex) { + ex.trace(); + } + + out_file << response_content; + } + + in_file.close(); + 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 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 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 += "\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 dictionary, 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). Some of the more common parameters are:"; + result += "\n"; + result += "\nAs mandatory, the stack definition given through the xml dictionary:"; + result += "\n -dictionary "; + result += "\n"; + result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:"; + result += "\n -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0"; + result += "\n"; + result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:"; + result += "\n -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0"; + result += "\n"; + 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."; + result += "\n"; + result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own"; + result += "\n customized ones using '-cer ' and '-dwr '."; + result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own"; + result += "\n customized ones using operations interface."; + result += "\n"; + result += "\n"; + result += "\nDYNAMIC OPERATIONS"; + result += "\n------------------"; + result += "\n"; + result += "\nADL 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. Startup information-level traces also dump this help."; + 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 += "\ndiameterServerSessions| Updates the maximum number of accepted connections to diameter"; + result += "\n server socket."; + result += "\ncollect Reset statistics and counters to start a new test stage of"; + result += "\n performance measurement. Context data is written at"; + result += "\n '/var/tmp/anna.context.' by mean 'kill -10 '."; + 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 += "\nsendxml| Same as 'sendxml2e'."; + 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|[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."; + 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 += "\nsendhex| Same as 'sendhex2e'."; + 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<[2c] or 2e>' 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/sendhex 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"; + result += "\n-------------------------------------------------------------------------------------------- Load tests"; + 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| Show programmed burst message for order provided."; + result += "\n"; + result += "\n"; + result += "\nUSING OPERATIONS INTERFACE"; + result += "\n--------------------------"; + result += "\n"; + result += "\n------------------------------------------------------------------------- Operations via HTTP interface"; + result += "\n"; + result += "\nAll the operations described above can be used through the optional HTTP interface. You only have"; + result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'."; + result += "\nTo send the task, we shall build the http request body with the operation string. Some examples"; + result += "\n using curl client could be:"; + result += "\n"; + result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000"; + result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000"; + result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000"; + result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000"; + result += "\n etc."; + result += "\n"; + result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal"; + result += "\n"; + result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at"; + result += "\n signal event:"; + result += "\n echo \"<\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME; + result += "\n then"; + result += "\n kill -12 "; + result += "\n or"; + result += "\n kill -s SIGUSR2 "; + result += "\n and then see the results:"; + result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME; + result += "\n"; + result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that"; + result += "\n case over the output file. Take into account that all the content of the task file will be executed"; + result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http"; + result += "\n interface."; + result += "\n"; + result += "\n"; + return result; +} + +void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION)); + CommandLine& cl(anna::CommandLine::instantiate()); + LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION)); + response_content = "Operation processed with exception. See traces\n"; // supposed + std::string result = ""; + anna::DataBlock db_aux(true); + + /////////////////////////////////////////////////////////////////// + // Simple operations without arguments: + + // Help: + if(operation == "help") { + std::string s_help = help(); + std::cout << s_help << std::endl; + LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION)); + response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n"; + return; + } + + // Reset performance data: + if(operation == "collect") { + resetCounters(); + resetStatistics(); + response_content = "All process counters & statistic information have been reset\n"; + return; + } + + // Counters dump on demand: + if(operation == "forceCountersRecord") { + forceCountersRecord(); + response_content = "Current counters have been dump to disk\n"; + return; + } + + /////////////////////////////////////////////////////////////////// + // Tokenize operation + Tokenizer params; + params.apply(operation, "|"); + int numParams = params.size() - 1; + + // No operation has more than 2 arguments ... + if(numParams > 2) { + LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION)); + throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION); + } + + // Get the operation type: + Tokenizer::const_iterator tok_iter = params.begin(); + std::string opType = Tokenizer::data(tok_iter); + // Check the number of parameters: + bool wrongBody = false; + + if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true; + + if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true; + + if((opType == "burst") && (numParams < 1)) wrongBody = true; + + if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true; + + if(wrongBody) { + // Launch exception + std::string msg = "Wrong body content format on HTTP Request for '"; + msg += opType; + msg += "' operation (missing parameter/s)"; + throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); + } + + // All seems ok: + std::string param1, param2; + + if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); } + + if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); } + + // Operations: + if(opType == "code") { + G_codecMsg.loadXML(param1); + std::string hexString = anna::functions::asHexString(G_codecMsg.code()); + // write to outfile + std::ofstream outfile(param2.c_str(), std::ifstream::out); + outfile.write(hexString.c_str(), hexString.size()); + outfile.close(); + } else if(opType == "decode") { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + // Decode + try { G_codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); } + + std::string xmlString = G_codecMsg.asXMLString(); + // write to outfile + std::ofstream outfile(param2.c_str(), std::ifstream::out); + 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 != "") { + if(param2 != "") { + std::string key = param1; + key += "|"; + key += param2; + + if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide(); + + if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show(); + + if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false"; + + if(opType == "shown") result = getMyDiameterEngine()->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 == "show") getMyDiameterEngine()->findServer(address, port)->show(); + + if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false"; + + if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false"; + } + } else { + if(opType == "hide") entity->hide(); + + if(opType == "show") entity->show(); + + if(opType == "hidden") result = entity->hidden() ? "true" : "false"; + + 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); + + if((opType == "sendxml") || (opType == "sendxml2e")) { + G_codecMsg.loadXML(param1); + G_commMsgSent2e.clearBody(); + try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher) + + G_commMsgSent2e.setBody(G_codecMsg.code()); + } else { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + G_commMsgSent2e.setBody(db_aux); + } + + bool success = entity->send(G_commMsgSent2e, cl.exists("balance")); + + // Detailed log: + if(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(G_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. + // burst|load| loads the next diameter message into launcher burst. + // burst|start| starts the message sending with a certain initial load. + // burst|push| sends specific non-aynchronous load. + // burst|stop stops the burst cycle. + // burst|repeat|[[yes]|no] restarts the burst launch when finish. + // burst|send| send messages from burst list. The main difference with + // start/push operations is that burst won't be awaken. + // Externally we could control sending time (no request + // will be sent for answers). + // burst|goto| Updates current burst pointer position. + // burst|look| Show programmed burst message for order provided. + + if(param1 == "clear") { + result = "Removed "; + result += anna::functions::asString(clearBurst()); + result += " elements."; + } else if(param1 == "load") { + if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION); + + G_codecMsg.loadXML(param2); + + if(G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION); + try { G_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(G_codecMsg.code()); + result = "Loaded '"; + result += param2; + result += "' file into burst list position "; + result += anna::functions::asString(position); + } else if(param1 == "start") { + 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); + + if(processed > 0) { + result = "Initial load completed for "; + result += anna::functions::entriesAsString(processed, "message"); + result += "."; + } + } 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())); + + if(pushed > 0) { + result = "Pushed "; + result += anna::functions::entriesAsString(pushed, "message"); + result += "."; + } + } else if(param1 == "pop") { + if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION); + + int releaseLoad = atoi(param2.c_str()); + int popped = popBurst(releaseLoad); + + if(popped > 0) { + result = "Burst popped for "; + result += anna::functions::entriesAsString(popped, "message"); + result += "."; + } + } else if(param1 == "stop") { + int left = stopBurst(); + + if(left != -1) { + result += anna::functions::entriesAsString(left, "message"); + result += " left to the end of the cycle."; + } + } else if(param1 == "repeat") { + if(param2 == "") param2 = "yes"; + + bool repeat = (param2 == "yes"); + 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())); + + if(sent > 0) { + result = "Sent "; + result += anna::functions::entriesAsString(sent, "message"); + result += "."; + } + } 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 += "."; + } 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 += "\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); + + if(opType == "sendxml2c") { + G_codecMsg.loadXML(param1); + G_commMsgSent2c.clearBody(); + try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher) + + G_commMsgSent2c.setBody(G_codecMsg.code()); + } else { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + G_commMsgSent2c.setBody(db_aux); + } + + bool success = localServer->send(G_commMsgSent2c); + + // Detailed log: + if(logEnabled()) { + anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail); + } + } else if(opType == "loadxml") { + G_codecMsg.loadXML(param1); + std::string xmlString = G_codecMsg.asXMLString(); + std::cout << xmlString << std::endl; + } else if(opType == "diameterServerSessions") { + int diameterServerSessions = atoi(param1.c_str()); + + if(!getDiameterLocalServer()) + startDiameterServer(diameterServerSessions); + else + getDiameterLocalServer()->setMaxConnections(diameterServerSessions); + } else if((opType == "answerxml") || (opType == "answerxml2c")) { + MyLocalServer *localServer = getDiameterLocalServer(); + + if(!localServer) + throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION); + + if(param1 == "") { // programmed answers FIFO's to stdout + std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } else if (param1 == "rotate") { + localServer->getReactingAnswers()->rotate(true); + } else if (param1 == "exhaust") { + localServer->getReactingAnswers()->rotate(false); + } else if (param1 == "clear") { + localServer->getReactingAnswers()->clear(); + } else if (param1 == "dump") { + localServer->getReactingAnswers()->dump(); + } else { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + anna::diameter::codec::Message *message = engine->createMessage(param1); + LOGDEBUG + ( + anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION); + ); + + if(message->isRequest()) + throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION); + + int code = message->getId().first; + LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION)); + 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); + + if(param1 == "") { // programmed answers FIFO's to stdout + std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } else if (param1 == "rotate") { + entity->getReactingAnswers()->rotate(true); + } else if (param1 == "exhaust") { + entity->getReactingAnswers()->rotate(false); + } else if (param1 == "clear") { + entity->getReactingAnswers()->clear(); + } else if (param1 == "dump") { + entity->getReactingAnswers()->dump(); + } else { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + anna::diameter::codec::Message *message = engine->createMessage(param1); + LOGDEBUG + ( + anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION); + ); + + if(message->isRequest()) + throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION); + + int code = message->getId().first; + LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION)); + entity->getReactingAnswers()->addMessage(code, message); + } + } else { + LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION)); + throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION); + } + + // HTTP response + response_content = "Operation processed; "; + + if((opType == "decode") || (opType == "code")) { + response_content += "File '"; + response_content += param2; + response_content += "' created."; + response_content += "\n"; + } else if((opType == "hide") || (opType == "show")) { + response_content += "Resource '"; + response_content += ((param1 != "") ? param1 : "Entity"); + + if(param2 != "") { + response_content += "|"; + response_content += param2; + } + + response_content += "' "; + + if(opType == "hide") response_content += "has been hidden."; + + if(opType == "show") response_content += "has been shown."; + + response_content += "\n"; + } else if((opType == "hidden") || (opType == "shown")) { + response_content += "Result: "; + response_content += result; + response_content += "\n"; + } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) { + response_content += "Message '"; + response_content += param1; + response_content += "' sent to entity."; + response_content += "\n"; + } else if(opType == "burst") { + response_content += "Burst '"; + response_content += param1; + response_content += "' executed. "; + response_content += result; + response_content += "\n"; + } else if((opType == "sendxml2c") || (opType == "sendhex2c")) { + response_content += "Message '"; + response_content += param1; + response_content += "' sent to client."; + response_content += "\n"; + } else if(opType == "loadxml") { + response_content += "Message '"; + response_content += param1; + response_content += "' loaded."; + response_content += "\n"; + } else if((opType == "answerxml") || (opType == "answerxml2c")) { + response_content += "'"; + response_content += param1; + response_content += "' applied on server FIFO queue"; + response_content += "\n"; + } else if(opType == "answerxml2e") { + response_content += "'"; + response_content += param1; + response_content += "' applied on client FIFO queue"; + response_content += "\n"; + } else if(opType == "diameterServerSessions") { + response_content += "Maximum server socket connections updated to '"; + response_content += param1; + response_content += "'."; + response_content += "\n"; + } +} + +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: + //default: + // return -1; // IEC model and Unknown traffic types + } + } 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"); + anna::comm::Application::asXML(result); + // Timming: + result->createAttribute("StartTime", a_start_time.asString()); + result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000); + // Diameter: + (anna::functions::component (ANNA_FILE_LOCATION))->asXML(result); + // OAM: + anna::diameter::comm::OamModule::instantiate().asXML(result); + anna::diameter::codec::OamModule::instantiate().asXML(result); + // Statistics: + anna::statistics::Engine::instantiate().asXML(result); + return result; +}