From: Eduardo Ramos Testillano Date: Sun, 17 May 2015 18:32:32 +0000 (+0200) Subject: NEW Restruct launcher source code. Separate classes in different files to improve... X-Git-Tag: REFACTORING_TESTING_LIBRARY~139 X-Git-Url: https://git.teslayout.com/public/public/public/?a=commitdiff_plain;h=752438861433c3789eb1b0d9f2c15e15037595e6;p=anna.git NEW Restruct launcher source code. Separate classes in different files to improve maintenance. --- 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; +} diff --git a/example/diameter/launcher/Launcher.hpp b/example/diameter/launcher/Launcher.hpp index e69de29..9a61627 100644 --- a/example/diameter/launcher/Launcher.hpp +++ b/example/diameter/launcher/Launcher.hpp @@ -0,0 +1,111 @@ +// 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 // + + +#ifndef example_diameter_launcher_Launcher_hpp +#define example_diameter_launcher_Launcher_hpp + +// Standard +#include +#include +#include + +// Project +#include +#include +#include +#include + +namespace anna { + namespace diameter { + namespace comm { + //class Entity; + //class Response; + class LocalServer; + } + } +} + +// Process +#include "MyCommunicator.hpp" +#include "MyCounterRecorder.hpp" +#include "MyDiameterEngine.hpp" + + +class Launcher : public anna::comm::Application { + + MyCommunicator *a_communicator; + MyDiameterEngine *a_myDiameterEngine; + MyDiameterEntity *a_entity; + std::string a_logFile, a_burstLogFile; + std::ofstream a_burstLogStream; + bool a_splitLog, a_detailedLog, a_dumpLog; + anna::time::Date a_start_time; + anna::timex::Engine* a_timeEngine; + MyCounterRecorder *a_counterRecorder; + MyCounterRecorderClock *a_counterRecorderClock; + std::string a_cerPathfile; + std::string a_dwrPathfile; + + // Burst feature + int a_burstCycle; + bool a_burstRepeat; + bool a_burstActive; + std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages; + int a_burstLoadIndx; + std::map::const_iterator a_burstDeliveryIt; + int a_otaRequest; + int a_burstPopCounter; + + anna::comm::ServerSocket* a_httpServerSocket; // HTTP + MyLocalServer* a_diameterLocalServer; // DIAMETER + void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException); + void initialize() throw(anna::RuntimeException); // HTTP + void run() throw(anna::RuntimeException); + +public: + Launcher(); + + MyCommunicator *getCommunicator() throw() { return a_communicator; } + MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); } + void baseProtocolSetupAsClient(void) throw(anna::RuntimeException); + MyDiameterEntity *getEntity() throw() { return a_entity; } + MyLocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; } + void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException); + bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); } + void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw(); + void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw(); + void writeBurstLogFile(const std::string &buffer) throw(); + bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); } + void startDiameterServer(int) throw(anna::RuntimeException); + void forceCountersRecord() throw(anna::RuntimeException) { if (a_counterRecorderClock) a_counterRecorderClock->tick(); } + + anna::xml::Node* asXML(anna::xml::Node* parent) const throw(); + void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); } + void resetCounters() throw(); + void signalUSR2() throw(anna::RuntimeException); + std::string help() const throw(); + + // helpers + bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw(); + + // Burst feature + int clearBurst() throw(); // returns removed + int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException); + void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; } + int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative) + int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative) + int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative) + int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped + int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped + bool burstActive() const throw() { return a_burstActive; } + bool sendBurstMessage(bool anyway = false) throw(); + std::string lookBurst(int order) const throw(); + std::string gotoBurst(int order) throw(); +}; + +#endif diff --git a/example/diameter/launcher/MyCommunicator.cpp b/example/diameter/launcher/MyCommunicator.cpp index e69de29..6a85871 100644 --- a/example/diameter/launcher/MyCommunicator.cpp +++ b/example/diameter/launcher/MyCommunicator.cpp @@ -0,0 +1,88 @@ +// 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 + +// Process +#include "MyCommunicator.hpp" + + +void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() { + // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request. + // If user wants to test a specific answer without changing it, use send operations better than programming. + // Sequence substitution: + answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request)); + answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request)); + + // Session-Id substitution: + try { + std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request); + LOGDEBUG( + std::string msg = "Extracted Session-Id: "; + msg += sessionId; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId); + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + + // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information, + // then it will be adapted with the received data at request. + if(answer->countAvp("Subscription-Id") > 0) { + std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); + std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); + + if((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information: + answer->removeAvp("Subscription-Id", 0 /* remove all */); + } + + // Replacements: + if(msisdn != "") { + anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); + sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); + sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn); + } + + if(imsi != "") { + anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another + sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); + sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi); + } + } +} + +// HTTP +void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION)); + + if(clientSocket.support(anna::http::Transport::className()) == false) + return; + + MyHandler& httpHandler = a_contexts.get(); + httpHandler.apply(clientSocket, message); +} + +void MyCommunicator::eventBreakConnection(Server* server) +throw() { + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION)); + terminate(); + anna::comm::Communicator::eventBreakConnection(server); +} + +void MyCommunicator::terminate() +throw() { + if(hasRequestedStop() == true) + return; + + requestStop(); +} diff --git a/example/diameter/launcher/MyCommunicator.hpp b/example/diameter/launcher/MyCommunicator.hpp index e69de29..d336c7d 100644 --- a/example/diameter/launcher/MyCommunicator.hpp +++ b/example/diameter/launcher/MyCommunicator.hpp @@ -0,0 +1,36 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyCommunicator_hpp +#define example_diameter_launcher_MyCommunicator_hpp + +// Project +#include +#include +#include + +// Process +#include "MyHandler.hpp" + + +class MyCommunicator : public anna::comm::Communicator { +public: + MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode), + a_contexts("Contexts") + {;} + + void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw(); + void terminate() throw(); + +private: + anna::ThreadData a_contexts; + void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException); + void eventBreakConnection(Server* server) throw(); +}; + +#endif diff --git a/example/diameter/launcher/MyCounterRecorder.cpp b/example/diameter/launcher/MyCounterRecorder.cpp index e69de29..4f62f72 100644 --- a/example/diameter/launcher/MyCounterRecorder.cpp +++ b/example/diameter/launcher/MyCounterRecorder.cpp @@ -0,0 +1,73 @@ +// 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 // + + +// Process +#include "MyCounterRecorder.hpp" + + +MyCounterRecorder::MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) { + a_previousTime = ::time(NULL); +} + +// pure virtual definitions: +void MyCounterRecorder::open() throw(anna::RuntimeException) { + static char str [256]; + const time_t now = ::time(NULL); + struct tm tmNow; + struct tm tmPrevious; + anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow)); + anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious)); + sprintf( + str, ".Date%04d%02d%02d.Time%02d%02d%02d", + 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, + tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec); + a_fileName = a_fileNamePrefix; + a_fileName += str; + LOGDEBUG( + std::string msg("Flush counters | "); + msg += a_fileName; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1) + throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); + + sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d", + 1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1, + tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min, + 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, + tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min + ); + a_fixedLine = str; +} + +void MyCounterRecorder::apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) { + static char line [356]; + anna::oam::Counter::type_t value = counter; + sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str()); + + if(write(a_stream, line, anna_strlen(line)) == -1) + throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); +} + +void MyCounterRecorder::close() throw() { + if(a_stream != -1) { + ::close(a_stream); + a_stream = -1; + } + +chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR); +a_previousTime = ::time(NULL); +} + +std::string MyCounterRecorder::asString() const throw() { + std::string result = "Physical counters dump at file '"; + result += a_fileName; + result += "'. Another way to see counters: context dump (kill -10 "; + return result; +} diff --git a/example/diameter/launcher/MyCounterRecorder.hpp b/example/diameter/launcher/MyCounterRecorder.hpp index e69de29..d283125 100644 --- a/example/diameter/launcher/MyCounterRecorder.hpp +++ b/example/diameter/launcher/MyCounterRecorder.hpp @@ -0,0 +1,40 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyCounterRecorder_hpp +#define example_diameter_launcher_MyCounterRecorder_hpp + +// Standard +#include // chmod +#include // open / write +#include + +// Process +#include "MyCounterRecorderClock.hpp" + + +class MyCounterRecorder : public anna::oam::CounterRecorder { + + // attributes + int a_stream; + std::string a_fileNamePrefix; + std::string a_fileName; + time_t a_previousTime; + std::string a_fixedLine; + + // pure virtual definitions: + void open() throw(anna::RuntimeException); + void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException); + void close() throw(); + std::string asString() const throw(); + +public: + MyCounterRecorder(const std::string &fnp); +}; + +#endif diff --git a/example/diameter/launcher/MyCounterRecorderClock.hpp b/example/diameter/launcher/MyCounterRecorderClock.hpp index e69de29..56a47a3 100644 --- a/example/diameter/launcher/MyCounterRecorderClock.hpp +++ b/example/diameter/launcher/MyCounterRecorderClock.hpp @@ -0,0 +1,32 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyCounterRecorderClock_hpp +#define example_diameter_launcher_MyCounterRecorderClock_hpp + +// Project +#include +#include +#include +#include + + +class MyCounterRecorderClock : public anna::timex::Clock { +public: + MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) : + anna::timex::Clock(clockName, timeout) {;} + //virtual ~MyCounterRecorderClock(); + + virtual bool tick() throw(anna::RuntimeException) { + anna::diameter::comm::OamModule::instantiate().recordCounters(); + anna::diameter::codec::OamModule::instantiate().recordCounters(); + return true; + } +}; + +#endif diff --git a/example/diameter/launcher/MyDiameterEngine.hpp b/example/diameter/launcher/MyDiameterEngine.hpp index e69de29..8491fd9 100644 --- a/example/diameter/launcher/MyDiameterEngine.hpp +++ b/example/diameter/launcher/MyDiameterEngine.hpp @@ -0,0 +1,51 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyDiameterEngine_hpp +#define example_diameter_launcher_MyDiameterEngine_hpp + +// Project +#include + +// Process +#include "MyDiameterEntity.hpp" +#include "MyLocalServer.hpp" + + +class MyDiameterEngine : public anna::diameter::comm::Engine { +public: + + static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; } + MyDiameterEngine() {;} + +// Default implementation is enough +// void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied +// void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied +// void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied + +private: + anna::Recycler a_entitiesRecycler; + + anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); } + + void releaseEntity(anna::diameter::comm::Entity* entity) throw() { + MyDiameterEntity* aux = static_cast (entity); + a_entitiesRecycler.release(aux); + } + + anna::Recycler a_localServersRecycler; + + anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); } + + void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() { + MyLocalServer* aux = static_cast (localServer); + a_localServersRecycler.release(aux); + } +}; + +#endif diff --git a/example/diameter/launcher/MyDiameterEntity.cpp b/example/diameter/launcher/MyDiameterEntity.cpp index e69de29..c69290d 100644 --- a/example/diameter/launcher/MyDiameterEntity.cpp +++ b/example/diameter/launcher/MyDiameterEntity.cpp @@ -0,0 +1,232 @@ +// 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 + +// Process +#include "MyDiameterEntity.hpp" +#include "Launcher.hpp" + +// Auxiliary message for sendings +extern anna::diameter::comm::Message G_commMsgSent2e, G_commMsgFwd2c; +extern anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg; +extern anna::Recycler G_commMessages; // create on requests forwards without programmed answer / release in answers forward + + +void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Request received: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); + + // Lookup reacting answers list: + int code = cid.first; + anna::diameter::codec::Message *answer_message = a_reactingAnswers.getMessage(code); + if (answer_message) { + // Prepare answer: + my_app.getCommunicator()->prepareAnswer(answer_message, message); + + try { + G_commMsgSent2e.setBody(answer_message->code()); + /* response = NULL =*/clientSession->send(&G_commMsgSent2e); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString()); + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString()); + } + + // Pop front the reacting answer: + a_reactingAnswers.nextMessage(code); + return; + } + + LOGDEBUG + ( + std::string msg = "No answers programmed (maybe sold out) for request coming from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // not found: forward to client (if exists) + // Forward to client: + anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); + + if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) { + try { + anna::diameter::comm::Message *msg = G_commMessages.create(); + msg->updateEndToEnd(false); // end-to-end will be kept + msg->setBody(message); + msg->setRequestClientSessionKey(clientSession->getKey()); + bool success = localServer->send(msg); + + // Detailed log: + if(my_app.logEnabled()) { + anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail); + } + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + } +} + +void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION)); + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::diameter::comm::ClassCode::_v code = response.getClassCode(); + anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); + anna::diameter::comm::Message* request = const_cast(response.getRequest()); + const anna::DataBlock* message = response.getMessage(); + const anna::diameter::comm::ClientSession *clientSession = static_cast(response.getSession()); + bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); + bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); + bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); + bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); + bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); + // CommandId: + anna::diameter::CommandId request_cid = request->getCommandId(); + LOGDEBUG + ( + std::string msg = "Response received for original diameter request: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + msg += " | Response: "; + msg += response.asString(); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(isUnavailable) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION)); + } + + if(contextExpired) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION)); + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString()); + } + } + + if(isOK) { + LOGDEBUG( + std::string msg = "Received response for diameter message: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + // Write reception + bool alreadyDecodedOnG_codecMsg = false; + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) { + my_app.writeLogFile(*message, "recvfe", clientSession->asString()); + alreadyDecodedOnG_codecMsg = true; + } + } + + // Forward to client: + anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); + + if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) { + try { + G_commMsgFwd2c.updateEndToEnd(false); // end-to-end will be kept + G_commMsgFwd2c.setBody(*message); + bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey()); + G_commMessages.release(request); + // Detailed log: + anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey()); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + + if(my_app.logEnabled()) { + if(alreadyDecodedOnG_codecMsg) + my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail); + else + my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail); + } + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + } + } + + // Triggering burst: + if(isOK || contextExpired) my_app.sendBurstMessage(); +} + +void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Out-of-context response received from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString()); +} + +void MyDiameterEntity::eventDPA(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventDPA", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Disconnect-Peer-Answer received from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); +} diff --git a/example/diameter/launcher/MyDiameterEntity.hpp b/example/diameter/launcher/MyDiameterEntity.hpp index e69de29..fe23cfa 100644 --- a/example/diameter/launcher/MyDiameterEntity.hpp +++ b/example/diameter/launcher/MyDiameterEntity.hpp @@ -0,0 +1,35 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyDiameterEntity_hpp +#define example_diameter_launcher_MyDiameterEntity_hpp + +// Project +#include + +// Process +#include "ProgrammedAnswers.hpp" + + +class MyDiameterEntity : public anna::diameter::comm::Entity { + + void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); + void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventDPA(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + + // Reimplementation + int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw(); + +public: + + ProgrammedAnswers a_reactingAnswers; + ProgrammedAnswers *getReactingAnswers() throw() { return (ProgrammedAnswers *)&a_reactingAnswers; } +}; + +#endif diff --git a/example/diameter/launcher/MyHandler.cpp b/example/diameter/launcher/MyHandler.cpp index e69de29..f35c89f 100644 --- a/example/diameter/launcher/MyHandler.cpp +++ b/example/diameter/launcher/MyHandler.cpp @@ -0,0 +1,62 @@ +// 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 // + + +// Standard +#include + +// Project +#include + +// Process +#include "MyHandler.hpp" +#include "Launcher.hpp" + + +void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request) +throw(anna::RuntimeException) { + const anna::DataBlock& body = request.getBody(); + + if(body.getSize() == 0) + throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION); + + LOGINFORMATION( + std::string msg("Received body: "); + msg += anna::functions::asString(body); + anna::Logger::information(msg, ANNA_FILE_LOCATION); + ); + std::string body_content; + body_content.assign(body.getData(), body.getSize()); + // Operation: + std::string response_content; + + try { + Launcher& my_app = static_cast (anna::app::functions::getApp()); + my_app.eventOperation(body_content, response_content); + } catch(RuntimeException &ex) { + ex.trace(); + } + + anna::http::Response* response = allocateResponse(); + response->setStatusCode(200); // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes + anna::DataBlock db_content(true); + db_content = response_content; + response->setBody(db_content); +// response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT"); +// anna::http::Header* keepAlive = response->find("Keep-Alive"); +// +// if (keepAlive == NULL) +// keepAlive = response->createHeader("Keep-Alive"); +// +// keepAlive->setValue("Verificacion del cambio 1.0.7"); + + try { + clientSocket.send(*response); + } catch(Exception& ex) { + ex.trace(); + } +} diff --git a/example/diameter/launcher/MyHandler.hpp b/example/diameter/launcher/MyHandler.hpp index e69de29..5f04d91 100644 --- a/example/diameter/launcher/MyHandler.hpp +++ b/example/diameter/launcher/MyHandler.hpp @@ -0,0 +1,29 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyHandler_hpp +#define example_diameter_launcher_MyHandler_hpp + +// Project +#include +#include + + +class MyHandler : public anna::http::Handler { +public: + MyHandler() : anna::http::Handler("http_converter::MyHandler") { + allocateResponse()->createHeader(anna::http::Header::Type::Date); + } + +private: + + void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException); + void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;} +}; + +#endif diff --git a/example/diameter/launcher/MyLocalServer.cpp b/example/diameter/launcher/MyLocalServer.cpp index e69de29..dab87d1 100644 --- a/example/diameter/launcher/MyLocalServer.cpp +++ b/example/diameter/launcher/MyLocalServer.cpp @@ -0,0 +1,245 @@ +// 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 + +// Process +#include "MyLocalServer.hpp" +#include "Launcher.hpp" + +// Auxiliary message for sendings +extern anna::diameter::comm::Message G_commMsgSent2c, G_commMsgFwd2e; +extern anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg; +extern anna::Recycler G_commMessages; // create on requests forwards without programmed answer / release in answers forward + + +void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Request received: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); + + // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point) + int code = cid.first; + anna::diameter::codec::Message *programmed_answer = a_reactingAnswers.getMessage(code); + bool programmed = (programmed_answer != NULL); + + anna::diameter::comm::Entity *entity = my_app.getEntity(); + if(!programmed && entity) { // forward condition (no programmed answer + entity available) + anna::diameter::comm::Message *msg = G_commMessages.create(); + msg->updateEndToEnd(false); // end-to-end will be kept + msg->setBody(message); + msg->setRequestServerSessionKey(serverSession->getKey()); + bool success = entity->send(msg, cl.exists("balance")); + + // Detailed log: + if(my_app.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 + my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded + } + + return; + } + + // Error analisys: + bool analysisOK = true; // by default + anna::diameter::codec::Message *answer_message = NULL; + + if(!cl.exists("ignoreErrors")) { // Error analysis + answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg; + answer_message->clear(); + + // Decode + try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); } + + answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm()); + analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); + } + + // Programmed answer only when all is ok + if(analysisOK) { + if(programmed) { + answer_message = programmed_answer; + // Prepare answer: + my_app.getCommunicator()->prepareAnswer(answer_message, message); + } else return; // nothing done + } + + anna::diameter::codec::Engine *codecEngine = (anna::functions::component (ANNA_FILE_LOCATION)); + anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode(); + + if(!analysisOK) + codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never); + + try { + G_commMsgSent2c.setBody(answer_message->code()); + /* response = NULL =*/serverSession->send(&G_commMsgSent2c); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString()); + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString()); + } + + // Restore validation mode + codecEngine->setValidationMode(backupVM); + + // Pop front the reacting answer: + if(analysisOK && programmed) a_reactingAnswers.nextMessage(code); +} + +void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION)); + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::diameter::comm::ClassCode::_v code = response.getClassCode(); + anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); + anna::diameter::comm::Message* request = const_cast(response.getRequest()); + const anna::DataBlock* message = response.getMessage(); + const anna::diameter::comm::ServerSession *serverSession = static_cast(response.getSession()); + bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); + bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); + bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); + bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); + bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); + // CommandId: + anna::diameter::CommandId request_cid = request->getCommandId(); + LOGDEBUG + ( + std::string msg = "Response received for original diameter request: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + msg += " | Response: "; + msg += response.asString(); + msg += " | LocalServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(isUnavailable) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION)); + } + + if(contextExpired) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION)); + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString()); + } + } + + if(isOK) { + LOGDEBUG( + std::string msg = "Received response for diameter message: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString()); + + // This is not very usual, but answers could arrive from clients: + anna::diameter::comm::Entity *entity = my_app.getEntity(); + + if(entity) { + anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey()); + std::string detail; + + if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir + + try { + G_commMsgFwd2e.updateEndToEnd(false); // end-to-end will be kept + G_commMsgFwd2e.setBody(*message); + + // Metodo 1: + if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e); + + // Metodo 2: + //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey()); + //bool success = entity->send(G_commMsgFwd2e); + G_commMessages.release(request); + + if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded + } + } + } +} + +void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Out-of-context response received from client: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString()); +} + +void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Disconnect-Peer-Answer response received from client: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); +} diff --git a/example/diameter/launcher/MyLocalServer.hpp b/example/diameter/launcher/MyLocalServer.hpp index e69de29..65b74e2 100644 --- a/example/diameter/launcher/MyLocalServer.hpp +++ b/example/diameter/launcher/MyLocalServer.hpp @@ -0,0 +1,32 @@ +// 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 // + + +#ifndef example_diameter_launcher_MyLocalServer_hpp +#define example_diameter_launcher_MyLocalServer_hpp + +// Project +#include + +// Process +#include "ProgrammedAnswers.hpp" + + +class MyLocalServer : public anna::diameter::comm::LocalServer { + + void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); + void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventDPA(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); + +public: + + ProgrammedAnswers a_reactingAnswers; + ProgrammedAnswers *getReactingAnswers() throw() { return (ProgrammedAnswers *)&a_reactingAnswers; } +}; + +#endif diff --git a/example/diameter/launcher/ProgrammedAnswers.cpp b/example/diameter/launcher/ProgrammedAnswers.cpp index e69de29..5f6dd4f 100644 --- a/example/diameter/launcher/ProgrammedAnswers.cpp +++ b/example/diameter/launcher/ProgrammedAnswers.cpp @@ -0,0 +1,111 @@ +// 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 // + + +// Standard +#include +#include + +// Project +#include + +// Process +#include "ProgrammedAnswers.hpp" + + +void ProgrammedAnswers::clear () throw() { + for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + engine->releaseMessage(*(it->second->begin())); + delete(it->second); + } + a_deques.clear(); +} + +void ProgrammedAnswers::dump () throw() { + std::string outfilename, xmlString; + for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + int sequence = 1; + for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { + // programmed_answer.. + outfilename = "programmed_answer."; + outfilename += anna::functions::asString(it->first); + outfilename += "."; + outfilename += anna::functions::asString(sequence++); + outfilename += ".xml"; + std::ofstream outfile(outfilename.c_str(), std::ifstream::out); + xmlString = (*itm)->asXMLString(); + outfile.write(xmlString.c_str(), xmlString.size()); + outfile.close(); + } + } +} + +void ProgrammedAnswers::addMessage(int code, anna::diameter::codec::Message *message) throw() { + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + it->second->push_back(message); + } + else { + codec_messages_deque *deque = new codec_messages_deque; + a_deques[code] = deque; + deque->push_back(message); + } +} + +anna::diameter::codec::Message* ProgrammedAnswers::getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty + anna::diameter::codec::Message *result = NULL; + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + if (!it->second->empty()) result = *(it->second->begin()); + } + return result; +} + +void ProgrammedAnswers::nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty) + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + if (!it->second->empty()) { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + if (a_rotate) { + addMessage(code, *(it->second->begin())); + } + else { + engine->releaseMessage(*(it->second->begin())); + } + it->second->pop_front(); + } + } +} + +std::string ProgrammedAnswers::asString(const char *queueName) const throw() { + std::string result = ""; + std::string aux = "FIFO QUEUE '"; + aux += queueName; + aux += "', Rotation "; + aux += a_rotate ? "enabled":"disabled"; + result += anna::functions::highlightJustify(aux); + if(a_deques.size() != 0) { + for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + if (it->second->size() != 0) { + aux = "Answer code "; + aux += anna::functions::asString(it->first); + result += anna::functions::highlightJustify(aux, anna::functions::TextHighlightMode::OverAndUnderline, + anna::functions::TextJustifyMode::Left, '-'); + for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { + result += (*itm)->asXMLString(); + result += "\n"; + } + result += "\n"; + } + } + } + else { + result = "No ocurrences found\n\n"; + } + return result; +} diff --git a/example/diameter/launcher/ProgrammedAnswers.hpp b/example/diameter/launcher/ProgrammedAnswers.hpp index e69de29..00b9d4d 100644 --- a/example/diameter/launcher/ProgrammedAnswers.hpp +++ b/example/diameter/launcher/ProgrammedAnswers.hpp @@ -0,0 +1,53 @@ +// 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 // + + +#ifndef example_diameter_launcher_ProgrammedAnswers_hpp +#define example_diameter_launcher_ProgrammedAnswers_hpp + +// Standard +#include +#include +#include + +namespace anna { + namespace diameter { + namespace codec { + class Message; + } + } +} + + +class ProgrammedAnswers { + +typedef std::deque codec_messages_deque; +typedef std::deque::iterator codec_messages_deque_iterator; +typedef std::deque::const_iterator codec_messages_deque_const_iterator; +typedef std::map < int /* message code */, codec_messages_deque* > reacting_answers_container; +typedef std::map < int /* message code */, codec_messages_deque* >::iterator reacting_answers_iterator; +typedef std::map < int /* message code */, codec_messages_deque* >::const_iterator reacting_answers_const_iterator; + + reacting_answers_container a_deques; + bool a_rotate; + + public: + ProgrammedAnswers() { a_rotate = false; } + ~ProgrammedAnswers() { clear(); } + + bool rotate() const throw() { return a_rotate; } + void rotate(bool r) throw() { a_rotate = r; } + + void clear () throw(); + void dump () throw(); + void addMessage(int code, anna::diameter::codec::Message *message) throw(); + anna::diameter::codec::Message* getMessage(int code) const throw(); + void nextMessage(int code) throw(); + std::string asString(const char *queueName) const throw(); +}; + +#endif diff --git a/example/diameter/launcher/main.cpp b/example/diameter/launcher/main.cpp index dde2f7c..b27f4ee 100644 --- a/example/diameter/launcher/main.cpp +++ b/example/diameter/launcher/main.cpp @@ -6,1029 +6,14 @@ // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // -#include -#include -#include -#include // chmod -#include // open / write - -#include -#include -#include - - -#include -#include +// Project #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include - -namespace anna { -class DataBlock; -} - -namespace anna { -namespace diameter { -namespace comm { -class Entity; -class Response; -class LocalServer; -} -} -} - -#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::comm::Message G_commMsg; -anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg; -anna::Recycler G_commMessages; // create on requests forwards without programmed answer / release in answers forward - -// Auxiliary resources for answers programming -class ProgrammedAnswers { - -typedef std::deque codec_messages_deque; -typedef std::deque::iterator codec_messages_deque_iterator; -typedef std::deque::const_iterator codec_messages_deque_const_iterator; -typedef std::map < int /* message code */, codec_messages_deque* > reacting_answers_container; -typedef std::map < int /* message code */, codec_messages_deque* >::iterator reacting_answers_iterator; -typedef std::map < int /* message code */, codec_messages_deque* >::const_iterator reacting_answers_const_iterator; - - reacting_answers_container a_deques; - bool a_rotate; - - public: - ProgrammedAnswers() { a_rotate = false; } - ~ProgrammedAnswers() { clear(); } - - bool rotate() const throw() { return a_rotate; } - void rotate(bool r) throw() { a_rotate = r; } - - void clear () throw() { - for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { - anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); - engine->releaseMessage(*(it->second->begin())); - delete(it->second); - } - a_deques.clear(); - } - - void dump () throw() { - std::string outfilename, xmlString; - for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { - int sequence = 1; - for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { - // programmed_answer.. - outfilename = "programmed_answer."; - outfilename += anna::functions::asString(it->first); - outfilename += "."; - outfilename += anna::functions::asString(sequence++); - outfilename += ".xml"; - std::ofstream outfile(outfilename.c_str(), std::ifstream::out); - xmlString = (*itm)->asXMLString(); - outfile.write(xmlString.c_str(), xmlString.size()); - outfile.close(); - } - } - } - - void addMessage(int code, anna::diameter::codec::Message *message) throw() { - reacting_answers_const_iterator it = a_deques.find(code); - if (it != a_deques.end()) { - it->second->push_back(message); - } - else { - codec_messages_deque *deque = new codec_messages_deque; - a_deques[code] = deque; - deque->push_back(message); - } - } - - anna::diameter::codec::Message* getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty - anna::diameter::codec::Message *result = NULL; - reacting_answers_const_iterator it = a_deques.find(code); - if (it != a_deques.end()) { - if (!it->second->empty()) result = *(it->second->begin()); - } - return result; - } - - void nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty) - reacting_answers_const_iterator it = a_deques.find(code); - if (it != a_deques.end()) { - if (!it->second->empty()) { - anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); - if (a_rotate) { - addMessage(code, *(it->second->begin())); - } - else { - engine->releaseMessage(*(it->second->begin())); - } - it->second->pop_front(); - } - } - } - - std::string asString(const char *queueName) const throw() { - std::string result = ""; - std::string aux = "FIFO QUEUE '"; - aux += queueName; - aux += "', Rotation "; - aux += a_rotate ? "enabled":"disabled"; - result += anna::functions::highlightJustify(aux); - if(a_deques.size() != 0) { - for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { - if (it->second->size() != 0) { - aux = "Answer code "; - aux += anna::functions::asString(it->first); - result += anna::functions::highlightJustify(aux, anna::functions::TextHighlightMode::OverAndUnderline, - anna::functions::TextJustifyMode::Left, '-'); - for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { - result += (*itm)->asXMLString(); - result += "\n"; - } - result += "\n"; - } - } - } - else { - result = "No ocurrences found\n\n"; - } - return result; - } -}; - -ProgrammedAnswers G_reactingAnswers2C, G_reactingAnswers2E; - - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// COUNTERS RECORD PROCEDURE ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -class MyCounterRecorderClock : public anna::timex::Clock { -public: - MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) : - anna::timex::Clock(clockName, timeout) {;} - //virtual ~MyCounterRecorderClock(); - - virtual bool tick() throw(RuntimeException) { - anna::diameter::comm::OamModule::instantiate().recordCounters(); - anna::diameter::codec::OamModule::instantiate().recordCounters(); - return true; - } -}; - -class MyCounterRecorder : public anna::oam::CounterRecorder { - - // attributes - int a_stream; - std::string a_fileNamePrefix; - std::string a_fileName; - time_t a_previousTime; - std::string a_fixedLine; - - // pure virtual definitions: - void open() throw(anna::RuntimeException) { - static char str [256]; - const time_t now = ::time(NULL); - struct tm tmNow; - struct tm tmPrevious; - anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow)); - anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious)); - sprintf( - str, ".Date%04d%02d%02d.Time%02d%02d%02d", - 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, - tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec); - a_fileName = a_fileNamePrefix; - a_fileName += str; - LOGDEBUG( - std::string msg("Flush counters | "); - msg += a_fileName; - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1) - throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); - - sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d", - 1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1, - tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min, - 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, - tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min - ); - a_fixedLine = str; - } - - - void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) { - static char line [356]; - anna::oam::Counter::type_t value = counter; - sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str()); - - if(write(a_stream, line, anna_strlen(line)) == -1) - throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); - } - - void close() throw() { - if(a_stream != -1) { - ::close(a_stream); - a_stream = -1; - } - - chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR); - a_previousTime = ::time(NULL); - } - - std::string asString() const throw() { - std::string result = "Physical counters dump at file '"; - result += a_fileName; - result += "'. Another way to see counters: context dump (kill -10 "; - return result; - } - -public: - MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) { - a_previousTime = ::time(NULL); - } -}; - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - -class MyDiameterEntity : public anna::diameter::comm::Entity { - - void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); - void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); - void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); - void eventDPA(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); - - // Reimplementation - int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw(); -}; - -class MyLocalServer : public anna::diameter::comm::LocalServer { - - void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); - void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); - void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); - void eventDPA(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); -}; - -class MyDiameterEngine : public anna::diameter::comm::Engine { -public: - - static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; } - MyDiameterEngine() {;} - -// Default implementation is enough -// void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied -// void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied -// void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied - -private: - anna::Recycler a_entitiesRecycler; - - anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); } - - void releaseEntity(anna::diameter::comm::Entity* entity) throw() { - MyDiameterEntity* aux = static_cast (entity); - a_entitiesRecycler.release(aux); - } - - anna::Recycler a_localServersRecycler; - - anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); } - - void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() { - MyLocalServer* aux = static_cast (localServer); - a_localServersRecycler.release(aux); - } -}; - - -class MyHandler : public anna::http::Handler { -public: - MyHandler() : anna::http::Handler("http_converter::MyHandler") { - allocateResponse()->createHeader(anna::http::Header::Type::Date); - } - -private: - - void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException); - void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;} -}; - -class MyCommunicator : public anna::comm::Communicator { -public: - MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode), - a_contexts("Contexts") - {;} - - void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw(); - void terminate() throw(); - -private: - anna::ThreadData a_contexts; - void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException); - void eventBreakConnection(Server* server) throw(); -}; - -class Launcher : public anna::comm::Application { - - MyCommunicator *a_communicator; - MyDiameterEngine *a_myDiameterEngine; - anna::diameter::comm::Entity *a_entity; - std::string a_logFile, a_burstLogFile; - std::ofstream a_burstLogStream; - bool a_splitLog, a_detailedLog, a_dumpLog; - anna::time::Date a_start_time; - anna::timex::Engine* a_timeEngine; - MyCounterRecorder *a_counterRecorder; - MyCounterRecorderClock *a_counterRecorderClock; - std::string a_cerPathfile; - std::string a_dwrPathfile; - - // Burst feature - int a_burstCycle; - bool a_burstRepeat; - bool a_burstActive; - std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages; - int a_burstLoadIndx; - std::map::const_iterator a_burstDeliveryIt; - int a_otaRequest; - int a_burstPopCounter; - - anna::comm::ServerSocket* a_httpServerSocket; // HTTP - anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER - void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException); - void initialize() throw(anna::RuntimeException); // HTTP - void run() throw(anna::RuntimeException); - -public: - Launcher(); - - MyCommunicator *getCommunicator() throw() { return a_communicator; } - MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); } - void baseProtocolSetupAsClient(void) throw(anna::RuntimeException); - anna::diameter::comm::Entity *getEntity() throw() { return a_entity; } - anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; } - void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException); - bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); } - void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw(); - void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw(); - void writeBurstLogFile(const std::string &buffer) throw(); - bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); } - void startDiameterServer(int) throw(anna::RuntimeException); - void forceCountersRecord() throw(anna::RuntimeException) { if (a_counterRecorderClock) a_counterRecorderClock->tick(); } - - anna::xml::Node* asXML(anna::xml::Node* parent) const throw(); - void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); } - void resetCounters() throw(); - void signalUSR2() throw(anna::RuntimeException); - std::string help() const throw(); - - // helpers - bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw(); - - // Burst feature - int clearBurst() throw(); // returns removed - int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException); - void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; } - int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative) - int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative) - int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative) - int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped - int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped - bool burstActive() const throw() { return a_burstActive; } - bool sendBurstMessage(bool anyway = false) throw(); - std::string lookBurst(int order) const throw(); - std::string gotoBurst(int order) throw(); -}; - -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 MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() { - // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request. - // If user wants to test a specific answer without changing it, use send operations better than programming. - // Sequence substitution: - answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request)); - answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request)); - - // Session-Id substitution: - try { - std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request); - LOGDEBUG( - std::string msg = "Extracted Session-Id: "; - msg += sessionId; - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId); - } catch(anna::RuntimeException &ex) { - ex.trace(); - } - - // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information, - // then it will be adapted with the received data at request. - if(answer->countAvp("Subscription-Id") > 0) { - std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); - std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); - - if((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information: - answer->removeAvp("Subscription-Id", 0 /* remove all */); - } - - // Replacements: - if(msisdn != "") { - anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); - sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); - sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn); - } - - if(imsi != "") { - anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another - sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); - sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi); - } - } -} - -// HTTP -void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION)); - - if(clientSocket.support(anna::http::Transport::className()) == false) - return; +#include - MyHandler& httpHandler = a_contexts.get(); - httpHandler.apply(clientSocket, message); -} +// Process +#include "Launcher.hpp" -using namespace std; -using namespace anna::diameter; int main(int argc, const char** argv) { anna::Logger::setLevel(anna::Logger::Warning); @@ -1039,7 +24,7 @@ int main(int argc, const char** argv) { anna::http::functions::initialize(); try { - CommandLine& commandLine(anna::CommandLine::instantiate()); + anna::CommandLine& commandLine(anna::CommandLine::instantiate()); // General commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)"); commandLine.add("log", anna::CommandLine::Argument::Optional, "Process log file (operations result, traffic log, etc.). By default 'launcher.log'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever)"); @@ -1079,1644 +64,9 @@ int main(int argc, const char** argv) { commandLine.verify(); std::cout << commandLine.asString() << std::endl; app.start(); - } catch(Exception& ex) { - cout << ex.asString() << endl; + } catch(anna::Exception& ex) { + std::cout << ex.asString() << std::endl; } return 0; } - -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_myDiameterEngine->setFreezeEndToEndOnSending(); - 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_burstMessages.clear(); - 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; - } - - ofstream out(targetFile.c_str(), ifstream::out | 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"; - ofstream outMsg(name.c_str(), ifstream::out | 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() { - ofstream out(a_burstLogFile.c_str(), ifstream::out | 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 = 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 = 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(); -} - -void MyCommunicator::eventBreakConnection(Server* server) -throw() { - LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION)); - terminate(); - anna::comm::Communicator::eventBreakConnection(server); -} - -void MyCommunicator::terminate() -throw() { - if(hasRequestedStop() == true) - return; - - requestStop(); -} - -void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request) -throw(anna::RuntimeException) { - const anna::DataBlock& body = request.getBody(); - - if(body.getSize() == 0) - throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION); - - LOGINFORMATION( - string msg("Received body: "); - msg += anna::functions::asString(body); - anna::Logger::information(msg, ANNA_FILE_LOCATION); - ); - std::string body_content; - body_content.assign(body.getData(), body.getSize()); - // Operation: - std::string response_content; - - try { - Launcher& my_app = static_cast (anna::app::functions::getApp()); - my_app.eventOperation(body_content, response_content); - } catch(RuntimeException &ex) { - ex.trace(); - } - - anna::http::Response* response = allocateResponse(); - response->setStatusCode(200); // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes - anna::DataBlock db_content(true); - db_content = response_content; - response->setBody(db_content); -// response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT"); -// anna::http::Header* keepAlive = response->find("Keep-Alive"); -// -// if (keepAlive == NULL) -// keepAlive = response->createHeader("Keep-Alive"); -// -// keepAlive->setValue("Verificacion del cambio 1.0.7"); - - try { - clientSocket.send(*response); - } catch(Exception& ex) { - ex.trace(); - } -} - -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 - ofstream outfile(param2.c_str(), 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 - ofstream outfile(param2.c_str(), ifstream::out); - outfile.write(xmlString.c_str(), xmlString.size()); - outfile.close(); - } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) { - anna::diameter::comm::Entity *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")) { - anna::diameter::comm::Entity *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")) { - anna::diameter::comm::LocalServer *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")) { - anna::diameter::comm::LocalServer *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 << G_reactingAnswers2C.asString("ANSWERS TO CLIENT") << std::endl; - response_content = "Programmed answers dumped on stdout\n"; - return; - } else if (param1 == "rotate") { - G_reactingAnswers2C.rotate(true); - } else if (param1 == "exhaust") { - G_reactingAnswers2C.rotate(false); - } else if (param1 == "clear") { - G_reactingAnswers2C.clear(); - } else if (param1 == "dump") { - G_reactingAnswers2C.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)); - G_reactingAnswers2C.addMessage(code, message); - } - } else if(opType == "answerxml2e") { - anna::diameter::comm::Entity *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 << G_reactingAnswers2E.asString("ANSWERS TO ENTITY") << std::endl; - response_content = "Programmed answers dumped on stdout\n"; - return; - } else if (param1 == "rotate") { - G_reactingAnswers2C.rotate(true); - } else if (param1 == "exhaust") { - G_reactingAnswers2C.rotate(false); - } else if (param1 == "clear") { - G_reactingAnswers2E.clear(); - } else if (param1 == "dump") { - G_reactingAnswers2E.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)); - G_reactingAnswers2E.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; -} - - -void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - CommandLine& cl(anna::CommandLine::instantiate()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Request received: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // Write reception - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); - - // Lookup reacting answers list: - int code = cid.first; - anna::diameter::codec::Message *answer_message = G_reactingAnswers2E.getMessage(code); - if (answer_message) { - // Prepare answer: - my_app.getCommunicator()->prepareAnswer(answer_message, message); - - try { - G_commMsgSent2e.setBody(answer_message->code()); - /* response = NULL =*/clientSession->send(&G_commMsgSent2e); - - if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString()); - } catch(anna::RuntimeException &ex) { - ex.trace(); - - if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString()); - } - - // Pop front the reacting answer: - G_reactingAnswers2E.nextMessage(code); - return; - } - - LOGDEBUG - ( - std::string msg = "No answers programmed (maybe sold out) for request coming from entity: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // not found: forward to client (if exists) - // Forward to client: - anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); - - if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) { - try { - anna::diameter::comm::Message *msg = G_commMessages.create(); - msg->updateEndToEnd(false); // end-to-end will be kept - msg->setBody(message); - msg->setRequestClientSessionKey(clientSession->getKey()); - bool success = localServer->send(msg); - - // Detailed log: - if(my_app.logEnabled()) { - anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); - std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir - my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail); - } - } catch(anna::RuntimeException &ex) { - ex.trace(); - } - } -} - - -void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION)); - Launcher& my_app = static_cast (anna::app::functions::getApp()); - CommandLine& cl(anna::CommandLine::instantiate()); - anna::diameter::comm::ClassCode::_v code = response.getClassCode(); - anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); - anna::diameter::comm::Message* request = const_cast(response.getRequest()); - const anna::DataBlock* message = response.getMessage(); - const anna::diameter::comm::ClientSession *clientSession = static_cast(response.getSession()); - bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); - bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); - bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); - bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); - bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); - // CommandId: - anna::diameter::CommandId request_cid = request->getCommandId(); - LOGDEBUG - ( - std::string msg = "Response received for original diameter request: "; - msg += anna::diameter::functions::commandIdAsPairString(request_cid); - msg += " | Response: "; - msg += response.asString(); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - if(isUnavailable) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION)); - } - - if(contextExpired) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION)); - - if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA - if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString()); - } - } - - if(isOK) { - LOGDEBUG( - std::string msg = "Received response for diameter message: "; - msg += anna::diameter::functions::commandIdAsPairString(request_cid); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - // Write reception - bool alreadyDecodedOnG_codecMsg = false; - - if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA - if(my_app.logEnabled()) { - my_app.writeLogFile(*message, "recvfe", clientSession->asString()); - alreadyDecodedOnG_codecMsg = true; - } - } - - // Forward to client: - anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); - - if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) { - try { - G_commMsgFwd2c.updateEndToEnd(false); // end-to-end will be kept - G_commMsgFwd2c.setBody(*message); - bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey()); - G_commMessages.release(request); - // Detailed log: - anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey()); - std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir - - if(my_app.logEnabled()) { - if(alreadyDecodedOnG_codecMsg) - my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail); - else - my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail); - } - } catch(anna::RuntimeException &ex) { - ex.trace(); - } - } - } - - // Triggering burst: - if(isOK || contextExpired) my_app.sendBurstMessage(); -} - - -void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Out-of-context response received from entity: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // Write reception - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString()); -} - -void MyDiameterEntity::eventDPA(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventDPA", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Disconnect-Peer-Answer received from entity: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // Write reception - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); -} - -void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - CommandLine& cl(anna::CommandLine::instantiate()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Request received: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // Write reception - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); - - // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point) - int code = cid.first; - anna::diameter::codec::Message *programmed_answer = G_reactingAnswers2C.getMessage(code); - bool programmed = (programmed_answer != NULL); - - anna::diameter::comm::Entity *entity = my_app.getEntity(); - if(!programmed && entity) { // forward condition (no programmed answer + entity available) - anna::diameter::comm::Message *msg = G_commMessages.create(); - msg->updateEndToEnd(false); // end-to-end will be kept - msg->setBody(message); - msg->setRequestServerSessionKey(serverSession->getKey()); - bool success = entity->send(msg, cl.exists("balance")); - - // Detailed log: - if(my_app.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 - my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded - } - - return; - } - - // Error analisys: - bool analysisOK = true; // by default - anna::diameter::codec::Message *answer_message = NULL; - - if(!cl.exists("ignoreErrors")) { // Error analysis - answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg; - answer_message->clear(); - - // Decode - try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); } - - answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm()); - analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); - } - - // Programmed answer only when all is ok - if(analysisOK) { - if(programmed) { - answer_message = programmed_answer; - // Prepare answer: - my_app.getCommunicator()->prepareAnswer(answer_message, message); - } else return; // nothing done - } - - anna::diameter::codec::Engine *codecEngine = (anna::functions::component (ANNA_FILE_LOCATION)); - anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode(); - - if(!analysisOK) - codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never); - - try { - G_commMsgSent2c.setBody(answer_message->code()); - /* response = NULL =*/serverSession->send(&G_commMsgSent2c); - - if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString()); - } catch(anna::RuntimeException &ex) { - ex.trace(); - - if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString()); - } - - // Restore validation mode - codecEngine->setValidationMode(backupVM); - - // Pop front the reacting answer: - if(analysisOK && programmed) G_reactingAnswers2C.nextMessage(code); -} - -void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION)); - Launcher& my_app = static_cast (anna::app::functions::getApp()); - CommandLine& cl(anna::CommandLine::instantiate()); - anna::diameter::comm::ClassCode::_v code = response.getClassCode(); - anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); - anna::diameter::comm::Message* request = const_cast(response.getRequest()); - const anna::DataBlock* message = response.getMessage(); - const anna::diameter::comm::ServerSession *serverSession = static_cast(response.getSession()); - bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); - bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); - bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); - bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); - bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); - // CommandId: - anna::diameter::CommandId request_cid = request->getCommandId(); - LOGDEBUG - ( - std::string msg = "Response received for original diameter request: "; - msg += anna::diameter::functions::commandIdAsPairString(request_cid); - msg += " | Response: "; - msg += response.asString(); - msg += " | LocalServer: "; - msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - if(isUnavailable) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION)); - } - - if(contextExpired) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION)); - - if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA - if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString()); - } - } - - if(isOK) { - LOGDEBUG( - std::string msg = "Received response for diameter message: "; - msg += anna::diameter::functions::commandIdAsPairString(request_cid); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - // Write reception - if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString()); - - // This is not very usual, but answers could arrive from clients: - anna::diameter::comm::Entity *entity = my_app.getEntity(); - - if(entity) { - anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey()); - std::string detail; - - if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir - - try { - G_commMsgFwd2e.updateEndToEnd(false); // end-to-end will be kept - G_commMsgFwd2e.setBody(*message); - - // Metodo 1: - if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e); - - // Metodo 2: - //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey()); - //bool success = entity->send(G_commMsgFwd2e); - G_commMessages.release(request); - - if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded - } catch(anna::RuntimeException &ex) { - ex.trace(); - - if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded - } - } - } -} - -void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Out-of-context response received from client: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString()); -} - -void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) -throw(anna::RuntimeException) { - LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION)); - // Performance stats: - Launcher& my_app = static_cast (anna::app::functions::getApp()); - // CommandId: - anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); - LOGDEBUG - ( - std::string msg = "Disconnect-Peer-Answer response received from client: "; - msg += anna::diameter::functions::commandIdAsPairString(cid); - msg += " | DiameterServer: "; - msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); - msg += " | EventTime: "; - msg += anna::time::functions::currentTimeAsString(); - anna::Logger::debug(msg, ANNA_FILE_LOCATION); - ); - - if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); -} - -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; -} - diff --git a/include/anna/diameter.comm/Entity.hpp b/include/anna/diameter.comm/Entity.hpp index 151f0ff..2674e85 100644 --- a/include/anna/diameter.comm/Entity.hpp +++ b/include/anna/diameter.comm/Entity.hpp @@ -19,6 +19,8 @@ #include #include +#include + namespace anna { class DataBlock; @@ -39,6 +41,7 @@ class Engine; class Server; class Response; class Message; +class ClientSession; /**