From 8a1f47e88dcab70acec64b625142304e3a5047a2 Mon Sep 17 00:00:00 2001 From: Eduardo Ramos Testillano Date: Sun, 17 May 2015 15:55:23 +0200 Subject: [PATCH] Revert "Restruct launcher source code. Separate classes in different files to improve maintenance." This reverts commit 705d780f70b3596a222479ec7ad0dc3b3ab192cf. --- .settings/language.settings.xml | 25 - README.md | 2 +- example/diameter/launcher/Launcher.cpp | 0 example/diameter/launcher/Launcher.hpp | 0 example/diameter/launcher/MyCommunicator.cpp | 0 example/diameter/launcher/MyCommunicator.hpp | 0 .../diameter/launcher/MyCounterRecorder.cpp | 0 .../diameter/launcher/MyCounterRecorder.hpp | 0 .../launcher/MyCounterRecorderClock.hpp | 0 .../diameter/launcher/MyDiameterEngine.hpp | 0 .../diameter/launcher/MyDiameterEntity.cpp | 0 .../diameter/launcher/MyDiameterEntity.hpp | 0 example/diameter/launcher/MyHandler.cpp | 0 example/diameter/launcher/MyHandler.hpp | 0 example/diameter/launcher/MyLocalServer.cpp | 0 example/diameter/launcher/MyLocalServer.hpp | 0 .../diameter/launcher/ProgrammedAnswers.cpp | 0 .../diameter/launcher/ProgrammedAnswers.hpp | 0 .../deployments/ft-client/pre-start.sh | 2 +- example/diameter/launcher/main.cpp | 2722 +++++++++++++++++ include/anna/config/defines.hpp | 118 + include/anna/diameter.comm/Entity.hpp | 460 +++ 22 files changed, 3302 insertions(+), 27 deletions(-) delete mode 100644 .settings/language.settings.xml delete mode 100644 example/diameter/launcher/Launcher.cpp delete mode 100644 example/diameter/launcher/Launcher.hpp delete mode 100644 example/diameter/launcher/MyCommunicator.cpp delete mode 100644 example/diameter/launcher/MyCommunicator.hpp delete mode 100644 example/diameter/launcher/MyCounterRecorder.cpp delete mode 100644 example/diameter/launcher/MyCounterRecorder.hpp delete mode 100644 example/diameter/launcher/MyCounterRecorderClock.hpp delete mode 100644 example/diameter/launcher/MyDiameterEngine.hpp delete mode 100644 example/diameter/launcher/MyDiameterEntity.cpp delete mode 100644 example/diameter/launcher/MyDiameterEntity.hpp delete mode 100644 example/diameter/launcher/MyHandler.cpp delete mode 100644 example/diameter/launcher/MyHandler.hpp delete mode 100644 example/diameter/launcher/MyLocalServer.cpp delete mode 100644 example/diameter/launcher/MyLocalServer.hpp delete mode 100644 example/diameter/launcher/ProgrammedAnswers.cpp delete mode 100644 example/diameter/launcher/ProgrammedAnswers.hpp diff --git a/.settings/language.settings.xml b/.settings/language.settings.xml deleted file mode 100644 index f76d245..0000000 --- a/.settings/language.settings.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/README.md b/README.md index 4014f83..29e3fef 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ANNA is a complete suite of tools and resources to build proffesional applicatio Based on GIT, hosted on http://redmine.teslayout.com You could use my pre-commit specific template if you want to do some basic checkings (i.e. - astyle code processing): Execute './scr/git/use_pre-commit.sh' + astyle code processing): Execute './scr/git/use-pre-commit.sh' ## Documentation diff --git a/example/diameter/launcher/Launcher.cpp b/example/diameter/launcher/Launcher.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/Launcher.hpp b/example/diameter/launcher/Launcher.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyCommunicator.cpp b/example/diameter/launcher/MyCommunicator.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyCommunicator.hpp b/example/diameter/launcher/MyCommunicator.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyCounterRecorder.cpp b/example/diameter/launcher/MyCounterRecorder.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyCounterRecorder.hpp b/example/diameter/launcher/MyCounterRecorder.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyCounterRecorderClock.hpp b/example/diameter/launcher/MyCounterRecorderClock.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyDiameterEngine.hpp b/example/diameter/launcher/MyDiameterEngine.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyDiameterEntity.cpp b/example/diameter/launcher/MyDiameterEntity.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyDiameterEntity.hpp b/example/diameter/launcher/MyDiameterEntity.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyHandler.cpp b/example/diameter/launcher/MyHandler.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyHandler.hpp b/example/diameter/launcher/MyHandler.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyLocalServer.cpp b/example/diameter/launcher/MyLocalServer.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/MyLocalServer.hpp b/example/diameter/launcher/MyLocalServer.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/ProgrammedAnswers.cpp b/example/diameter/launcher/ProgrammedAnswers.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/ProgrammedAnswers.hpp b/example/diameter/launcher/ProgrammedAnswers.hpp deleted file mode 100644 index e69de29..0000000 diff --git a/example/diameter/launcher/deployments/ft-client/pre-start.sh b/example/diameter/launcher/deployments/ft-client/pre-start.sh index a01d1f0..b1863af 100755 --- a/example/diameter/launcher/deployments/ft-client/pre-start.sh +++ b/example/diameter/launcher/deployments/ft-client/pre-start.sh @@ -24,7 +24,7 @@ fi # DEFAULTS #[ "$entity_dflt" = "" ] && entity_dflt="192.168.12.11:3868,192.168.12.21:3868" [ "$entity_dflt" = "" ] && entity_dflt="localhost:3868" -[ "$entityServerSessions_dflt" = "" ] && entityServerSessions_dflt=1 +[ "$entityServerSessions_dflt" = "" ] && entityServerSessions_dflt=10 [ "$dictionary_dflt" = "" ] && dictionary_dflt=dictionary.xml diff --git a/example/diameter/launcher/main.cpp b/example/diameter/launcher/main.cpp index e69de29..dde2f7c 100644 --- a/example/diameter/launcher/main.cpp +++ b/example/diameter/launcher/main.cpp @@ -0,0 +1,2722 @@ +// ANNA - Anna is Not Nothingness Anymore // +// // +// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo // +// // +// See project site at http://redmine.teslayout.com/projects/anna-suite // +// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // + + +#include +#include +#include +#include // chmod +#include // open / write + +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace anna { +class DataBlock; +} + +namespace anna { +namespace diameter { +namespace comm { +class Entity; +class Response; +class LocalServer; +} +} +} + +#define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input" +#define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output" + + +// Auxiliary message for sendings +anna::diameter::comm::Message G_commMsgSent2c, G_commMsgSent2e, G_commMsgFwd2c, G_commMsgFwd2e; +anna::diameter::comm::Message G_commMsg; +anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg; +anna::Recycler G_commMessages; // create on requests forwards without programmed answer / release in answers forward + +// Auxiliary resources for answers programming +class ProgrammedAnswers { + +typedef std::deque codec_messages_deque; +typedef std::deque::iterator codec_messages_deque_iterator; +typedef std::deque::const_iterator codec_messages_deque_const_iterator; +typedef std::map < int /* message code */, codec_messages_deque* > reacting_answers_container; +typedef std::map < int /* message code */, codec_messages_deque* >::iterator reacting_answers_iterator; +typedef std::map < int /* message code */, codec_messages_deque* >::const_iterator reacting_answers_const_iterator; + + reacting_answers_container a_deques; + bool a_rotate; + + public: + ProgrammedAnswers() { a_rotate = false; } + ~ProgrammedAnswers() { clear(); } + + bool rotate() const throw() { return a_rotate; } + void rotate(bool r) throw() { a_rotate = r; } + + void clear () throw() { + for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + engine->releaseMessage(*(it->second->begin())); + delete(it->second); + } + a_deques.clear(); + } + + void dump () throw() { + std::string outfilename, xmlString; + for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + int sequence = 1; + for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { + // programmed_answer.. + outfilename = "programmed_answer."; + outfilename += anna::functions::asString(it->first); + outfilename += "."; + outfilename += anna::functions::asString(sequence++); + outfilename += ".xml"; + std::ofstream outfile(outfilename.c_str(), std::ifstream::out); + xmlString = (*itm)->asXMLString(); + outfile.write(xmlString.c_str(), xmlString.size()); + outfile.close(); + } + } + } + + void addMessage(int code, anna::diameter::codec::Message *message) throw() { + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + it->second->push_back(message); + } + else { + codec_messages_deque *deque = new codec_messages_deque; + a_deques[code] = deque; + deque->push_back(message); + } + } + + anna::diameter::codec::Message* getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty + anna::diameter::codec::Message *result = NULL; + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + if (!it->second->empty()) result = *(it->second->begin()); + } + return result; + } + + void nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty) + reacting_answers_const_iterator it = a_deques.find(code); + if (it != a_deques.end()) { + if (!it->second->empty()) { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + if (a_rotate) { + addMessage(code, *(it->second->begin())); + } + else { + engine->releaseMessage(*(it->second->begin())); + } + it->second->pop_front(); + } + } + } + + std::string asString(const char *queueName) const throw() { + std::string result = ""; + std::string aux = "FIFO QUEUE '"; + aux += queueName; + aux += "', Rotation "; + aux += a_rotate ? "enabled":"disabled"; + result += anna::functions::highlightJustify(aux); + if(a_deques.size() != 0) { + for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) { + if (it->second->size() != 0) { + aux = "Answer code "; + aux += anna::functions::asString(it->first); + result += anna::functions::highlightJustify(aux, anna::functions::TextHighlightMode::OverAndUnderline, + anna::functions::TextJustifyMode::Left, '-'); + for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) { + result += (*itm)->asXMLString(); + result += "\n"; + } + result += "\n"; + } + } + } + else { + result = "No ocurrences found\n\n"; + } + return result; + } +}; + +ProgrammedAnswers G_reactingAnswers2C, G_reactingAnswers2E; + + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// COUNTERS RECORD PROCEDURE ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +class MyCounterRecorderClock : public anna::timex::Clock { +public: + MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) : + anna::timex::Clock(clockName, timeout) {;} + //virtual ~MyCounterRecorderClock(); + + virtual bool tick() throw(RuntimeException) { + anna::diameter::comm::OamModule::instantiate().recordCounters(); + anna::diameter::codec::OamModule::instantiate().recordCounters(); + return true; + } +}; + +class MyCounterRecorder : public anna::oam::CounterRecorder { + + // attributes + int a_stream; + std::string a_fileNamePrefix; + std::string a_fileName; + time_t a_previousTime; + std::string a_fixedLine; + + // pure virtual definitions: + void open() throw(anna::RuntimeException) { + static char str [256]; + const time_t now = ::time(NULL); + struct tm tmNow; + struct tm tmPrevious; + anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow)); + anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious)); + sprintf( + str, ".Date%04d%02d%02d.Time%02d%02d%02d", + 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, + tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec); + a_fileName = a_fileNamePrefix; + a_fileName += str; + LOGDEBUG( + std::string msg("Flush counters | "); + msg += a_fileName; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1) + throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); + + sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d", + 1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1, + tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min, + 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1, + tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min + ); + a_fixedLine = str; + } + + + void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) { + static char line [356]; + anna::oam::Counter::type_t value = counter; + sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str()); + + if(write(a_stream, line, anna_strlen(line)) == -1) + throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION); + } + + void close() throw() { + if(a_stream != -1) { + ::close(a_stream); + a_stream = -1; + } + + chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR); + a_previousTime = ::time(NULL); + } + + std::string asString() const throw() { + std::string result = "Physical counters dump at file '"; + result += a_fileName; + result += "'. Another way to see counters: context dump (kill -10 "; + return result; + } + +public: + MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) { + a_previousTime = ::time(NULL); + } +}; + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + +class MyDiameterEntity : public anna::diameter::comm::Entity { + + void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); + void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventDPA(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException); + + // Reimplementation + int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw(); +}; + +class MyLocalServer : public anna::diameter::comm::LocalServer { + + void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException); + void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); + void eventDPA(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException); +}; + +class MyDiameterEngine : public anna::diameter::comm::Engine { +public: + + static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; } + MyDiameterEngine() {;} + +// Default implementation is enough +// void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied +// void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied +// void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied + +private: + anna::Recycler a_entitiesRecycler; + + anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); } + + void releaseEntity(anna::diameter::comm::Entity* entity) throw() { + MyDiameterEntity* aux = static_cast (entity); + a_entitiesRecycler.release(aux); + } + + anna::Recycler a_localServersRecycler; + + anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); } + + void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() { + MyLocalServer* aux = static_cast (localServer); + a_localServersRecycler.release(aux); + } +}; + + +class MyHandler : public anna::http::Handler { +public: + MyHandler() : anna::http::Handler("http_converter::MyHandler") { + allocateResponse()->createHeader(anna::http::Header::Type::Date); + } + +private: + + void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException); + void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;} +}; + +class MyCommunicator : public anna::comm::Communicator { +public: + MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode), + a_contexts("Contexts") + {;} + + void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw(); + void terminate() throw(); + +private: + anna::ThreadData a_contexts; + void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException); + void eventBreakConnection(Server* server) throw(); +}; + +class Launcher : public anna::comm::Application { + + MyCommunicator *a_communicator; + MyDiameterEngine *a_myDiameterEngine; + anna::diameter::comm::Entity *a_entity; + std::string a_logFile, a_burstLogFile; + std::ofstream a_burstLogStream; + bool a_splitLog, a_detailedLog, a_dumpLog; + anna::time::Date a_start_time; + anna::timex::Engine* a_timeEngine; + MyCounterRecorder *a_counterRecorder; + MyCounterRecorderClock *a_counterRecorderClock; + std::string a_cerPathfile; + std::string a_dwrPathfile; + + // Burst feature + int a_burstCycle; + bool a_burstRepeat; + bool a_burstActive; + std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages; + int a_burstLoadIndx; + std::map::const_iterator a_burstDeliveryIt; + int a_otaRequest; + int a_burstPopCounter; + + anna::comm::ServerSocket* a_httpServerSocket; // HTTP + anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER + void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException); + void initialize() throw(anna::RuntimeException); // HTTP + void run() throw(anna::RuntimeException); + +public: + Launcher(); + + MyCommunicator *getCommunicator() throw() { return a_communicator; } + MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); } + void baseProtocolSetupAsClient(void) throw(anna::RuntimeException); + anna::diameter::comm::Entity *getEntity() throw() { return a_entity; } + anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; } + void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException); + bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); } + void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw(); + void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw(); + void writeBurstLogFile(const std::string &buffer) throw(); + bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); } + void startDiameterServer(int) throw(anna::RuntimeException); + void forceCountersRecord() throw(anna::RuntimeException) { if (a_counterRecorderClock) a_counterRecorderClock->tick(); } + + anna::xml::Node* asXML(anna::xml::Node* parent) const throw(); + void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); } + void resetCounters() throw(); + void signalUSR2() throw(anna::RuntimeException); + std::string help() const throw(); + + // helpers + bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw(); + + // Burst feature + int clearBurst() throw(); // returns removed + int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException); + void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; } + int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative) + int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative) + int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative) + int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped + int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped + bool burstActive() const throw() { return a_burstActive; } + bool sendBurstMessage(bool anyway = false) throw(); + std::string lookBurst(int order) const throw(); + std::string gotoBurst(int order) throw(); +}; + +bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() { + // Get hex string + static char buffer[8192]; + std::ifstream infile(pathfile.c_str(), std::ifstream::in); + + if(infile.is_open()) { + infile >> buffer; + std::string hexString(buffer, strlen(buffer)); + // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString': + hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end()); + LOGDEBUG( + std::string msg = "Hex string (remove colons if exists): "; + msg += hexString; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + anna::functions::fromHexString(hexString, db); + // Close file + infile.close(); + return true; + } + + return false; +} + +int Launcher::clearBurst() throw() { + int size = a_burstMessages.size(); + + if(size) { + std::map::const_iterator it; + std::map::const_iterator it_min(a_burstMessages.begin()); + std::map::const_iterator it_max(a_burstMessages.end()); + + for(it = it_min; it != it_max; it++) G_commMessages.release((*it).second); + + a_burstMessages.clear(); + } else { + std::string msg = "Burst list already empty. Nothing done"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + } + + a_burstActive = false; + a_burstLoadIndx = 0; + a_burstDeliveryIt = a_burstMessages.begin(); + return size; +} + + +int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) { + anna::diameter::comm::Message *msg = G_commMessages.create(); + msg->setBody(db); + a_burstMessages[a_burstLoadIndx++] = msg; + return (a_burstLoadIndx - 1); +} + +int Launcher::stopBurst() throw() { + if(!a_burstActive) { + std::string msg = "Burst launch is already stopped. Nothing done"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -1; + } + + a_burstActive = false; + // Remaining on cycle: + return (a_burstMessages.size() - (*a_burstDeliveryIt).first); +} + +int Launcher::popBurst(int releaseAmount) throw() { + if(!a_burstActive) { + std::string msg = "Burst launch is stopped. Nothing done"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -1; + } + + if(releaseAmount < 1) { + std::string msg = "No valid release amount is specified. Ignoring burst pop"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -2; + } + + int currentOTArequests = a_entity->getOTARequests(); + a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount; + return a_burstPopCounter; +} + +int Launcher::pushBurst(int loadAmount) throw() { + if(a_burstMessages.size() == 0) { + std::string msg = "Burst data not found (empty list). Ignoring burst launch"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -1; + } + + if(loadAmount < 1) { + std::string msg = "No valid load amount is specified. Ignoring burst push"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -2; + } + + a_burstActive = true; + int count; + + for(count = 0; count < loadAmount; count++) + if(!sendBurstMessage()) break; + + return count; +} + + +int Launcher::sendBurst(int loadAmount) throw() { + if(a_burstMessages.size() == 0) { + std::string msg = "Burst data not found (empty list). Ignoring burst launch"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -1; + } + + if(loadAmount < 1) { + std::string msg = "No valid load amount is specified. Ignoring burst send"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -2; + } + + int count; + + for(count = 0; count < loadAmount; count++) + if(!sendBurstMessage(true /* anyway */)) break; + + return count; +} + + + +int Launcher::startBurst(int initialLoad) throw() { + if(initialLoad < 1) { + std::string msg = "No initial load is specified. Ignoring burst start"; + std::cout << msg << std::endl; + LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION)); + return -2; + } + + a_burstActive = true; + a_burstCycle = 1; + a_burstDeliveryIt = a_burstMessages.begin(); + return (pushBurst(initialLoad)); +} + +bool Launcher::sendBurstMessage(bool anyway) throw() { + if(!anyway && !burstActive()) return false; + + if(a_burstPopCounter > 0) { + if(burstLogEnabled()) writeBurstLogFile("x"); + + a_burstPopCounter--; + return false; + } + + if(a_burstDeliveryIt == a_burstMessages.end()) { + a_burstDeliveryIt = a_burstMessages.begin(); + + if(!anyway) { + if(a_burstRepeat) { + a_burstCycle++; + + if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle)); + } else { + if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n"); + + stopBurst(); + return false; + } + } + } + + anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second; + int order = (*a_burstDeliveryIt).first + 1; + a_burstDeliveryIt++; + bool dot = true; + // sending + bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance")); + + if(burstLogEnabled()) { + if(a_burstMessages.size() >= 100) + dot = (order % (a_burstMessages.size() / 100)); + + if(dot) { + writeBurstLogFile("."); + } else { + writeBurstLogFile(anna::functions::asString(" %d", order)); + int otaReqs = a_entity->getOTARequests(); + + if(result && (otaReqs != a_otaRequest)) { + // false if was a sending after an answer received (no OTA change in this case) + // true after push and pop operations + a_otaRequest = otaReqs; + writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest)); + } + } + } + + // Detailed log: + if(logEnabled()) { + anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource(); + anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL; + std::string detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir + writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail); + } + + return result; +} + + +std::string Launcher::lookBurst(int order) const throw() { + std::string result = "No message found for order provided ("; + result += anna::functions::asString(order); + result += ")"; + std::map::const_iterator it = a_burstMessages.find(order - 1); + + if(it != a_burstMessages.end()) { + // Decode + try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); } + + result = G_codecMsg.asXMLString(); + } + + return result; +} + +std::string Launcher::gotoBurst(int order) throw() { + std::string result = "Position not found for order provided ("; + std::map::iterator it = a_burstMessages.find(order - 1); + + if(it != a_burstMessages.end()) { + a_burstDeliveryIt = it; + result = "Position updated for order provided ("; + } + + result += anna::functions::asString(order); + result += ")"; + return result; +} + +//////////////////////////////////////////////////// + + +void Launcher::resetCounters() throw() { + // Diameter::comm module: + anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate(); + oamDiameterComm.resetCounters(); +} + +void Launcher::signalUSR2() throw(anna::RuntimeException) { + LOGNOTICE( + std::string msg = "Captured signal SIGUSR2. Reading tasks at '"; + msg += SIGUSR2_TASKS_INPUT_FILENAME; + msg += "' (results will be written at '"; + msg += SIGUSR2_TASKS_OUTPUT_FILENAME; + msg += "')"; + anna::Logger::notice(msg, ANNA_FILE_LOCATION); + ); + // Operation: + std::string line; + std::string response_content; + std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME); + std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME); + + if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION); + + if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION); + + while(getline(in_file, line)) { + LOGDEBUG( + std::string msg = "Processing line: "; + msg += line; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + try { + eventOperation(line, response_content); + } catch(RuntimeException &ex) { + ex.trace(); + } + + out_file << response_content; + } + + in_file.close(); + out_file.close(); +} + + +std::string Launcher::help() const throw() { + std::string result = "\n"; + result += "\n ------------- HELP -------------\n"; + result += "\n"; + result += "\nOVERVIEW"; + result += "\n--------"; + result += "\n"; + result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server"; + result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server"; + result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),"; + result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary"; + result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and"; + result += "\n send it to another process."; + result += "\n"; + result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections"; + result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard"; + result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA"; + result += "\n generation, expiration control and many more features."; + result += "\n"; + result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually"; + result += "\n 'debug' or 'warning'. See ANNA documentation for more details."; + result += "\n"; + result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:"; + result += "\n kill -10 "; + result += "\n or"; + result += "\n kill -s SIGUSR1 "; + result += "\n and then"; + result += "\n vi /var/tmp/anna.context."; + result += "\n"; + result += "\nA complete xml report will show all the context information (counters, alarms, statistics,"; + result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events"; + result += "\n processed and flow information. Statistics could be analized at context dump and optionally"; + result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the"; + result += "\n measurements."; + result += "\n"; + result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this."; + result += "\n"; + result += "\n"; + result += "\nCOMMAND LINE"; + result += "\n------------"; + result += "\n"; + result += "\nStart the launcher process without arguments in order to see all the startup configuration"; + result += "\n posibilities, many of which could be modified on the air through the management interface"; + result += "\n (we will talk later about this great feature). Some of the more common parameters are:"; + result += "\n"; + result += "\nAs mandatory, the stack definition given through the xml dictionary:"; + result += "\n -dictionary "; + result += "\n"; + result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:"; + result += "\n -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0"; + result += "\n"; + result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:"; + result += "\n -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0"; + result += "\n"; + result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably"; + result += "\n will need to program the answers to be replied through the operations interface. To balance the"; + result += "\n traffic at your client side you shall use '-balance' and '-sessionBasedModelsClientSocketSelection'"; + result += "\n arguments in order to define the balancing behaviour."; + result += "\n"; + result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own"; + result += "\n customized ones using '-cer ' and '-dwr '."; + result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own"; + result += "\n customized ones using operations interface."; + result += "\n"; + result += "\n"; + result += "\nDYNAMIC OPERATIONS"; + result += "\n------------------"; + result += "\n"; + result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh."; + result += "\nAn operation is specified by mean a string containing the operation name and needed arguments"; + result += "\n separated by pipes. These are the available commands:"; + result += "\n"; + result += "\n--------------------------------------------------------------------------------------- General purpose"; + result += "\n"; + result += "\nhelp This help. Startup information-level traces also dump this help."; + result += "\n"; + result += "\n------------------------------------------------------------------------------------ Parsing operations"; + result += "\n"; + result += "\ncode|| Encodes source file (pathfile) into target file (pathfile)."; + result += "\ndecode|| Decodes source file (pathfile) into target file (pathfile)."; + result += "\nloadxml| Reinterpret xml source file (pathfile)."; + result += "\n"; + result += "\n------------------------------------------------------------------------------------------- Hot changes"; + result += "\n"; + result += "\ndiameterServerSessions| Updates the maximum number of accepted connections to diameter"; + result += "\n server socket."; + result += "\ncollect Reset statistics and counters to start a new test stage of"; + result += "\n performance measurement. Context data is written at"; + result += "\n '/var/tmp/anna.context.' by mean 'kill -10 '."; + result += "\nforceCountersRecord Forces dump to file the current counters of the process."; + result += "\n"; + result += "\n|[
:]|[socket id]"; + result += "\n"; + result += "\n Actions: hide, show (update state) and hidden, shown (query state)."; + result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A)."; + result += "\n If missing server (first parameter) all applications sockets will be affected."; + result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected."; + result += "\n"; + result += "\n All application client sessions are shown on startup, but standard delivery only use primary"; + result += "\n server ones except if fails. Balance configuration use all the allowed sockets. You could also"; + result += "\n use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain"; + result += "\n client sessions, but for this, hide/show feature seems easier."; + result += "\n"; + result += "\n--------------------------------------------------------------------------------------- Flow operations"; + result += "\n"; + result += "\nsendxml2e| Sends xml source file (pathfile) through configured entity."; + result += "\nsendxml2c| Sends xml source file (pathfile) to client."; + result += "\nsendxml| Same as 'sendxml2e'."; + result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for incoming request with same code from entity."; + result += "\n The answer is stored in a FIFO queue for a specific message code, then there are"; + result += "\n as many queues as different message codes have been programmed."; + result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for incoming request with same code from client."; + result += "\n The answer is stored in a FIFO queue for a specific message code, then there are"; + result += "\n as many queues as different message codes have been programmed."; + result += "\nanswerxml|[source_file] Same as 'answerxml2c'."; + result += "\nanswerxml(2e/2c) List programmed answers (to entity/client) if no parameter provided."; + result += "\nanswerxml(2e/2c)|dump Write programmed answers (to entity/client) to file 'programmed_answer..',"; + result += "\n where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers."; + result += "\nanswerxml(2e/2c)|clear Clear programmed answers (to entity/client)."; + result += "\nanswerxml(2e/2c)|exhaust Disable the corresponding queue rotation, which is the default behaviour."; + result += "\nanswerxml(2e/2c)|rotate Enable the corresponding queue rotation, useful in performance tests."; + result += "\n Rotation consists in add again to the queue, each element retrieved for answering."; + result += "\n"; + result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test"; + result += "\nspecial scenarios (protocol errors):"; + result += "\n"; + result += "\nsendhex2e| Sends hex source file (pathfile) through configured entity."; + result += "\nsendhex2c| Sends hex source file (pathfile) to client."; + result += "\nsendhex| Same as 'sendhex2e'."; + result += "\n"; + result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also"; + result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,"; + result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created."; + result += "\n"; + result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be"; + result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,"; + result += "\n or answer message was received, the message is forwarded to the other side (entity or client),"; + result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when"; + result += "\n diameter server socket is configured, answer to entity have sense when entity does."; + result += "\n"; + result += "\nIn the most complete situation (process with both client and server side) there are internally"; + result += "\n two maps with N FIFO queues, one for each different message code within programmed answers."; + result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in"; + result += "\n each one we could program different answers corresponding to different request codes received."; + result += "\n"; + result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored"; + result += "\n to the peer which sent the request. If user wants to test a specific answer without changing it,"; + result += "\n use sendxml/sendhex operations better than programming."; + result += "\n"; + result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through"; + result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should"; + result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an"; + result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc."; + result += "\n"; + result += "\n--------------------------------------------------------------------------- Processing types (log tags)"; + result += "\n"; + result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log"; + result += "\n details when unique log file is dumped:"; + result += "\n"; + result += "\n [sent2e/send2eError] Send to entity (success/error)"; + result += "\n [sent2c/send2cError] Send to client (success/error)"; + result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)"; + result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)"; + result += "\n [recvfc] Reception from client"; + result += "\n [recvfe] Reception from entity"; + result += "\n [req2c-expired] A request sent to client has been expired"; + result += "\n [req2e-expired] A request sent to entity has been expired"; + result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired]"; + result += "\n has been logged)"; + result += "\n [recvfe-ans-unknown] Reception from entity of an unknown answer (probably former [req2e-expired]"; + result += "\n has been logged)"; + result += "\n"; + result += "\n-------------------------------------------------------------------------------------------- Load tests"; + result += "\n"; + result += "\nburst||[parameter] Used for performance testing, we first program diameter requests"; + result += "\n messages in order to launch them from client side to the configured"; + result += "\n diameter entity. We could start the burst with an initial load"; + result += "\n (non-asynchronous sending), after this, a new request will be sent"; + result += "\n per answer received or expired context. There are 10 actions: clear,"; + result += "\n load, start, push, pop, stop, repeat, send, goto and look."; + result += "\n"; + result += "\n burst|clear Clears all loaded burst messages."; + result += "\n burst|load| Loads the next diameter message into launcher burst."; + result += "\n burst|start| Starts (or restarts if already in progress) the message sending with"; + result += "\n a certain initial load."; + result += "\n burst|push| Sends specific non-aynchronous load."; + result += "\n burst|pop| Skip send burst messages in order to reduce over-the-air requests."; + result += "\n Popping all OTA requests implies burst stop because no more answer"; + result += "\n will arrive to the process. Burst output file (-burstLog command"; + result += "\n line parameter) shows popped messages with crosses (x). Each cross"; + result += "\n represents one received answer for which no new request is sent."; + result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount."; + result += "\n burst|repeat|[[yes]|no] Restarts the burst launch when finish. If initial load or push load"; + result += "\n amount is greater than burst list size, they will be limited when"; + result += "\n the list is processed except when repeat mode is enabled."; + result += "\n burst|send| Sends messages from burst list. The main difference with start/push"; + result += "\n operations is that burst won't be awaken. Externally we could control"; + result += "\n sending time (no request will be sent for answers)."; + result += "\n burst|goto| Updates current burst pointer position."; + result += "\n burst|look| Show programmed burst message for order provided."; + result += "\n"; + result += "\n"; + result += "\nUSING OPERATIONS INTERFACE"; + result += "\n--------------------------"; + result += "\n"; + result += "\n------------------------------------------------------------------------- Operations via HTTP interface"; + result += "\n"; + result += "\nAll the operations described above can be used through the optional HTTP interface. You only have"; + result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'."; + result += "\nTo send the task, we shall build the http request body with the operation string. Some examples"; + result += "\n using curl client could be:"; + result += "\n"; + result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000"; + result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000"; + result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000"; + result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000"; + result += "\n etc."; + result += "\n"; + result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal"; + result += "\n"; + result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at"; + result += "\n signal event:"; + result += "\n echo \"<\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME; + result += "\n then"; + result += "\n kill -12 "; + result += "\n or"; + result += "\n kill -s SIGUSR2 "; + result += "\n and then see the results:"; + result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME; + result += "\n"; + result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that"; + result += "\n case over the output file. Take into account that all the content of the task file will be executed"; + result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http"; + result += "\n interface."; + result += "\n"; + result += "\n"; + return result; +} + + +void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() { + // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request. + // If user wants to test a specific answer without changing it, use send operations better than programming. + // Sequence substitution: + answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request)); + answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request)); + + // Session-Id substitution: + try { + std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request); + LOGDEBUG( + std::string msg = "Extracted Session-Id: "; + msg += sessionId; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId); + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + + // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information, + // then it will be adapted with the received data at request. + if(answer->countAvp("Subscription-Id") > 0) { + std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); + std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); + + if((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information: + answer->removeAvp("Subscription-Id", 0 /* remove all */); + } + + // Replacements: + if(msisdn != "") { + anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); + sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164); + sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn); + } + + if(imsi != "") { + anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another + sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI); + sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi); + } + } +} + +// HTTP +void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION)); + + if(clientSocket.support(anna::http::Transport::className()) == false) + return; + + 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.trace", 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("dumpLog", anna::CommandLine::Argument::Optional, "Write to disk every incoming/outcoming message named as '.....xml'", 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("fixMode", anna::CommandLine::Argument::Optional, "Sets message fix mode (unreconized values will assume default 'BeforeEncoding'). Allowed: 'BeforeEncoding', 'AfterDecoding', 'Always', 'Never'"); + + 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_dumpLog = false; + a_timeEngine = NULL; + a_counterRecorder = NULL; + a_counterRecorderClock = NULL; + a_entity = NULL; + a_diameterLocalServer = NULL; + a_cerPathfile = "cer.xml"; + a_dwrPathfile = "dwr.xml"; + // Burst + a_burstCycle = 1; + a_burstRepeat = false; + a_burstActive = false; + //a_burstMessages.clear(); + a_burstLoadIndx = 0; + a_burstDeliveryIt = a_burstMessages.begin(); + a_otaRequest = 0; + a_burstPopCounter = 0; +} + +void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) { + // Build CER + // ::= < Diameter Header: 257, REQ > + // { Origin-Host } 264 diameterIdentity + // { Origin-Realm } 296 idem + // 1* { Host-IP-Address } 257, address + // { Vendor-Id } 266 Unsigned32 + // { Product-Name } 269 UTF8String + // [Origin-State-Id] 278 Unsigned32 + // * [ Supported-Vendor-Id ] 265 Unsigned32 + // * [ Auth-Application-Id ] 258 Unsigned32 + // * [Acct-Application-Id] 259 Unsigned32 + anna::diameter::codec::Message diameterCER; + int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32 + std::string OH = a_myDiameterEngine->getHost(); + std::string OR = a_myDiameterEngine->getRealm(); + std::string hostIP = anna::functions::getHostnameIP(); // Address + int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32 + std::string productName = "ANNA Diameter Launcher"; // UTF8String + bool loadingError = false; + + try { + diameterCER.loadXML(a_cerPathfile); + } catch(anna::RuntimeException &ex) { + //ex.trace(); + loadingError = true; + } + + if(loadingError) { + LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION)); + diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request); + diameterCER.setApplicationId(applicationId); + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|" + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId); + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName); + diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId); + } + + // Build DWR + // ::= < Diameter Header: 280, REQ > + // { Origin-Host } + // { Origin-Realm } + anna::diameter::codec::Message diameterDWR; + loadingError = false; + + try { + diameterDWR.loadXML(a_dwrPathfile); + } catch(anna::RuntimeException &ex) { + //ex.trace(); + loadingError = true; + } + + if(loadingError) { + LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION)); + diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request); + diameterDWR.setApplicationId(applicationId); + diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); + diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); + } + +////////////////////////// +// IDEM FOR CEA AND DWA // +////////////////////////// +// // Build CER +// // ::= < Diameter Header: 257, REQ > +// // { Origin-Host } 264 diameterIdentity +// // { Origin-Realm } 296 idem +// // 1* { Host-IP-Address } 257, address +// // { Vendor-Id } 266 Unsigned32 +// // { Product-Name } 269 UTF8String +// // [Origin-State-Id] 278 Unsigned32 +// // * [ Supported-Vendor-Id ] 265 Unsigned32 +// // * [ Auth-Application-Id ] 258 Unsigned32 +// // * [Acct-Application-Id] 259 Unsigned32 +// anna::diameter::codec::Message diameterCER; +// int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32 +// std::string OH = a_myDiameterEngine->getHost(); +// std::string OR = a_myDiameterEngine->getRealm(); +// std::string hostIP = anna::functions::getHostnameIP(); // Address +// int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32 +// std::string productName = "ANNA Diameter Launcher"; // UTF8String +// bool loadingError = false; +// +// try { +// diameterCER.loadXML("cer.xml"); +// } catch (anna::RuntimeException &ex) { +// ex.trace(); +// loadingError = true; +// } +// +// if (loadingError) { +// LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION)); +// diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request); +// diameterCER.setApplicationId(applicationId); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|" +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName); +// diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId); +// } +// +// // Build DWR +// // ::= < Diameter Header: 280, REQ > +// // { Origin-Host } +// // { Origin-Realm } +// anna::diameter::codec::Message diameterDWR; +// loadingError = false; +// +// try { +// diameterDWR.loadXML("dwr.xml"); +// } catch (anna::RuntimeException &ex) { +// ex.trace(); +// loadingError = true; +// } +// +// if (loadingError) { +// LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION)); +// diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request); +// diameterDWR.setApplicationId(applicationId); +// diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH); +// diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR); +// } + // Assignment for CER/DWR and CEA/DWA: + a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code()); + //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code()); +} + +void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() { +// if (!logEnabled()) return; + + // Decode + try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); } + + writeLogFile(G_codecMsg, logExtension, detail); +} + + +// Si ya lo tengo decodificado: +void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() { +// if (!logEnabled()) return; + // Open target file: + std::string targetFile = a_logFile; + + if(a_splitLog) { + targetFile += "."; + targetFile += logExtension; + } + + ofstream out(targetFile.c_str(), ifstream::out | ifstream::app); + // Set text to dump: + std::string title = "["; + title += logExtension; + title += "]"; + // Build complete log: + std::string log = "\n"; + std::string xml = decodedMessage.asXMLString(); + + + if(a_detailedLog) { + anna::time::Date now; + now.setNow(); + title += " "; + title += now.asString(); + log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline); + log += xml; + log += "\n"; + log += anna::functions::highlight("Used resource"); + log += detail; + log += "\n"; + } else { + log += title; + log += "\n"; + log += xml; + log += "\n"; + } + + if(a_dumpLog) { + std::string name = anna::functions::asString(decodedMessage.getHopByHop()); + name += "."; + name += anna::functions::asString(decodedMessage.getEndToEnd()); + name += "."; + name += anna::functions::asString(decodedMessage.getId().first); + name += "."; + name += ((decodedMessage.getId().second) ? "request.":"answer."); + name += logExtension; + name += ".xml"; + ofstream outMsg(name.c_str(), ifstream::out | ifstream::app); + outMsg.write(xml.c_str(), xml.size()); + outMsg.close(); + } + + // Write and close + out.write(log.c_str(), log.size()); + out.close(); +} + + +void Launcher::writeBurstLogFile(const std::string &buffer) throw() { + ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app); + out.write(buffer.c_str(), buffer.size()); + out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope). + // you'd call close() only if you indeed for some reason wanted to close the filestream + // earlier than it goes out of scope. +} + + +void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) { + CommandLine& cl(anna::CommandLine::instantiate()); + + if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory + + std::string parameter = cl.getValue(commandLineParameter); + + if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$ + int msecs = cl.getIntegerValue(commandLineParameter); + + if(msecs > a_timeEngine->getMaxTimeout()) { + std::string msg = "Commandline parameter '"; + msg += commandLineParameter; + msg += "' is greater than allowed max timeout for timming engine: "; + msg += anna::functions::asString(a_timeEngine->getMaxTimeout()); + throw RuntimeException(msg, ANNA_FILE_LOCATION); + } + + if(msecs <= a_timeEngine->getResolution()) { + std::string msg = "Commandline parameter '"; + msg += commandLineParameter; + msg += "' (and in general, all time measures) must be greater than timming engine resolution: "; + msg += anna::functions::asString(a_timeEngine->getResolution()); + throw RuntimeException(msg, ANNA_FILE_LOCATION); + } + + return; // ok + } + + // Excepcion (por no ser entero): + std::string msg = "Error at commandline parameter '"; + msg += commandLineParameter; + msg += "' = '"; + msg += parameter; + msg += "': must be a non-negative integer number"; + throw RuntimeException(msg, ANNA_FILE_LOCATION); +} + + +void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) { + if(diameterServerSessions <= 0) return; + + std::string address; + int port; + CommandLine& cl(anna::CommandLine::instantiate()); + anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port); + //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "") + a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions); + a_diameterLocalServer->setDescription("Launcher diameter local server"); + int allowedInactivityTime = 90000; // ms + + if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime"); + + a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime); +} + + +void Launcher::initialize() +throw(anna::RuntimeException) { + anna::comm::Application::initialize(); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single); +// if (cl.exists ("clone")) +// workMode = anna::comm::Communicator::WorkMode::Clone; + a_communicator = new MyCommunicator(workMode); + a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150); + // Counters record procedure: + anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms + + if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod"); + + if(cntRecordPeriod != 0) { + checkTimeMeasure("cntRecordPeriod"); + a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock + std::string cntDir = "."; + + if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir"); + + a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid())); + } +} + +void Launcher::run() +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION)); + CommandLine& cl(anna::CommandLine::instantiate()); + // Start time: + a_start_time.setNow(); + // Statistics: + anna::statistics::Engine::instantiate().enable(); + /////////////////////////////// + // Diameter library COUNTERS // + /////////////////////////////// + anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate(); + oamDiameterComm.initializeCounterScope(1); // 1000 - 1999 + anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate(); + oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999 + ///////////////// + // COMM MODULE // + ///////////////// + /* Main events */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17); + /* Diameter Base (capabilities exchange & keep alive) */ + // as client + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26); + // as server + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35); + /* server socket operations (enable/disable listening port for any local server) */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37); + /* Connectivity */ + // clients + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46); + // servers + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 58); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 59); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 60); + ////////////////// + // CODEC MODULE // + ////////////////// + /* Avp decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/); + /* Message decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/); + /* Avp validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/); + /* Message validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/); + /* Level validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/); + + ///////////////////////////////// + // Counter recorder associated // + ///////////////////////////////// + if(a_counterRecorderClock) { + oamDiameterComm.setCounterRecorder(a_counterRecorder); + oamDiameterCodec.setCounterRecorder(a_counterRecorder); + a_timeEngine->activate(a_counterRecorderClock); // start clock + } + + // Checking command line parameters + if(cl.exists("sessionBasedModelsClientSocketSelection")) { + std::string type = cl.getValue("sessionBasedModelsClientSocketSelection"); + + if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) { + throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION); + } + } + + // Tracing: + if(cl.exists("trace")) + anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace"))); + + LOGINFORMATION( + // Help on startup traces: + anna::Logger::information(help(), ANNA_FILE_LOCATION); + // Test messages dtd: + std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n"; + msg += anna::diameter::codec::MessageDTD; + anna::Logger::information(msg, ANNA_FILE_LOCATION); + ); + + // HTTP Server: + if(cl.exists("httpServer")) { + anna::comm::Network& network = anna::comm::Network::instantiate(); + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port); + //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP + const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve + a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory()); + } + + // Stack: + anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine(); + anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate(); + anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */); + // Analyze comma-separated list: + anna::Tokenizer lst; + std::string dictionaryParameter = cl.getValue("dictionary"); + lst.apply(dictionaryParameter, ","); + + if(lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory) + anna::Tokenizer::const_iterator tok_min(lst.begin()); + anna::Tokenizer::const_iterator tok_max(lst.end()); + anna::Tokenizer::const_iterator tok_iter; + std::string pathFile; + d->allowUpdates(); + + for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) { + pathFile = anna::Tokenizer::data(tok_iter); + d->load(pathFile); + } + } + + codecEngine->setDictionary(d); + LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION)); + + if(lst.size() > 1) { + std::string all_in_one = "./dictionary-all-in-one.xml"; + std::ofstream out(all_in_one.c_str(), std::ifstream::out); + std::string buffer = d->asXMLString(); + out.write(buffer.c_str(), buffer.size()); + out.close(); + std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl; + } + + + + // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always'). + // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError': + if(cl.exists("integrationAndDebugging")) { + codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); + codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete); + } + + // Fix mode + if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never + std::string fixMode = cl.getValue("fixMode"); + anna::diameter::codec::Engine::FixMode::_v fm; + if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding; + else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding; + else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always; + else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never; + else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION)); + codecEngine->setFixMode(fm); + } + + codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); + + // Diameter Server: + if(cl.exists("diameterServer")) + startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1); + + // Optional command line parameters //////////////////////////////////////////////////////// + checkTimeMeasure("allowedInactivityTime"); + checkTimeMeasure("tcpConnectDelay"); + checkTimeMeasure("answersTimeout"); + checkTimeMeasure("ceaTimeout"); + checkTimeMeasure("watchdogPeriod"); + checkTimeMeasure("reconnectionPeriod"); + int tcpConnectDelay = 200; // ms + anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms + anna::Millisecond ceaTimeout; + anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms + int reconnectionPeriod = 10000; // ms + + if(cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay"); + + if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout"); + + if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout"); + else ceaTimeout = answersTimeout; + + if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod"); + + if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod"); + + a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay); + a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod); + std::string originHost = ""; + std::string originRealm = ""; + + if(cl.exists("cer")) a_cerPathfile = cl.getValue("cer"); + + if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr"); + + if(cl.exists("originHost")) originHost = cl.getValue("originHost"); + + if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm"); + + a_myDiameterEngine->setHost(originHost); + a_myDiameterEngine->setRealm(originRealm); + + // Diameter entity: + if(cl.exists("entity")) { + int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1; + + if(entityServerSessions > 0) { + baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers + anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity")); + a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions); + a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"); + a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout); + a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout); + a_entity->bind(); + } + } + + // Logs + if(cl.exists("log")) a_logFile = cl.getValue("log"); + + if(cl.exists("splitLog")) a_splitLog = true; + + if(cl.exists("detailedLog")) a_detailedLog = true; + + if(cl.exists("dumpLog")) a_dumpLog = true; + + if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog"); + + // Log statistics concepts + if(cl.exists("logStatisticSamples")) { + std::string list = cl.getValue("logStatisticSamples"); + anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate(); + + if(list == "all") { + if(statEngine.enableSampleLog(/* -1: all concepts */)) + LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION)); + } else { + anna::Tokenizer lst; + lst.apply(cl.getValue("logStatisticSamples"), ","); + + if(lst.size() >= 1) { + anna::Tokenizer::const_iterator tok_min(lst.begin()); + anna::Tokenizer::const_iterator tok_max(lst.end()); + anna::Tokenizer::const_iterator tok_iter; + int conceptId; + + for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) { + conceptId = atoi(anna::Tokenizer::data(tok_iter)); + + if(statEngine.enableSampleLog(conceptId)) + LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION)); + } + } + } + } + + a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod); + + if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP + + a_communicator->accept(); +} + +void MyCommunicator::eventBreakConnection(Server* server) +throw() { + LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION)); + terminate(); + anna::comm::Communicator::eventBreakConnection(server); +} + +void MyCommunicator::terminate() +throw() { + if(hasRequestedStop() == true) + return; + + requestStop(); +} + +void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request) +throw(anna::RuntimeException) { + const anna::DataBlock& body = request.getBody(); + + if(body.getSize() == 0) + throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION); + + LOGINFORMATION( + string msg("Received body: "); + msg += anna::functions::asString(body); + anna::Logger::information(msg, ANNA_FILE_LOCATION); + ); + std::string body_content; + body_content.assign(body.getData(), body.getSize()); + // Operation: + std::string response_content; + + try { + Launcher& my_app = static_cast (anna::app::functions::getApp()); + my_app.eventOperation(body_content, response_content); + } catch(RuntimeException &ex) { + ex.trace(); + } + + anna::http::Response* response = allocateResponse(); + response->setStatusCode(200); // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes + anna::DataBlock db_content(true); + db_content = response_content; + response->setBody(db_content); +// response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT"); +// anna::http::Header* keepAlive = response->find("Keep-Alive"); +// +// if (keepAlive == NULL) +// keepAlive = response->createHeader("Keep-Alive"); +// +// keepAlive->setValue("Verificacion del cambio 1.0.7"); + + try { + clientSocket.send(*response); + } catch(Exception& ex) { + ex.trace(); + } +} + +void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION)); + CommandLine& cl(anna::CommandLine::instantiate()); + LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION)); + response_content = "Operation processed with exception. See traces\n"; // supposed + std::string result = ""; + anna::DataBlock db_aux(true); + + /////////////////////////////////////////////////////////////////// + // Simple operations without arguments: + + // Help: + if(operation == "help") { + std::string s_help = help(); + std::cout << s_help << std::endl; + LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION)); + response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n"; + return; + } + + // Reset performance data: + if(operation == "collect") { + resetCounters(); + resetStatistics(); + response_content = "All process counters & statistic information have been reset\n"; + return; + } + + // Counters dump on demand: + if(operation == "forceCountersRecord") { + forceCountersRecord(); + response_content = "Current counters have been dump to disk\n"; + return; + } + + /////////////////////////////////////////////////////////////////// + // Tokenize operation + Tokenizer params; + params.apply(operation, "|"); + int numParams = params.size() - 1; + + // No operation has more than 2 arguments ... + if(numParams > 2) { + LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION)); + throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION); + } + + // Get the operation type: + Tokenizer::const_iterator tok_iter = params.begin(); + std::string opType = Tokenizer::data(tok_iter); + // Check the number of parameters: + bool wrongBody = false; + + if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true; + + if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true; + + if((opType == "burst") && (numParams < 1)) wrongBody = true; + + if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true; + + if(wrongBody) { + // Launch exception + std::string msg = "Wrong body content format on HTTP Request for '"; + msg += opType; + msg += "' operation (missing parameter/s)"; + throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); + } + + // All seems ok: + std::string param1, param2; + + if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); } + + if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); } + + // Operations: + if(opType == "code") { + G_codecMsg.loadXML(param1); + std::string hexString = anna::functions::asHexString(G_codecMsg.code()); + // write to outfile + ofstream outfile(param2.c_str(), ifstream::out); + outfile.write(hexString.c_str(), hexString.size()); + outfile.close(); + } else if(opType == "decode") { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + // Decode + try { G_codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); } + + std::string xmlString = G_codecMsg.asXMLString(); + // write to outfile + ofstream outfile(param2.c_str(), ifstream::out); + outfile.write(xmlString.c_str(), xmlString.size()); + outfile.close(); + } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) { + anna::diameter::comm::Entity *entity = getEntity(); + + if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION); + + if(param1 != "") { + if(param2 != "") { + std::string key = param1; + key += "|"; + key += param2; + + if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide(); + + if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show(); + + if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false"; + + if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false"; + } else { + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port); + + if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide(); + + if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show(); + + if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false"; + + if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false"; + } + } else { + if(opType == "hide") entity->hide(); + + if(opType == "show") entity->show(); + + if(opType == "hidden") result = entity->hidden() ? "true" : "false"; + + if(opType == "shown") result = entity->shown() ? "true" : "false"; + } + } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) { + anna::diameter::comm::Entity *entity = getEntity(); + + if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION); + + if((opType == "sendxml") || (opType == "sendxml2e")) { + G_codecMsg.loadXML(param1); + G_commMsgSent2e.clearBody(); + try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher) + + G_commMsgSent2e.setBody(G_codecMsg.code()); + } else { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + G_commMsgSent2e.setBody(db_aux); + } + + bool success = entity->send(G_commMsgSent2e, cl.exists("balance")); + + // Detailed log: + if(logEnabled()) { + anna::diameter::comm::Server *usedServer = entity->getLastUsedResource(); + anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL; + std::string detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir + writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail); + } + } else if((opType == "burst")) { + anna::diameter::comm::Entity *entity = getEntity(); + + if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION); + + // burst|clear clears all loaded burst messages. + // burst|load| loads the next diameter message into launcher burst. + // burst|start| starts the message sending with a certain initial load. + // burst|push| sends specific non-aynchronous load. + // burst|stop stops the burst cycle. + // burst|repeat|[[yes]|no] restarts the burst launch when finish. + // burst|send| send messages from burst list. The main difference with + // start/push operations is that burst won't be awaken. + // Externally we could control sending time (no request + // will be sent for answers). + // burst|goto| Updates current burst pointer position. + // burst|look| Show programmed burst message for order provided. + + if(param1 == "clear") { + result = "Removed "; + result += anna::functions::asString(clearBurst()); + result += " elements."; + } else if(param1 == "load") { + if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION); + + G_codecMsg.loadXML(param2); + + if(G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION); + try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher) + + int position = loadBurstMessage(G_codecMsg.code()); + result = "Loaded '"; + result += param2; + result += "' file into burst list position "; + result += anna::functions::asString(position); + } else if(param1 == "start") { + if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION); + + int initialLoad = atoi(param2.c_str()); + int processed = startBurst(initialLoad); + + if(processed > 0) { + result = "Initial load completed for "; + result += anna::functions::entriesAsString(processed, "message"); + result += "."; + } + } else if(param1 == "push") { + if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION); + + int pushed = pushBurst(atoi(param2.c_str())); + + if(pushed > 0) { + result = "Pushed "; + result += anna::functions::entriesAsString(pushed, "message"); + result += "."; + } + } else if(param1 == "pop") { + if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION); + + int releaseLoad = atoi(param2.c_str()); + int popped = popBurst(releaseLoad); + + if(popped > 0) { + result = "Burst popped for "; + result += anna::functions::entriesAsString(popped, "message"); + result += "."; + } + } else if(param1 == "stop") { + int left = stopBurst(); + + if(left != -1) { + result += anna::functions::entriesAsString(left, "message"); + result += " left to the end of the cycle."; + } + } else if(param1 == "repeat") { + if(param2 == "") param2 = "yes"; + + bool repeat = (param2 == "yes"); + repeatBurst(repeat); + result += (repeat ? "Mode on." : "Mode off."); + } else if(param1 == "send") { + if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION); + + int sent = sendBurst(atoi(param2.c_str())); + + if(sent > 0) { + result = "Sent "; + result += anna::functions::entriesAsString(sent, "message"); + result += "."; + } + } else if(param1 == "goto") { + if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION); + + result = gotoBurst(atoi(param2.c_str())); + result += "."; + } else if(param1 == "look") { + if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION); + + result = "\n\n"; + result += lookBurst(atoi(param2.c_str())); + result += "\n\n"; + } else { + throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION); + } + } else if((opType == "sendxml2c") || (opType == "sendhex2c")) { + anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer(); + + if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION); + + if(opType == "sendxml2c") { + G_codecMsg.loadXML(param1); + G_commMsgSent2c.clearBody(); + try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher) + + G_commMsgSent2c.setBody(G_codecMsg.code()); + } else { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + G_commMsgSent2c.setBody(db_aux); + } + + bool success = localServer->send(G_commMsgSent2c); + + // Detailed log: + if(logEnabled()) { + anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail); + } + } else if(opType == "loadxml") { + G_codecMsg.loadXML(param1); + std::string xmlString = G_codecMsg.asXMLString(); + std::cout << xmlString << std::endl; + } else if(opType == "diameterServerSessions") { + int diameterServerSessions = atoi(param1.c_str()); + + if(!getDiameterLocalServer()) + startDiameterServer(diameterServerSessions); + else + getDiameterLocalServer()->setMaxConnections(diameterServerSessions); + } else if((opType == "answerxml") || (opType == "answerxml2c")) { + anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer(); + + if(!localServer) + throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION); + + if(param1 == "") { // programmed answers FIFO's to stdout + std::cout << G_reactingAnswers2C.asString("ANSWERS TO CLIENT") << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } else if (param1 == "rotate") { + G_reactingAnswers2C.rotate(true); + } else if (param1 == "exhaust") { + G_reactingAnswers2C.rotate(false); + } else if (param1 == "clear") { + G_reactingAnswers2C.clear(); + } else if (param1 == "dump") { + G_reactingAnswers2C.dump(); + } else { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + anna::diameter::codec::Message *message = engine->createMessage(param1); + LOGDEBUG + ( + anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION); + ); + + if(message->isRequest()) + throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION); + + int code = message->getId().first; + LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION)); + G_reactingAnswers2C.addMessage(code, message); + } + } else if(opType == "answerxml2e") { + anna::diameter::comm::Entity *entity = getEntity(); + + if(!entity) + throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION); + + if(param1 == "") { // programmed answers FIFO's to stdout + std::cout << G_reactingAnswers2E.asString("ANSWERS TO ENTITY") << std::endl; + response_content = "Programmed answers dumped on stdout\n"; + return; + } else if (param1 == "rotate") { + G_reactingAnswers2C.rotate(true); + } else if (param1 == "exhaust") { + G_reactingAnswers2C.rotate(false); + } else if (param1 == "clear") { + G_reactingAnswers2E.clear(); + } else if (param1 == "dump") { + G_reactingAnswers2E.dump(); + } else { + anna::diameter::codec::Engine *engine = anna::functions::component (ANNA_FILE_LOCATION); + anna::diameter::codec::Message *message = engine->createMessage(param1); + LOGDEBUG + ( + anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION); + ); + + if(message->isRequest()) + throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION); + + int code = message->getId().first; + LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION)); + G_reactingAnswers2E.addMessage(code, message); + } + } else { + LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION)); + throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION); + } + + // HTTP response + response_content = "Operation processed; "; + + if((opType == "decode") || (opType == "code")) { + response_content += "File '"; + response_content += param2; + response_content += "' created."; + response_content += "\n"; + } else if((opType == "hide") || (opType == "show")) { + response_content += "Resource '"; + response_content += ((param1 != "") ? param1 : "Entity"); + + if(param2 != "") { + response_content += "|"; + response_content += param2; + } + + response_content += "' "; + + if(opType == "hide") response_content += "has been hidden."; + + if(opType == "show") response_content += "has been shown."; + + response_content += "\n"; + } else if((opType == "hidden") || (opType == "shown")) { + response_content += "Result: "; + response_content += result; + response_content += "\n"; + } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) { + response_content += "Message '"; + response_content += param1; + response_content += "' sent to entity."; + response_content += "\n"; + } else if(opType == "burst") { + response_content += "Burst '"; + response_content += param1; + response_content += "' executed. "; + response_content += result; + response_content += "\n"; + } else if((opType == "sendxml2c") || (opType == "sendhex2c")) { + response_content += "Message '"; + response_content += param1; + response_content += "' sent to client."; + response_content += "\n"; + } else if(opType == "loadxml") { + response_content += "Message '"; + response_content += param1; + response_content += "' loaded."; + response_content += "\n"; + } else if((opType == "answerxml") || (opType == "answerxml2c")) { + response_content += "'"; + response_content += param1; + response_content += "' applied on server FIFO queue"; + response_content += "\n"; + } else if(opType == "answerxml2e") { + response_content += "'"; + response_content += param1; + response_content += "' applied on client FIFO queue"; + response_content += "\n"; + } else if(opType == "diameterServerSessions") { + response_content += "Maximum server socket connections updated to '"; + response_content += param1; + response_content += "'."; + response_content += "\n"; + } +} + + +int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() { + CommandLine& cl(anna::CommandLine::instantiate()); + std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart"); + + if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1 + + try { + // Service-Context-Id: + anna::diameter::helpers::dcca::ChargingContext::_v chargingContext; + std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext); + + switch(chargingContext) { + case anna::diameter::helpers::dcca::ChargingContext::Data: + case anna::diameter::helpers::dcca::ChargingContext::Voice: + case anna::diameter::helpers::dcca::ChargingContext::Content: { + // Session-Id: ';;[;="">]' + std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody()); + std::string diameterIdentity, optional; + anna::U32 high, low; + anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional); + + if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions); + + if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions); + + if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions); + } + //case anna::diameter::helpers::dcca::ChargingContext::SMS: + //case anna::diameter::helpers::dcca::ChargingContext::MMS: + //default: + // return -1; // IEC model and Unknown traffic types + } + } catch(anna::RuntimeException &ex) { + LOGDEBUG( + std::string msg = ex.getText(); + msg += " | Round-robin between sessions will be used to send"; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + } + + return -1; +} + + +void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Request received: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); + + // Lookup reacting answers list: + int code = cid.first; + anna::diameter::codec::Message *answer_message = G_reactingAnswers2E.getMessage(code); + if (answer_message) { + // Prepare answer: + my_app.getCommunicator()->prepareAnswer(answer_message, message); + + try { + G_commMsgSent2e.setBody(answer_message->code()); + /* response = NULL =*/clientSession->send(&G_commMsgSent2e); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString()); + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString()); + } + + // Pop front the reacting answer: + G_reactingAnswers2E.nextMessage(code); + return; + } + + LOGDEBUG + ( + std::string msg = "No answers programmed (maybe sold out) for request coming from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // not found: forward to client (if exists) + // Forward to client: + anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); + + if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) { + try { + anna::diameter::comm::Message *msg = G_commMessages.create(); + msg->updateEndToEnd(false); // end-to-end will be kept + msg->setBody(message); + msg->setRequestClientSessionKey(clientSession->getKey()); + bool success = localServer->send(msg); + + // Detailed log: + if(my_app.logEnabled()) { + anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource(); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail); + } + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + } +} + + +void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION)); + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::diameter::comm::ClassCode::_v code = response.getClassCode(); + anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); + anna::diameter::comm::Message* request = const_cast(response.getRequest()); + const anna::DataBlock* message = response.getMessage(); + const anna::diameter::comm::ClientSession *clientSession = static_cast(response.getSession()); + bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); + bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); + bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); + bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); + bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); + // CommandId: + anna::diameter::CommandId request_cid = request->getCommandId(); + LOGDEBUG + ( + std::string msg = "Response received for original diameter request: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + msg += " | Response: "; + msg += response.asString(); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(isUnavailable) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION)); + } + + if(contextExpired) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION)); + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString()); + } + } + + if(isOK) { + LOGDEBUG( + std::string msg = "Received response for diameter message: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + // Write reception + bool alreadyDecodedOnG_codecMsg = false; + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) { + my_app.writeLogFile(*message, "recvfe", clientSession->asString()); + alreadyDecodedOnG_codecMsg = true; + } + } + + // Forward to client: + anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer(); + + if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) { + try { + G_commMsgFwd2c.updateEndToEnd(false); // end-to-end will be kept + G_commMsgFwd2c.setBody(*message); + bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey()); + G_commMessages.release(request); + // Detailed log: + anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey()); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // esto no deberia ocurrir + + if(my_app.logEnabled()) { + if(alreadyDecodedOnG_codecMsg) + my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail); + else + my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail); + } + } catch(anna::RuntimeException &ex) { + ex.trace(); + } + } + } + + // Triggering burst: + if(isOK || contextExpired) my_app.sendBurstMessage(); +} + + +void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Out-of-context response received from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString()); +} + +void MyDiameterEntity::eventDPA(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventDPA", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Disconnect-Peer-Answer received from entity: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString()); +} + +void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Request received: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); + + // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point) + int code = cid.first; + anna::diameter::codec::Message *programmed_answer = G_reactingAnswers2C.getMessage(code); + bool programmed = (programmed_answer != NULL); + + anna::diameter::comm::Entity *entity = my_app.getEntity(); + if(!programmed && entity) { // forward condition (no programmed answer + entity available) + anna::diameter::comm::Message *msg = G_commMessages.create(); + msg->updateEndToEnd(false); // end-to-end will be kept + msg->setBody(message); + msg->setRequestServerSessionKey(serverSession->getKey()); + bool success = entity->send(msg, cl.exists("balance")); + + // Detailed log: + if(my_app.logEnabled()) { + anna::diameter::comm::Server *usedServer = entity->getLastUsedResource(); + anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL; + std::string detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir + my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded + } + + return; + } + + // Error analisys: + bool analysisOK = true; // by default + anna::diameter::codec::Message *answer_message = NULL; + + if(!cl.exists("ignoreErrors")) { // Error analysis + answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg; + answer_message->clear(); + + // Decode + try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); } + + answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm()); + analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); + } + + // Programmed answer only when all is ok + if(analysisOK) { + if(programmed) { + answer_message = programmed_answer; + // Prepare answer: + my_app.getCommunicator()->prepareAnswer(answer_message, message); + } else return; // nothing done + } + + anna::diameter::codec::Engine *codecEngine = (anna::functions::component (ANNA_FILE_LOCATION)); + anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode(); + + if(!analysisOK) + codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never); + + try { + G_commMsgSent2c.setBody(answer_message->code()); + /* response = NULL =*/serverSession->send(&G_commMsgSent2c); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString()); + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString()); + } + + // Restore validation mode + codecEngine->setValidationMode(backupVM); + + // Pop front the reacting answer: + if(analysisOK && programmed) G_reactingAnswers2C.nextMessage(code); +} + +void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION)); + Launcher& my_app = static_cast (anna::app::functions::getApp()); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::diameter::comm::ClassCode::_v code = response.getClassCode(); + anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode(); + anna::diameter::comm::Message* request = const_cast(response.getRequest()); + const anna::DataBlock* message = response.getMessage(); + const anna::diameter::comm::ServerSession *serverSession = static_cast(response.getSession()); + bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind); + bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage); + bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout); + bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable); + bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success); + // CommandId: + anna::diameter::CommandId request_cid = request->getCommandId(); + LOGDEBUG + ( + std::string msg = "Response received for original diameter request: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + msg += " | Response: "; + msg += response.asString(); + msg += " | LocalServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(isUnavailable) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION)); + } + + if(contextExpired) { + //if (isApplicationMessage) + LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION)); + + if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA + if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString()); + } + } + + if(isOK) { + LOGDEBUG( + std::string msg = "Received response for diameter message: "; + msg += anna::diameter::functions::commandIdAsPairString(request_cid); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + // Write reception + if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString()); + + // This is not very usual, but answers could arrive from clients: + anna::diameter::comm::Entity *entity = my_app.getEntity(); + + if(entity) { + anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey()); + std::string detail; + + if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : ""; // esto no deberia ocurrir + + try { + G_commMsgFwd2e.updateEndToEnd(false); // end-to-end will be kept + G_commMsgFwd2e.setBody(*message); + + // Metodo 1: + if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e); + + // Metodo 2: + //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey()); + //bool success = entity->send(G_commMsgFwd2e); + G_commMessages.release(request); + + if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded + } catch(anna::RuntimeException &ex) { + ex.trace(); + + if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded + } + } + } +} + +void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Out-of-context response received from client: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString()); +} + +void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message) +throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION)); + // Performance stats: + Launcher& my_app = static_cast (anna::app::functions::getApp()); + // CommandId: + anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message); + LOGDEBUG + ( + std::string msg = "Disconnect-Peer-Answer response received from client: "; + msg += anna::diameter::functions::commandIdAsPairString(cid); + msg += " | DiameterServer: "; + msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort()); + msg += " | EventTime: "; + msg += anna::time::functions::currentTimeAsString(); + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString()); +} + +anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const +throw() { + anna::xml::Node* result = parent->createChild("launcher"); + anna::comm::Application::asXML(result); + // Timming: + result->createAttribute("StartTime", a_start_time.asString()); + result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000); + // Diameter: + (anna::functions::component (ANNA_FILE_LOCATION))->asXML(result); + // OAM: + anna::diameter::comm::OamModule::instantiate().asXML(result); + anna::diameter::codec::OamModule::instantiate().asXML(result); + // Statistics: + anna::statistics::Engine::instantiate().asXML(result); + return result; +} + diff --git a/include/anna/config/defines.hpp b/include/anna/config/defines.hpp index e69de29..a8e995b 100644 --- a/include/anna/config/defines.hpp +++ b/include/anna/config/defines.hpp @@ -0,0 +1,118 @@ +// ANNA - Anna is Not Nothingness Anymore // +// // +// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo // +// // +// See project site at http://redmine.teslayout.com/projects/anna-suite // +// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // + + +#ifndef anna_config_defines_hpp +#define anna_config_defines_hpp + +//#include +#include +// For cstd0x compatibility we will use stdint.h types instead of std:: ones on cstdint: +//#include when C++11 available + +#ifdef ANNA_FILE_LOCATION +#undef ANNA_FILE_LOCATION +#endif +#define ANNA_FILE_LOCATION (const char *)__FILE__,(const int)__LINE__ +//#define ANNA_FILE_LOCATION __PRETTY_FUNCTION__,(const char *)__FILE__,(const int)__LINE__ + + +#define ANNA_VERSION 0x000d03 + +#if defined(__linux__) && !defined (_NO_BUILTIN) +#define anna_memcpy(a,b,c) __builtin_memcpy((a),(b),(c)) +#define anna_memset(a,b,c) __builtin_memset((a),(b),(c)) +#define anna_memmove(a,b,c) __builtin_memmove((a),(b),(c)) +#define anna_strcpy(a,b) __builtin_strcpy((a),(b)) +#define anna_strncpy(a,b,c) __builtin_strncpy((a),(b),(c)) +#define anna_strcmp(a,b) __builtin_strcmp((a),(b)) +#define anna_strncmp(a,b,n) __builtin_strncmp((a),(b),(n)) +#define anna_strcat(a,b) __builtin_strcat((a),(b)) +#define anna_strlen(a) __builtin_strlen((a)) +#define anna_strstr(a,b) __builtin_strstr((a),(b)) +#define anna_strchr(a,b) __builtin_strchr((a),(b)) +#else +#define anna_memcpy(a,b,c) memcpy((a),(b),(c)) +#define anna_memset(a,b,c) memset((a),(b),(c)) +#define anna_memmove(a,b,c) memmove((a),(b),(c)) +#define anna_strcpy(a,b) strcpy((a),(b)) +#define anna_strncpy(a,b,c) strncpy((a),(b),(c)) +#define anna_strcmp(a,b) strcmp((a),(b)) +#define anna_strncmp(a,b,n) strncmp((a),(b),(n)) +#define anna_strcat(a,b) strcat((a),(b)) +#define anna_strlen(a) strlen((a)) +#define anna_strstr(a,b) strstr((a),(b)) +#define anna_strchr(a,b) strchr((a),(b)) +#endif + +#define anna_signal_shield(r,a) { int cx (0); do { if ((r = (a)) < 0) cx ++; } while (r < 0 && errno == EINTR && cx < 5); } + +//#define anna_append_string(str,str1,str2) (str).append (str1).append (str2) + +#ifndef _NOTRACE +#define LOGWARNING(a) if (anna::Logger::isActive (anna::Logger::Warning) == true) {a;} +#define LOGNOTICE(a) if (anna::Logger::isActive (anna::Logger::Notice) == true) {a;} +#define LOGINFORMATION(a) if (anna::Logger::isActive (anna::Logger::Information) == true) {a;} +#define LOG_EXCL_INFORMATION(a) if (anna::Logger::isActive (anna::Logger::Debug) == false && anna::Logger::isActive (anna::Logger::Information) == true) {a;} +#define LOGDEBUG(a) if (anna::Logger::isActive (anna::Logger::Debug) == true) {a;} +#define LOGLOCAL0(a) if (anna::Logger::isActive (anna::Logger::Local0) == true) {a;} +#define LOGLOCAL1(a) if (anna::Logger::isActive (anna::Logger::Local1) == true) {a;} +#define LOGLOCAL2(a) if (anna::Logger::isActive (anna::Logger::Local2) == true) {a;} +#define LOGLOCAL3(a) if (anna::Logger::isActive (anna::Logger::Local3) == true) {a;} +#define LOGLOCAL4(a) if (anna::Logger::isActive (anna::Logger::Local4) == true) {a;} +#define LOGLOCAL5(a) if (anna::Logger::isActive (anna::Logger::Local5) == true) {a;} +#define LOGLOCAL6(a) if (anna::Logger::isActive (anna::Logger::Local6) == true) {a;} +#define LOGLOCAL7(a) if (anna::Logger::isActive (anna::Logger::Local7) == true) {a;} +#define LOGMETHOD(a) a; +#define LOGFUNCTION(a) a; +#else +#define LOGWARNING(a) +#define LOGNOTICE(a) +#define LOGINFORMATION(a) +#define LOGDEBUG(a) +#define LOGLOCAL0(a) +#define LOGLOCAL1(a) +#define LOGLOCAL2(a) +#define LOGLOCAL3(a) +#define LOGLOCAL4(a) +#define LOGLOCAL5(a) +#define LOGLOCAL6(a) +#define LOGLOCAL7(a) +#define LOGMETHOD(a) +#define LOGFUNCTION(a) +#endif + +#ifdef _MT +#define WHEN_MULTITHREAD(a) a +#define WHEN_SINGLETHREAD(a) +#else +#define WHEN_MULTITHREAD(a) +#define WHEN_SINGLETHREAD(a) a +#endif + +namespace anna { +#ifndef __x86_64__ +#undef __anna64__ +///** Defines required data type to conversion from pointer to integer */ +//typedef int ptrnumber; +#else +#define __anna64__ +///** Defines required data type to conversion from pointer to integer */ +//typedef long ptrnumber; +#endif + +typedef intptr_t ptrnumber; + +} + +/** + * Make conversion from pointer to integer, it will work both 64 bits and 32 bits architecture. + */ +#define anna_ptrnumber_cast(pointer) (anna::ptrnumber)((void*)(pointer)) + +#endif + diff --git a/include/anna/diameter.comm/Entity.hpp b/include/anna/diameter.comm/Entity.hpp index e69de29..151f0ff 100644 --- a/include/anna/diameter.comm/Entity.hpp +++ b/include/anna/diameter.comm/Entity.hpp @@ -0,0 +1,460 @@ +// ANNA - Anna is Not Nothingness Anymore // +// // +// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo // +// // +// See project site at http://redmine.teslayout.com/projects/anna-suite // +// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // + + +#ifndef anna_diameter_comm_Entity_hpp +#define anna_diameter_comm_Entity_hpp + + +// STL +#include +#include + +#include + +#include +#include + + +namespace anna { +class DataBlock; +namespace xml { +class Node; +} +} + + + +namespace anna { + +namespace diameter { + +namespace comm { + +class Engine; +class Server; +class Response; +class Message; + + +/** + Generic diameter server list (N-servers entity) +*/ +class Entity { + + std::vector a_servers; + int a_maxServers; // -1 means "no limit to add servers" + std::string a_description; + int a_category; + std::vector::iterator a_deliveryIterator; + Server *a_lastUsedResource; + + // Engine + Engine *a_engine; + + // Availability + bool a_available; // any of the servers must be bound + void availabilityLost() throw(); + void availabilityRecovered() throw(); + bool refreshAvailability() throw(); // return true if change + void assertReady() throw(anna::RuntimeException); + void initialize() throw(); + void childIdle() const throw(); + + // Selected for remove + bool a_deprecated; // entity has been selected as deprecated (will be removed when idle) + + // internal helpers + std::string a_socketListLiteral; // ADDRESS:PORT space-separated list + std::string a_primarySocketLiteral; // ADDRESS:PORT for primary (used on standard entities) + std::string a_secondarySocketLiteral; // ADDRESS:PORT for primary (used on standard entities) + + + // Activity + anna::Millisecond a_lastIncomingActivityTime; // last unix timestamp (in milliseconds) when message reception was managed over this entity + anna::Millisecond a_lastOutgoingActivityTime; // last unix timestamp (in milliseconds) when message sending was managed over this entity + void updateIncomingActivityTime() throw(); + void updateOutgoingActivityTime() throw(); + + // Private close/destroy method + void close(bool destroy) throw(anna::RuntimeException); + + +public: + + + /** + * Default constructor. Entities should be create through diameter::comm::Engine + * @param maxServers Maximum number of servers managed by the entity. Default is 2 (standard/dual entity). + * The value -1, means no limit to add servers. + */ + Entity(int maxServers = 2) : a_maxServers(maxServers) { initialize(); } + + + /** + * Sets the maximum number of servers managed by the entity. + * + * @param maxServers Maximum number of servers managed by the entity. + */ + void setMaxServers(int maxServers) throw() { a_maxServers = maxServers; } + + /** + * Gets the maximum number of servers managed by the entity. + * + * @return Maximum number of servers managed by the entity. + */ + int getMaxServers() const throw() { return a_maxServers; } + + + /** + * Sets the entity description. + * + * @param description Entity description. Empty by default. + */ + void setDescription(const std::string &description) throw() { a_description = description; } + + /** + * Gets the entity description. + * + * @return Entity description. + */ + const std::string & getDescription() const throw() { return a_description; } + + + /** + * Sets the diameter::comm::Engine + * @param e Diameter::comm::Engine + */ + void setEngine(Engine *e) throw() { a_engine = e; } + + + /** + * Add a server to the entity and create all the servers configured at #setSocketsPerDiameterServer within that server. + * + * \param serverId Diameter server ip/port. + * + * @return Returns success on send operation over any server within the entity + */ + void addServer(const socket_t & serverId) throw(anna::RuntimeException); + + /** + * Binds entity servers. + * + * @return Returns true if all client-session were successfully bound + */ + bool bind() throw(anna::RuntimeException); + + /** + * Propagate auto recovery configuration to servers within entity + * + * @param autoRecovery Auto recovery indicator. True by default. + */ + void raiseAutoRecovery(bool autoRecovery = true) throw(anna::RuntimeException); + + /** + Sets timeout for wait responses for any class code request for all entity servers + + \param v Diameter request type. + \param millisecond Milliseconds for timeout + */ + void setClassCodeTimeout(const ClassCode::_v v, const anna::Millisecond & millisecond) throw(); + + /** + Sets entity category. Used by application in order to categorize or clasify. + + @param category Entity category + */ + void setCategory(int category) throw() { a_category = category; } + + /** + Gets entity category. Used by application in order to categorize or clasify. + + @return Entity category + */ + int getCategory() const throw() { return a_category; } + + /** + Gets the last used resource (server) during sending. + Broadcast doesn't updates this information. + */ + Server *getLastUsedResource() const throw() { return (a_lastUsedResource); } + + + +// SIMPLE BALANCE or STANDARD documentation version +// /** +// Sent a message to the entity. First uses primary server, secondary if fails and so on to the +// last defined resource (server) within entity. Another sending algorithm (non standard) could +// be enabled (balance boolean parameter): it consist in round-robin server selection without +// trying any one if fails (standard behaviour tries all servers from FIRST defined). +// Anyway, last used delivery resource could be known through #getLastUsedResource(). +// +// When the message is a request, a timer will be set automatically to control the response time. +// If expires, the ResultCode Timeout will be finally notified on #Entity::eventResponse. This +// timeout value will be configured at #setClassCodeTimeout. +// +// \param message Message sent. +// \param balance False by default (standard beaviour), but useful to balance over servers within entity. +// +// @return Boolean about success in send operation. Standard behaviour (no balance) implies true result when any +// of the entity servers could send the message, and false when neither of the servers was available or fail to +// send the message. Broadcast try to send all over the resources in spite of any fail, and balanced sendings +// fails when next selected resource fail to send the message (and no alarm or error counter is generated in +// this case because it can't be understood/ensured as entity-sending fail. +// */ + +// OJO: en el caso estandard, no se prueban todas las sessiones de un servidor si tiene mas de una, luego la alarma +// generada en caso de error, presupone que las sessiones no usadas, también darían error, lo cual no tiene porque +// ser cierto. En condiciones normales, los servidores tienen una session, con lo que lo anterior es cierto y el +// la practica es lo mas normal. + + /** + Sent a message to the entity. First uses primary server, secondary if fails and so on to the + last defined resource (server) within entity. Another sending algorithm (non standard) could + be enabled (balance boolean parameter): it consist in round-robin server selection to set the + first resource in a complete cycle (standard behaviour tries all servers from FIRST defined). + Anyway, last used delivery resource could be known through #getLastUsedResource(). + + When the message is a request, a timer will be set automatically to control the response time. + If expires, the ResultCode Timeout will be finally notified on #Entity::eventResponse. This + timeout value will be configured at #setClassCodeTimeout. + + \param message Message sent. + \param balance False by default (standard beaviour), but useful to balance over servers within entity. + + @return Boolean about success in send operation. Implies true result when any of the entity servers could + send the message, and false when neither of the servers was available or fail to send the message (an alarm + and error counter will be generated in this case). Broadcast try to send all over the resources in spite of + any fail. + */ + bool send(const Message *message, bool balance = false) throw(anna::RuntimeException); + bool send(const Message &message, bool balance = false) throw(anna::RuntimeException) { return send(&message, balance); } + + + /** + Before sending a message over each entity server, socketId could be specified to select + which client session within such server will manage the message. + + Default implementation has been focused on charging applications but any other kind of + application could re-implement this method and change the behaviour: + +
+     Charging involves two peers:
+
+        Charging Trigger Function (CTF): Makes decisions on how to charge the user for specific
+                                         services, issues requests to the server (OCF).
+        Online Charging Function (OCF):  Performs actual charging based on received message type,
+                                         service logic and user profile information.
+
+     There are three main scenarios:
+
+        Immediate Event Charging (IEC): The CTF sends a one time request. This request contains
+                                        a predefined set of AVPs indicating which service has
+                                        been activated or how many units have been consumed
+                                        (this depends on application logic).
+
+        Event Charging with Unit Reservation (ECUR): The CTF issues a request which indicates the
+                                                     desired unit count for reservation. On service
+                                                     delivery, the CTF issues another request which
+                                                     indicates how many units were actually consumed.
+                                                     Units can be of any type, as they are application
+                                                     specific.
+
+        Session Charging with Unit Reservation(SCUR): As above, however reservation can happen more than once.
+
+     In order to minimize race conditions within trasactions, default implementation will select the connection
+     fixed by an stickiness value (Session-Id will be used) for ECUR and SCUR models (Data, Voice and Content
+     traffic). IEC model, represented by SMS ans MMS traffic will use round-robin between sockets. The type
+     of traffic will be analyzed by mean Service-Context-Id AVP. If traffic type is not reconized, value of
+     '-1' will be returned doing round-robin socket selection within active server.
+
+     Diameter session-oriented load balancing enables to distribute Diameter signaling traffic across
+     multiple client sessions for the selected entity server. Application could re-implement different
+     load balancing policies, including support for session stickiness and business decisions, and
+     subscriber and service aware contextual load balancing strategies. By default, Session-Id avp
+     is used to select the resource. Session-Id is split into 4 sections: diameter identity, high
+     part, low part and optional part. Default implementation analizes 'low' part, returning its
+     value as reference for socket selection.
+     
+ + When server is configured as single client session (max client sessions equal to 1), entity will ignore + this method being more efficient, because former algorithms would not affect the session selection. + + \param message Message which is being sent. + \param maxClientSessions Number of client-sessions on specific server prepared for send. + + @return Socket-id used within range [0,maxClientSessions-1]. Value '-1' if round-robin is desired. + If socket-id is return out of range, send procedure will throw an exception. + */ + virtual int readSocketId(const Message *message, int maxClientSessions) const throw(); + + + /** + Sent a message to all the entity servers. + It is used, i.e., in Disconnect-Peer-Request procedure over a certain entity. + + \param message Message which is being sent. + + @return Returns true (success) only when broadcast is success over all the entity servers. If any server fails, + then false is returned. + */ + bool broadcast(const Message *message) throw(anna::RuntimeException); + bool broadcast(const Message &message) throw(anna::RuntimeException) { return broadcast(&message); } + + + /** + Returns true when any of the entity servers is Bound. False when all not-bound. + */ + bool isAvailable() const throw() { return a_available; } + + /** + Returns true when the entity has been selected as deprecated + */ + bool isDeprecated() const throw() { return a_deprecated; } + + /** + Sets the entity deprecated state + */ + void setDeprecated(bool deprecated = true) throw() { a_deprecated = deprecated; } + + + /** + Gets the number of requests messages over-the-air. + + @return OTA messages. + */ + int getOTARequests() const throw(); + + /** + Returns idle state (no pending answers). + + @return Idle state. + */ + bool idle() const throw() { return (getOTARequests() == 0); } + + + std::vector::iterator begin() throw() { return a_servers.begin(); } + std::vector::iterator end() throw() { return a_servers.end(); } + std::vector::const_iterator begin() const throw() { return a_servers.begin(); } + std::vector::const_iterator end() const throw() { return a_servers.end(); } + + /** + Close all the entity servers (close client-sessions within them). Depending on client-session configuration ('OnDisconnect' behaviour), + pending answers will be wait (graceful) or ignored (immediate-abrupt close). + Resources are not destroyed. + */ + void close() throw(anna::RuntimeException) { close(false /* no destroy */); } + + // helpers + + /** + Number of currently configured servers + */ + int getNumberOfServers() const throw() { return a_servers.size(); } + + /** + Number of maximum allowed servers + */ + int getMaxServerss() const throw() { return a_maxServers; } + + /** + List of (address,port) pairs defining entity servers + */ + socket_v getAddressPortList() const throw(); + + + /** + Deny resources for delivery restriction. + Deny all its servers + */ + void hide() throw(); + + /** + Allow resource for delivery permission. + Allow all its servers + */ + void show() throw(); + + /** + Returns true when all its servers resources are hidden for application messages delivery + */ + bool hidden() const throw(); + + /** + Returns true when all its servers resources are shown for application messages delivery + */ + bool shown() const throw(); + + + /** + Class string representation + \return String with relevant information for this instance. + */ + std::string asString() const throw(); + + /** + Class xml representation + \param parent Parent XML node on which hold this instance information. + \return XML document with relevant information for this instance. + */ + anna::xml::Node* asXML(anna::xml::Node* parent) const throw(); + +protected: + + /** + Handler about event break connection from diameter server (server) over this entity. + When notified, ANNA.diameter.comm generates an diameter::comm::Entity::eventResponse for every request with pending answers. + Default implementation traces warning event + \param clientSession ClientSession from which shutdown has been received + */ + virtual void eventPeerShutdown(const ClientSession* clientSession) throw(); + + /** + Handler for diameter server (server) responses + + \param response Answer container object for corresponding diameter request + */ + virtual void eventResponse(const Response& response) throw(anna::RuntimeException) = 0; + + /** + Handler for diameter server (server) requests + + \param clientSession ClientSession from which request has been received + \param request Diameter request message received + */ + virtual void eventRequest(ClientSession* clientSession, const anna::DataBlock &request) throw(anna::RuntimeException) = 0; + //virtual void eventRequest(ClientSession* clientSession, const Message& request) throw(anna::RuntimeException) = 0; + + /** + Handler for diameter session responses out of context + + \param clientSession ClientSession from which request has been received + \param response Answer data block object without context match + */ + virtual void eventUnknownResponse(ClientSession *clientSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0; + + /** + Handler for diameter session Disconnect-Peer-Answer messages + + \param clientSession ClientSession from which request has been received + \param response Answer data block object without context match + */ + virtual void eventDPA(ClientSession *clientSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0; + + + + + friend class Engine; + friend class Server; +}; + +} +} +} + +#endif + -- 2.20.1