From: Eduardo Ramos Testillano Date: Sat, 4 Apr 2015 01:51:53 +0000 (+0200) Subject: astyle X-Git-Tag: REFACTORING_TESTING_LIBRARY~194 X-Git-Url: https://git.teslayout.com/public/public/public/?a=commitdiff_plain;h=4456556fc4cd3d24eab8d555acceae339d476c5b;p=anna.git astyle --- diff --git a/example/diameter/launcher/main.cpp b/example/diameter/launcher/main.cpp index 7a08518..2916704 100644 --- a/example/diameter/launcher/main.cpp +++ b/example/diameter/launcher/main.cpp @@ -113,14 +113,14 @@ reacting_answers_container G_reactingAnswers2C, G_reactingAnswers2E; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // COUNTERS RECORD PROCEDURE ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class MyCounterRecorderClock : public anna::timex::Clock { - public: +public: MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) : anna::timex::Clock(clockName, timeout) {;} //virtual ~MyCounterRecorderClock(); - virtual bool tick() throw (RuntimeException) { + virtual bool tick() throw(RuntimeException) { anna::diameter::comm::OamModule::instantiate().recordCounters(); - anna::diameter::codec::OamModule::instantiate().recordCounters(); + anna::diameter::codec::OamModule::instantiate().recordCounters(); return true; } }; @@ -137,38 +137,32 @@ class MyCounterRecorder : public anna::oam::CounterRecorder { // pure virtual definitions: void open() throw(anna::RuntimeException) { static char str [256]; - - const time_t now = ::time (NULL); + 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", + 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 | "); + 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 - ); - + ); + + 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; } @@ -176,18 +170,20 @@ class MyCounterRecorder : public anna::oam::CounterRecorder { 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); + 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); + if(a_stream != -1) { + ::close(a_stream); a_stream = -1; - } - chmod (a_fileName.c_str (), S_IWUSR | S_IRUSR); - a_previousTime = ::time (NULL); + } + + chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR); + a_previousTime = ::time(NULL); } std::string asString() const throw() { @@ -197,10 +193,10 @@ class MyCounterRecorder : public anna::oam::CounterRecorder { return result; } - public: - MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) { - a_previousTime = ::time (NULL); - } +public: + MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) { + a_previousTime = ::time(NULL); + } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -208,26 +204,26 @@ class MyCounterRecorder : public anna::oam::CounterRecorder { 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 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); - // Reimplementation - int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw(); + // 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 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); }; class MyDiameterEngine : public anna::diameter::comm::Engine { public: - static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; } - MyDiameterEngine() {;} + 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 @@ -235,131 +231,131 @@ public: // void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied private: - anna::Recycler a_entitiesRecycler; + anna::Recycler a_entitiesRecycler; - anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); } + 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); - } + void releaseEntity(anna::diameter::comm::Entity* entity) throw() { + MyDiameterEntity* aux = static_cast (entity); + a_entitiesRecycler.release(aux); + } - anna::Recycler a_localServersRecycler; + anna::Recycler a_localServersRecycler; - anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); } + 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); - } + 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); - } + 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) {;} + 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") - {;} + 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(); + 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(); + 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; - 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); + 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; + 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); - - 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(); - std::string programmedAnswers2e() const throw(); - std::string programmedAnswers2c() 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(); + 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); + + 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(); + std::string programmedAnswers2e() const throw(); + std::string programmedAnswers2c() 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)); @@ -370,7 +366,6 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl msg += hexString; anna::Logger::debug(msg, ANNA_FILE_LOCATION); ); - anna::functions::fromHexString(hexString, db); // Close file infile.close(); @@ -381,738 +376,736 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl } 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 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); + 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); + 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; + 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; + 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; + 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)); + 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(!anyway && !burstActive()) return false; - if (a_burstPopCounter > 0) { - if (burstLogEnabled()) writeBurstLogFile("x"); + if(a_burstPopCounter > 0) { + if(burstLogEnabled()) writeBurstLogFile("x"); - a_burstPopCounter--; - return false; - } + a_burstPopCounter--; + return false; + } - if (a_burstDeliveryIt == a_burstMessages.end()) { - a_burstDeliveryIt = a_burstMessages.begin(); + if(a_burstDeliveryIt == a_burstMessages.end()) { + a_burstDeliveryIt = a_burstMessages.begin(); - if (!anyway) { - if (a_burstRepeat) { - a_burstCycle++; + 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"); + 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; - } + 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)); - } + 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); - } + // 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; + 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); + 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(); } + if(it != a_burstMessages.end()) { + // Decode + try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); } - result = G_codecMsg.asXMLString(); - } + result = G_codecMsg.asXMLString(); + } - return result; + 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); + 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 ("; - } + if(it != a_burstMessages.end()) { + a_burstDeliveryIt = it; + result = "Position updated for order provided ("; + } - result += anna::functions::asString(order); - result += ")"; - return result; + 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(); + // 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; + } - 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(); + 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.traces\" 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 += "\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 corresponding request from entity."; - result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for corresponding request from client."; - result += "\nanswerxml|[source_file] Same as 'answerxml2c'."; - result += "\n List programmed answers if no parameter provided."; - 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 += "\nis intended to be used with decoded messages in order to replace things like hop by hop, end to end,"; - result += "\nsubscriber id, session id, etc."; - 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 += "\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; + 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.traces\" 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 += "\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 corresponding request from entity."; + result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for corresponding request from client."; + result += "\nanswerxml|[source_file] Same as 'answerxml2c'."; + result += "\n List programmed answers if no parameter provided."; + 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 += "\nis intended to be used with decoded messages in order to replace things like hop by hop, end to end,"; + result += "\nsubscriber id, session id, etc."; + 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 += "\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; } std::string Launcher::programmedAnswers2c() const throw() { - std::string result = "\n"; - result += "\n ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n"; - - if (G_reactingAnswers2C.size() == 0) { - result += "No ocurrences found\n\n"; - } else { - for (reacting_answers_const_iterator it = G_reactingAnswers2C.begin(); it != G_reactingAnswers2C.end(); it++) { - result += (*it).second->asXMLString(); - result += "\n\n"; - } - } + std::string result = "\n"; + result += "\n ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n"; + + if(G_reactingAnswers2C.size() == 0) { + result += "No ocurrences found\n\n"; + } else { + for(reacting_answers_const_iterator it = G_reactingAnswers2C.begin(); it != G_reactingAnswers2C.end(); it++) { + result += (*it).second->asXMLString(); + result += "\n\n"; + } + } - return result; + return result; } std::string Launcher::programmedAnswers2e() const throw() { - std::string result = "\n"; - result += "\n\n ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n"; - - if (G_reactingAnswers2E.size() == 0) { - result += "No ocurrences found\n\n"; - } else { - for (reacting_answers_const_iterator it = G_reactingAnswers2E.begin(); it != G_reactingAnswers2E.end(); it++) { - result += (*it).second->asXMLString(); - result += "\n\n"; - } - } + std::string result = "\n"; + result += "\n\n ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n"; + + if(G_reactingAnswers2E.size() == 0) { + result += "No ocurrences found\n\n"; + } else { + for(reacting_answers_const_iterator it = G_reactingAnswers2E.begin(); it != G_reactingAnswers2E.end(); it++) { + result += (*it).second->asXMLString(); + result += "\n\n"; + } + } - return result; + 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(); - } + // 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); + // 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 */); - } + 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); - } + // 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); - } - } + 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)); + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION)); - if (clientSocket.support(anna::http::Transport::className()) == false) - return; + if(clientSocket.support(anna::http::Transport::className()) == false) + return; - MyHandler& httpHandler = a_contexts.get(); - httpHandler.apply(clientSocket, message); + MyHandler& httpHandler = a_contexts.get(); + httpHandler.apply(clientSocket, message); } using namespace std; using namespace anna::diameter; int main(int argc, const char** argv) { - anna::Logger::setLevel(anna::Logger::Warning); - anna::Logger::initialize("launcher", new TraceWriter("launcher.traces", 2048000)); - anna::time::functions::initialize(); // before application instantiation (it have a anna::time object) - anna::time::functions::setControlPoint(); // start control point (application lifetime) - Launcher app; - anna::http::functions::initialize(); - - try { - 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)"); - commandLine.add("splitLog", anna::CommandLine::Argument::Optional, "Splits log file (appends to log filename, extensions with the type of event: see help on startup information-level traces). No log files for code/decode and load operations are created", false); - commandLine.add("detailedLog", anna::CommandLine::Argument::Optional, "Insert detailed information at log files. Should be disabled on automatic tests. Useful on '-balance' mode to know messages flow along the sockets", false); - commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample..csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it)."); - commandLine.add("burstLog", anna::CommandLine::Argument::Optional, "Burst operations log file. By default 'launcher.burst'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst list size, plus OTA requests when changed."); - commandLine.add("cntDir", anna::CommandLine::Argument::Optional, "Counters directory. By default is the current execution directory. Warning: a counter file will be dump per record period; take care about the possible accumulation of files"); - commandLine.add("cntRecordPeriod", anna::CommandLine::Argument::Optional, "Counters record procedure period in milliseconds. If missing, default value of 300000 (5 minutes) will be assigned. Value of 0 disables the record procedure."); - // Communications - commandLine.add("httpServer", anna::CommandLine::Argument::Optional, "HTTP Management interface address (using i.e. curl tool) in '
:' format. For example: 10.20.30.40:8080"); - commandLine.add("httpServerShared", anna::CommandLine::Argument::Optional, "Enables shared bind for HTTP Management interface address. It would be useful i.e. to allow a great amount of curl operations per second", false); - commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '
:' format. For example: 10.20.30.40:3868"); - commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1"); - commandLine.add("entity", anna::CommandLine::Argument::Optional, "Target diameter entity (comma-separated '
:' format). For example: 10.20.30.40:3868,10.20.30.41:3868"); - commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1"); - commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false); - commandLine.add("sessionBasedModelsClientSocketSelection", anna::CommandLine::Argument::Optional, "By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied; usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin'."); - commandLine.add("dictionary", anna::CommandLine::Argument::Mandatory, "Diameter dictionary pathfiles (could be one or more ocurrences in a comma separated list, in order to accumulate loads). For example: avps_etsi.xml,avps_ietf.xml,avps_tgpp.xml,commands_qosControl.xml"); - commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false); - commandLine.add("ignoreErrors", anna::CommandLine::Argument::Optional, "Local server skips requests errors analysis which would prepare automatic answers for them when a problem is found. If no answer is programmed and entity is configured, a failed request would be forwarded (delegates at the end point) even if this parameter is missing", false); - commandLine.add("allowedInactivityTime", anna::CommandLine::Argument::Optional, "Milliseconds for the maximum allowed inactivity time on server sessions born over the local server before being reset. If missing, default value of 90000 will be assigned"); - commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned"); - commandLine.add("answersTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait pending application answers from diameter peers. If missing, default value of 10000 will be assigned"); - commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned"); - commandLine.add("watchdogPeriod", anna::CommandLine::Argument::Optional, "Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default value of 30000 will be assigned"); - commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned"); - commandLine.add("cer", anna::CommandLine::Argument::Optional, "Pathfile for the Capabilities Exchange Request xml message. If missing, \"cer.xml\" is searched. If missing again, process creates own CER"); - commandLine.add("dwr", anna::CommandLine::Argument::Optional, "Pathfile for the Device Watchdog Request xml message. If missing, \"dwr.xml\" is searched. If missing again, process creates own DWR"); - commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname"); - commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name"); - commandLine.add("integrationAndDebugging", anna::CommandLine::Argument::Optional, "Sets validation mode to 'Always' (default validates only after decoding), and validation depth to 'Complete' (default validates until 'FirstError')", false); + anna::Logger::setLevel(anna::Logger::Warning); + anna::Logger::initialize("launcher", new TraceWriter("launcher.traces", 2048000)); + anna::time::functions::initialize(); // before application instantiation (it have a anna::time object) + anna::time::functions::setControlPoint(); // start control point (application lifetime) + Launcher app; + anna::http::functions::initialize(); + + try { + 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)"); + commandLine.add("splitLog", anna::CommandLine::Argument::Optional, "Splits log file (appends to log filename, extensions with the type of event: see help on startup information-level traces). No log files for code/decode and load operations are created", false); + commandLine.add("detailedLog", anna::CommandLine::Argument::Optional, "Insert detailed information at log files. Should be disabled on automatic tests. Useful on '-balance' mode to know messages flow along the sockets", false); + commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample..csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it)."); + commandLine.add("burstLog", anna::CommandLine::Argument::Optional, "Burst operations log file. By default 'launcher.burst'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst list size, plus OTA requests when changed."); + commandLine.add("cntDir", anna::CommandLine::Argument::Optional, "Counters directory. By default is the current execution directory. Warning: a counter file will be dump per record period; take care about the possible accumulation of files"); + commandLine.add("cntRecordPeriod", anna::CommandLine::Argument::Optional, "Counters record procedure period in milliseconds. If missing, default value of 300000 (5 minutes) will be assigned. Value of 0 disables the record procedure."); + // Communications + commandLine.add("httpServer", anna::CommandLine::Argument::Optional, "HTTP Management interface address (using i.e. curl tool) in '
:' format. For example: 10.20.30.40:8080"); + commandLine.add("httpServerShared", anna::CommandLine::Argument::Optional, "Enables shared bind for HTTP Management interface address. It would be useful i.e. to allow a great amount of curl operations per second", false); + commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '
:' format. For example: 10.20.30.40:3868"); + commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1"); + commandLine.add("entity", anna::CommandLine::Argument::Optional, "Target diameter entity (comma-separated '
:' format). For example: 10.20.30.40:3868,10.20.30.41:3868"); + commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1"); + commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false); + commandLine.add("sessionBasedModelsClientSocketSelection", anna::CommandLine::Argument::Optional, "By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied; usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin'."); + commandLine.add("dictionary", anna::CommandLine::Argument::Mandatory, "Diameter dictionary pathfiles (could be one or more ocurrences in a comma separated list, in order to accumulate loads). For example: avps_etsi.xml,avps_ietf.xml,avps_tgpp.xml,commands_qosControl.xml"); + commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false); + commandLine.add("ignoreErrors", anna::CommandLine::Argument::Optional, "Local server skips requests errors analysis which would prepare automatic answers for them when a problem is found. If no answer is programmed and entity is configured, a failed request would be forwarded (delegates at the end point) even if this parameter is missing", false); + commandLine.add("allowedInactivityTime", anna::CommandLine::Argument::Optional, "Milliseconds for the maximum allowed inactivity time on server sessions born over the local server before being reset. If missing, default value of 90000 will be assigned"); + commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned"); + commandLine.add("answersTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait pending application answers from diameter peers. If missing, default value of 10000 will be assigned"); + commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned"); + commandLine.add("watchdogPeriod", anna::CommandLine::Argument::Optional, "Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default value of 30000 will be assigned"); + commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned"); + commandLine.add("cer", anna::CommandLine::Argument::Optional, "Pathfile for the Capabilities Exchange Request xml message. If missing, \"cer.xml\" is searched. If missing again, process creates own CER"); + commandLine.add("dwr", anna::CommandLine::Argument::Optional, "Pathfile for the Device Watchdog Request xml message. If missing, \"dwr.xml\" is searched. If missing again, process creates own DWR"); + commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname"); + commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name"); + commandLine.add("integrationAndDebugging", anna::CommandLine::Argument::Optional, "Sets validation mode to 'Always' (default validates only after decoding), and validation depth to 'Complete' (default validates until 'FirstError')", false); // commandLine.add("clone", anna::CommandLine::Argument::Optional, "Enables fork mode for request processing", false); - commandLine.initialize(argv, argc); - commandLine.verify(); - std::cout << commandLine.asString() << std::endl; - app.start(); - } catch (Exception& ex) { - cout << ex.asString() << endl; - } - - return 0; + commandLine.initialize(argv, argc); + commandLine.verify(); + std::cout << commandLine.asString() << std::endl; + app.start(); + } catch(Exception& ex) { + cout << ex.asString() << 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_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; + 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_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); - } + // 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 // @@ -1177,502 +1170,505 @@ void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) { // 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()); + // 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(); } + // Decode + try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); } - writeLogFile(G_codecMsg, logExtension, detail); + 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"; - - if (a_detailedLog) { - anna::time::Date now; - now.setNow(); - title += " "; - title += now.asString(); - log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline); - log += decodedMessage.asXMLString(); - log += "\n"; - log += anna::functions::highlight("Used resource"); - log += detail; - log += "\n"; - } else { - log += title; - log += "\n"; - log += decodedMessage.asXMLString(); - log += "\n"; - } - - // Write and close - out.write(log.c_str(), log.size()); - out.close(); + // 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"; + + if(a_detailedLog) { + anna::time::Date now; + now.setNow(); + title += " "; + title += now.asString(); + log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline); + log += decodedMessage.asXMLString(); + log += "\n"; + log += anna::functions::highlight("Used resource"); + log += detail; + log += "\n"; + } else { + log += title; + log += "\n"; + log += decodedMessage.asXMLString(); + log += "\n"; + } + + // 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. + 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()); + CommandLine& cl(anna::CommandLine::instantiate()); - if (!cl.exists(commandLineParameter) && optional) return; // start error if mandatory + if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory - std::string parameter = cl.getValue(commandLineParameter); + 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(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->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); - } + 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 - } + 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); + // 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; + 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 + 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"); + if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime"); - a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)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); + 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); - + 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) { + + 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"); + + 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(); - - try { - anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id */); - // 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); - } - } + 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); + } + } - codecEngine->setDictionary(d); - LOGDEBUG(anna::Logger::debug(codecEngine->asString(), 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()); + } - if (lst.size() > 1) { - std::string all_in_one = "./dictionary-all-in-one.xml"; - std::ofstream out(all_in_one, 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; + // Stack: + anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine(); + anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate(); + + try { + anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id */); + // 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); } + } - } catch (anna::RuntimeException &ex) { - ex.trace(); - } + codecEngine->setDictionary(d); + LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION)); - // 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); - } + if(lst.size() > 1) { + std::string all_in_one = "./dictionary-all-in-one.xml"; + std::ofstream out(all_in_one, 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; + } + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + + // 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); + } - codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); + codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); - // Diameter Server: - if (cl.exists("diameterServer")) - startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1); + // 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 + // 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("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay"); - if (cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout"); + if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout"); - if (cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout"); - else ceaTimeout = answersTimeout; + if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout"); + else ceaTimeout = answersTimeout; - if (cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod"); + if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod"); - if (cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod"); + if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod"); - a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay); - a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod); - std::string originHost = ""; - std::string originRealm = ""; + 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("cer")) a_cerPathfile = cl.getValue("cer"); - if (cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr"); + if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr"); - if (cl.exists("originHost")) originHost = cl.getValue("originHost"); + if(cl.exists("originHost")) originHost = cl.getValue("originHost"); - if (cl.exists("originRealm")) originRealm = cl.getValue("originRealm"); + if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm"); - a_myDiameterEngine->setHost(originHost); - a_myDiameterEngine->setRealm(originRealm); + a_myDiameterEngine->setHost(originHost); + a_myDiameterEngine->setRealm(originRealm); - // Diameter entity: - if (cl.exists("entity")) { - int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1; + // 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(); - } - } + 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"); + // Logs + if(cl.exists("log")) a_logFile = cl.getValue("log"); - if (cl.exists("splitLog")) a_splitLog = true; + if(cl.exists("splitLog")) a_splitLog = true; - if (cl.exists("detailedLog")) a_detailedLog = true; + if(cl.exists("detailedLog")) a_detailedLog = true; - if (cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog"); + 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(); + // 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)); - } - } + 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(); + 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); + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION)); + terminate(); + anna::comm::Communicator::eventBreakConnection(server); } void MyCommunicator::terminate() throw() { - if (hasRequestedStop() == true) - return; + if(hasRequestedStop() == true) + return; - requestStop(); + 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(); - } + 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); + 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"); // @@ -1681,653 +1677,667 @@ throw(anna::RuntimeException) { // // keepAlive->setValue("Verificacion del cambio 1.0.7"); - try { - clientSocket.send(*response); - } catch (Exception& ex) { - ex.trace(); - } + 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.traces file)\n"; - return; - } + 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.traces file)\n"; + return; + } - // Reset performance data: - if (operation == "collect") { - resetCounters(); - resetStatistics(); - response_content = "All process counters & statistic information have been reset\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(); + // Reset performance data: + if(operation == "collect") { + resetCounters(); + resetStatistics(); + response_content = "All process counters & statistic information have been reset\n"; + return; + } - } 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"; - } + /////////////////////////////////////////////////////////////////// + // 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 { - 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")) { + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port); - anna::diameter::comm::Entity *entity = getEntity(); - if (!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION); + if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide(); - 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); + 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(); - bool success = entity->send(G_commMsgSent2e, cl.exists("balance")); + 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); - // 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); + 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 ((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(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); - } 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); + int releaseLoad = atoi(param2.c_str()); + int popped = popBurst(releaseLoad); - 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()); + if(popped > 0) { + result = "Burst popped for "; + result += anna::functions::entriesAsString(popped, "message"); + result += "."; } - 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); + } 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); - bool success = localServer->send(G_commMsgSent2c); + int sent = sendBurst(atoi(param2.c_str())); - // 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); + 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(); - } else if (opType == "loadxml") { + if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION); + + if(opType == "sendxml2c") { 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 != "") { - 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; - reacting_answers_const_iterator it = G_reactingAnswers2C.find(code); - - if (it != G_reactingAnswers2C.end()) { // found: replace - LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION)); - engine->releaseMessage((*it).second); - } - - G_reactingAnswers2C[code] = message; - } else { // answers query on stdout - std::cout << programmedAnswers2c() << std::endl; - response_content = "Programmed answers dumped on stdout\n"; - return; + 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 != "") { + 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; + reacting_answers_const_iterator it = G_reactingAnswers2C.find(code); + + if(it != G_reactingAnswers2C.end()) { // found: replace + LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION)); + engine->releaseMessage((*it).second); } - } 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 != "") { - 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; - reacting_answers_const_iterator it = G_reactingAnswers2E.find(code); - - if (it != G_reactingAnswers2E.end()) { // found: replace - LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION)); - engine->releaseMessage((*it).second); - } - - G_reactingAnswers2E[code] = message; - } else { // answers query on stdout - std::cout << programmedAnswers2e() << std::endl; - response_content = "Programmed answers dumped on stdout\n"; - return; + + G_reactingAnswers2C[code] = message; + } else { // answers query on stdout + std::cout << programmedAnswers2c() << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } + } 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 != "") { + 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; + reacting_answers_const_iterator it = G_reactingAnswers2E.find(code); + + if(it != G_reactingAnswers2E.end()) { // found: replace + LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION)); + engine->releaseMessage((*it).second); } - } 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; "; + G_reactingAnswers2E[code] = message; + } else { // answers query on stdout + std::cout << programmedAnswers2e() << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } + } 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 ((opType == "decode") || (opType == "code")) { - response_content += "File '"; + if(param2 != "") { + response_content += "|"; 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 += "Answer to client '"; - response_content += param1; - response_content += "' programmed."; - response_content += "\n"; - } else if (opType == "answerxml2e") { - response_content += "Answer to entity '"; - response_content += param1; - response_content += "' programmed."; - response_content += "\n"; - } else if (opType == "diameterServerSessions") { - response_content += "Maximum server socket connections updated to '"; - response_content += param1; - response_content += "'."; - response_content += "\n"; - } + 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 += "Answer to client '"; + response_content += param1; + response_content += "' programmed."; + response_content += "\n"; + } else if(opType == "answerxml2e") { + response_content += "Answer to entity '"; + response_content += param1; + response_content += "' programmed."; + 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"); + 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 + 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); + 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); + 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 == "SessionIdLowPart") return (low % maxClientSessions); - if (sessionBasedModelsType == "SessionIdHighPart") return (high % 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); - ); - } + 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; + 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; - reacting_answers_const_iterator it = G_reactingAnswers2E.find(code); + 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; + reacting_answers_const_iterator it = G_reactingAnswers2E.find(code); + + if(it != G_reactingAnswers2E.end()) { + anna::diameter::codec::Message *answer_message = (*it).second; + // 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 (it != G_reactingAnswers2E.end()) { - anna::diameter::codec::Message *answer_message = (*it).second; - // Prepare answer: - my_app.getCommunicator()->prepareAnswer(answer_message, message); + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString()); + } + } else { // 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 { - 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()); - } - } else { // 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->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(); - } + anna::diameter::comm::Message *msg = G_commMessages.create(); + 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); - ); + 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 (isUnavailable) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", 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 (contextExpired) { - //if (isApplicationMessage) - LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION)); + 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(*request, "req2e-expired", clientSession->asString()); + 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; } - } + } - 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(); - // 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.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(); - } + if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) { + try { + 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(); + // 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()); + 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()); } @@ -2335,214 +2345,214 @@ throw(anna::RuntimeException) { 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; - reacting_answers_const_iterator it = G_reactingAnswers2C.find(code); - bool programmed = (it != G_reactingAnswers2C.end()); - 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->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 - } + 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; + reacting_answers_const_iterator it = G_reactingAnswers2C.find(code); + bool programmed = (it != G_reactingAnswers2C.end()); + 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->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; - } + return; + } - // Error analisys: - bool analysisOK = true; // by default - anna::diameter::codec::Message *answer_message = NULL; + // 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(); + 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(); } + // 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); - } + 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 = (*it).second; - // Prepare answer: - my_app.getCommunicator()->prepareAnswer(answer_message, message); - } else return; // nothing done - } + // Programmed answer only when all is ok + if(analysisOK) { + if(programmed) { + answer_message = (*it).second; + // 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(); + 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); + if(!analysisOK) + codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never); - try { - G_commMsgSent2c.setBody(answer_message->code()); - /* response = NULL =*/serverSession->send(&G_commMsgSent2c); + 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, "sent2c", serverSession->asString()); + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString()); + } - if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString()); - } - - // Restore validation mode - codecEngine->setValidationMode(backupVM); + // Restore validation mode + codecEngine->setValidationMode(backupVM); } 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)); - } + 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(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(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); - ); + 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()); + // 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(); + // 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(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 + if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir - try { - G_commMsgFwd2e.setBody(*message); + try { + G_commMsgFwd2e.setBody(*message); - // Metodo 1: - if (usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e); + // 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); + // 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, "fwd2e", detail); // forwarded + } catch(anna::RuntimeException &ex) { + ex.trace(); - if (my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded - } + 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()); + 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()); } 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; + 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/pcapDecoder/main.cpp b/example/diameter/pcapDecoder/main.cpp index 65681d8..6214825 100644 --- a/example/diameter/pcapDecoder/main.cpp +++ b/example/diameter/pcapDecoder/main.cpp @@ -290,10 +290,10 @@ void my_callback(u_char *useless, const struct pcap_pkthdr* pkthdr, } bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) 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)); @@ -304,7 +304,6 @@ bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) t msg += hexString; anna::Logger::debug(msg, ANNA_FILE_LOCATION); ); - anna::functions::fromHexString(hexString, db); // Close file infile.close(); @@ -316,10 +315,11 @@ bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) t void _exit(const std::string &message, int resultCode = 1) { - if (resultCode) + if(resultCode) std::cerr << message << std::endl << std::endl; else std::cout << message << std::endl << std::endl; + exit(resultCode); } @@ -397,11 +397,11 @@ int main(int argc, char **argv) { // Tracing: //if (cl.exists("trace")) // anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace"))); - // Check hex content input file (look extension): anna::DataBlock db_aux(true); + if(isHex) { - if (!getDataBlockFromHexFile(inputFile, db_aux)) + if(!getDataBlockFromHexFile(inputFile, db_aux)) _exit("Error reading hex file provided"); try { @@ -414,17 +414,14 @@ int main(int argc, char **argv) { outputFile += ".as.xml"; std::ofstream out(outputFile, std::ifstream::out); out << G_codecMsg.asXMLString(); - // Close output file: out.close(); - std::string msg = "Open 'file.trace' in order to see process traces.\n"; msg += "Open '"; msg += outputFile; msg += "' to see decoding results."; _exit(msg, 0); } // Normal input: pcap file: - // SNIFFING //////////////////////////////////////////////////////////////////////////////////////////////7 //temporary packet buffers struct pcap_pkthdr header; // The header that pcap gives us @@ -484,7 +481,6 @@ int main(int argc, char **argv) { // Close output file: out.close(); - std::string msg = "Open 'file.trace' in order to see process traces.\n"; msg += "Open '"; msg += outputFile; msg += "' to see decoding results."; _exit(msg, 0); diff --git a/include/anna/diameter/codec/Message.hpp b/include/anna/diameter/codec/Message.hpp index 9f3c85f..2b65175 100644 --- a/include/anna/diameter/codec/Message.hpp +++ b/include/anna/diameter/codec/Message.hpp @@ -148,28 +148,28 @@ class Message { const anna::diameter::stack::Command *getStackCommand(CommandId id) const throw(anna::RuntimeException); void setFailedAvp(const parent_t &parent, AvpId wrong, const char *wrongName = NULL) throw(anna::RuntimeException); - // During message decoding and validation, the first wrong avp is stored and all the tracking is managed to find out its - // nested path for the case of grouped avps with wrong avps inside. Remember the RFC 6733, section 7.5: - // - // In the case where the offending AVP is embedded within a Grouped AVP, - // the Failed-AVP MAY contain the grouped AVP, which in turn contains - // the single offending AVP. The same method MAY be employed if the - // grouped AVP itself is embedded in yet another grouped AVP and so on. - // In this case, the Failed-AVP MAY contain the grouped AVP hierarchy up - // to the single offending AVP. This enables the recipient to detect - // the location of the offending AVP when embedded in a group. - // - // The first wrong avp found will set the final result code, as the RFC recommends: - // - // The value of the Result-Code AVP will provide information on the reason - // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an - // instance of the Failed-AVP AVP that corresponds to the error - // indicated by the Result-Code AVP. For practical purposes, this - // Failed-AVP would typically refer to the first AVP processing error - // that a Diameter node encounters. - // - // The message keeps the list (reverse order) of avps hierarchy (in case of grouping) for the final Failed-AVP construction, - // which is done at the end of decoding or validation, and only the first wrong avp is stored with its corresponding path. + // During message decoding and validation, the first wrong avp is stored and all the tracking is managed to find out its + // nested path for the case of grouped avps with wrong avps inside. Remember the RFC 6733, section 7.5: + // + // In the case where the offending AVP is embedded within a Grouped AVP, + // the Failed-AVP MAY contain the grouped AVP, which in turn contains + // the single offending AVP. The same method MAY be employed if the + // grouped AVP itself is embedded in yet another grouped AVP and so on. + // In this case, the Failed-AVP MAY contain the grouped AVP hierarchy up + // to the single offending AVP. This enables the recipient to detect + // the location of the offending AVP when embedded in a group. + // + // The first wrong avp found will set the final result code, as the RFC recommends: + // + // The value of the Result-Code AVP will provide information on the reason + // for the Failed-AVP AVP. A Diameter answer message SHOULD contain an + // instance of the Failed-AVP AVP that corresponds to the error + // indicated by the Result-Code AVP. For practical purposes, this + // Failed-AVP would typically refer to the first AVP processing error + // that a Diameter node encounters. + // + // The message keeps the list (reverse order) of avps hierarchy (in case of grouping) for the final Failed-AVP construction, + // which is done at the end of decoding or validation, and only the first wrong avp is stored with its corresponding path. protected: diff --git a/include/anna/diameter/codec/functions.hpp b/include/anna/diameter/codec/functions.hpp index c50563a..49ab379 100644 --- a/include/anna/diameter/codec/functions.hpp +++ b/include/anna/diameter/codec/functions.hpp @@ -72,16 +72,16 @@ namespace codec { // Used for alarms, tracing and Failed-AVP construction: typedef struct parent { - // Used on decoding: - anna::diameter::CommandId MessageId; - std::string MessageName; + // Used on decoding: + anna::diameter::CommandId MessageId; + std::string MessageName; - std::vector AvpsId; - std::vector AvpsName; + std::vector AvpsId; + std::vector AvpsName; - void setMessage(const anna::diameter::CommandId & mid, const char *mname = NULL /* well known in validation */) throw(); - void addAvp(const anna::diameter::AvpId & aid, const char *aname = NULL /* well known in validation */) throw(); - std::string asString() const throw(); + void setMessage(const anna::diameter::CommandId & mid, const char *mname = NULL /* well known in validation */) throw(); + void addAvp(const anna::diameter::AvpId & aid, const char *aname = NULL /* well known in validation */) throw(); + std::string asString() const throw(); } parent_t; diff --git a/source/diameter/codec/Avp.cpp b/source/diameter/codec/Avp.cpp index 97437c1..3a2c9b0 100644 --- a/source/diameter/codec/Avp.cpp +++ b/source/diameter/codec/Avp.cpp @@ -687,7 +687,6 @@ void Avp::decodeDataPart(const char * buffer, int size, const parent_t & parent, int avpPos = 0; Avp* avp; anna::DataBlock db; - // Me as parent: parent_t me = parent; me.addAvp(a_id); @@ -786,13 +785,12 @@ void Avp::decode(const anna::DataBlock &db, const parent_t & parent, Message *an // a Diameter client, server, proxy, or translation agent and either the AVP or its value is unrecognized, the message MUST be rejected. // Diameter Relay and redirect agents MUST NOT reject messages with unrecognized AVPs. if(!getStackAvp() && mandatoryBit()) { + if(answer) { + answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED); + answer->setFailedAvp(parent, a_id); + } - if(answer) { - answer->setResultCode(helpers::base::AVPVALUES__Result_Code::DIAMETER_AVP_UNSUPPORTED); - answer->setFailedAvp(parent, a_id); - } - - unknownAvpWithMandatoryBit(); + unknownAvpWithMandatoryBit(); } // Avp Length @@ -1318,9 +1316,8 @@ std::string Avp::getXMLdata(bool & isHex, const stack::Format *stackFormat) cons //---------------------------------------------------------------- Avp::decode() //------------------------------------------------------------------------------ void Avp::decode(const anna::DataBlock &db) throw(anna::RuntimeException) { - parent_t parent; - parent.setMessage(CommandId(0,false), "No-Parent"); + parent.setMessage(CommandId(0, false), "No-Parent"); decode(db, parent, NULL); }