-
-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.setCurrent();
- // 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*/);
- anna::oam::CounterManager& cm = anna::oam::CounterManager::instantiate();
- cm.setEngine(a_timeEngine);
- cm.setRecordPeriod(Millisecond(300000));
- cm.setCounterRecorder(static_cast<anna::oam::CounterRecorder*>(a_counterRecorder));
-
- // 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:
- 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)); // aqui hay que proporcionar una IP !
- const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // Artimaña para resolver (IP o hostname)
- a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
- // Stack:
- anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
- anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
-
- try {
- anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id */);
- // Analyze comma-separated list:
- anna::Tokenizer lst;
- std::string dictionaryParameter = cl.getValue("dictionary");
- lst.apply(dictionaryParameter, ",");
-
- if (lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
- anna::Tokenizer::const_iterator tok_min(lst.begin());
- anna::Tokenizer::const_iterator tok_max(lst.end());
- anna::Tokenizer::const_iterator tok_iter;
- std::string pathFile;
- d->allowUpdates();
-
- for (tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
- pathFile = anna::Tokenizer::data(tok_iter);
- d->load(pathFile);
- }
- }
-
- codecEngine->setDictionary(d);
- LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
- } catch (anna::RuntimeException &ex) {
- ex.trace();
- }
-
- // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
- // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
- if (cl.exists("integrationAndDebugging")) {
- codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
- codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
- }
-
- codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
-
- // 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("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);
- 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 {
- sendOperation(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 MyHandler::sendOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
- LOGMETHOD(anna::TraceMethod tm("MyHandler", "sendOperation", ANNA_FILE_LOCATION));
- Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- 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 = "";
-
- // Help:
- if (operation == "help") {
- std::cout << my_app.help() << std::endl;
- response_content = "Help dumped on stdout and information-level traces (launcher.traces file)\n";
- return;
- }
-
- // Reset performance data:
- if (operation == "collect") {
- my_app.resetCounters();
- my_app.resetStatistics();
- response_content = "All process counters & statistic information have been reset\n";
- return;
- }
-
- // Tokenize operation
- Tokenizer params;
- params.apply(operation, "|");
- int numParams = params.size() - 1;
- //LOGDEBUG(anna::Logger::debug(anna::functions::asString("Number of operation parameters: %d", numParams), ANNA_FILE_LOCATION));
-
- if (numParams > 2) {
- LOGWARNING(anna::Logger::warning(my_app.help(), ANNA_FILE_LOCATION));
- throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
- }
-
- Tokenizer::const_iterator tok_iter = params.begin();
- std::string opType = Tokenizer::data(tok_iter);
- std::string param1, param2;
-
- if (numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
-
- if (numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
-
- if (opType == "code") {
- if (numParams != 2)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'code' operation (missing parameter/s)", ANNA_FILE_LOCATION);
-
- 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") {
- if (numParams != 2)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'decode' operation (missing parameter/s)", ANNA_FILE_LOCATION);
-
- char buffer[2048];
- ifstream infile(param1.c_str(), ifstream::in);
- infile >> buffer;
- std::string hexString(buffer, strlen(buffer));
- anna::DataBlock db(true);
- anna::functions::fromHexString(hexString, db);
-
- // Decode
- try { G_codecMsg.decode(db); } 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();
- infile.close();
- } else if ((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
- anna::diameter::comm::Entity *entity = my_app.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") my_app.getMyDiameterEngine()->findClientSession(key)->hide();
-
- if (opType == "show") my_app.getMyDiameterEngine()->findClientSession(key)->show();
-
- if (opType == "hidden") result = my_app.getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
-
- if (opType == "shown") result = my_app.getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
- } else {
- std::string address;
- int port;
- anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
-
- if (opType == "hide") my_app.getMyDiameterEngine()->findServer(address, port)->hide();
-
- if (opType == "show") my_app.getMyDiameterEngine()->findServer(address, port)->show();
-
- if (opType == "hidden") result = my_app.getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
-
- if (opType == "shown") result = my_app.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")) {
- if (numParams != 1)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'sendxml/sendxml2e' operation (missing parameter)", ANNA_FILE_LOCATION);
-
- anna::diameter::comm::Entity *entity = my_app.getEntity();
-
- if (!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
-
- 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());
- bool success = entity->send(G_commMsgSent2e, 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() : "<null client session>"; // esto no deberia ocurrir
- my_app.writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
- }
- } else if ((opType == "burst")) {
- if (numParams < 1)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (missing action parameter)", ANNA_FILE_LOCATION);
-
- anna::diameter::comm::Entity *entity = my_app.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|<source_file> loads the next diameter message into launcher burst.
- // burst|start|<initial load> starts the message sending with a certain initial load.
- // burst|push|<load amount> sends specific non-aynchronous load.
- // burst|stop stops the burst cycle.
- // burst|repeat|[[yes]|no] restarts the burst launch when finish.
- // burst|send|<amount> 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|<order> Updates current burst pointer position.
- // burst|look|<order> Show programmed burst message for order provided.
-
- if (param1 == "clear") {
- result = "Removed ";
- result += anna::functions::asString(my_app.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 = my_app.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 = my_app.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 = my_app.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 = my_app.popBurst(releaseLoad);
-
- if (popped > 0) {
- result = "Burst popped for ";
- result += anna::functions::entriesAsString(popped, "message");
- result += ".";
- }
- } else if (param1 == "stop") {
- int left = my_app.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");
- my_app.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 = my_app.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 = my_app.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 += my_app.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") {
- if (numParams != 1)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'sendxml2c' operation (missing parameter)", ANNA_FILE_LOCATION);
-
- anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
-
- if (!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
-
- 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());
- bool success = localServer->send(G_commMsgSent2c);
-
- // Detailed log:
- if (my_app.logEnabled()) {
- anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
- std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
- my_app.writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
- }
- } else if (opType == "loadxml") {
- if (numParams != 1)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'loadxml' operation (missing parameter)", ANNA_FILE_LOCATION);
-
- G_codecMsg.loadXML(param1);
- std::string xmlString = G_codecMsg.asXMLString();
- std::cout << xmlString << std::endl;
- } else if (opType == "diameterServerSessions") {
- if (numParams != 1)
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'diameterServerSessions' operation (missing parameter)", ANNA_FILE_LOCATION);
-
- int diameterServerSessions = atoi(param1.c_str());
-
- if (!my_app.getDiameterLocalServer())
- my_app.startDiameterServer(diameterServerSessions);
- else
- my_app.getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
- } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
- anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
-
- if (!localServer)
- throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
-
- if (param1 != "") {
- anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
- anna::diameter::codec::Message *message = engine->createMessage(param1);
- LOGDEBUG
- (
- anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
- );
-
- if (message->isRequest())
- throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
-
- int code = message->getId().first;
- reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
-
- if (it != G_reactingAnswers2C.end()) { // found: replace
- LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
- engine->releaseMessage((*it).second);
- }
-
- G_reactingAnswers2C[code] = message;
- } else { // answers query on stdout
- std::cout << my_app.programmedAnswers2c() << std::endl;
- response_content = "Programmed answers dumped on stdout\n";
- return;
- }
- } else if ((opType == "answerxml2e")) {
- anna::diameter::comm::Entity *entity = my_app.getEntity();
-
- if (!entity)
- throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
-
- if (param1 != "") {
- anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
- anna::diameter::codec::Message *message = engine->createMessage(param1);
- LOGDEBUG
- (
- anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
- );
-
- if (message->isRequest())
- throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
-
- int code = message->getId().first;
- reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
-
- if (it != G_reactingAnswers2E.end()) { // found: replace
- LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
- engine->releaseMessage((*it).second);
- }
-
- G_reactingAnswers2E[code] = message;
- } else { // answers query on stdout
- std::cout << my_app.programmedAnswers2e() << std::endl;
- response_content = "Programmed answers dumped on stdout\n";
- return;
- }
- } else {
- LOGWARNING(anna::Logger::warning(my_app.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")) {
- 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") {
- response_content += "Message '";
- response_content += param1;
- response_content += "' sent to client.";
- response_content += "\n";
- } else if (opType == "loadxml") {
- response_content += "Message '";
- response_content += param1;
- response_content += "' loaded.";
- response_content += "\n";
- } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
- response_content += "Answer to client '";
- response_content += param1;
- response_content += "' programmed.";
- response_content += "\n";
- } else if ((opType == "answerxml2e")) {
- response_content += "Answer to entity '";
- response_content += param1;
- response_content += "' programmed.";
- response_content += "\n";
- } else if (opType == "diameterServerSessions") {
- response_content += "Maximum server socket connections updated to '";
- response_content += param1;
- response_content += "'.";
- response_content += "\n";
- }
-}
-
-
-int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
- CommandLine& cl(anna::CommandLine::instantiate());
- std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
-
- 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: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
- 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 <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
- // CommandId:
- anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
- LOGDEBUG
- (
- std::string msg = "Request received: ";
- msg += anna::diameter::functions::commandIdAsPairString(cid);
- msg += " | DiameterServer: ";
- msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
- msg += " | EventTime: ";
- msg += anna::time::functions::currentTimeAsString();
- anna::Logger::debug(msg, ANNA_FILE_LOCATION);
- );
-
- // Write reception
- if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
-
- // Lookup reacting answers list:
- int code = cid.first;
- reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
-
- if (it != G_reactingAnswers2E.end()) {
- anna::diameter::codec::Message *answer_message = (*it).second;
- // Prepare answer:
- my_app.getCommunicator()->prepareAnswer(answer_message, message);
-
- try {
- G_commMsgSent2e.setBody(answer_message->code());
- /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
-
- if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
- } catch (anna::RuntimeException &ex) {
- ex.trace();
-
- if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
- }
- } else { // not found: forward to client (if exists)
- // Forward to client:
- anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
-
- if (localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
- try {
- anna::diameter::comm::Message *msg = G_commMessages.create();
- msg->setBody(message);
- msg->setRequestClientSessionKey(clientSession->getKey());
- bool success = localServer->send(msg);
-
- // Detailed log:
- if (my_app.logEnabled()) {
- anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
- std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // 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 <Launcher&>(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<anna::diameter::comm::Message*>(response.getRequest());
- const anna::DataBlock* message = response.getMessage();
- const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(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.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() : "<null server session>"; // 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 <Launcher&>(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 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 <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
- // CommandId:
- anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
- LOGDEBUG
- (
- std::string msg = "Request received: ";
- msg += anna::diameter::functions::commandIdAsPairString(cid);
- msg += " | DiameterServer: ";
- msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
- msg += " | EventTime: ";
- msg += anna::time::functions::currentTimeAsString();
- anna::Logger::debug(msg, ANNA_FILE_LOCATION);
- );
-
- // Write reception
- if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
-
- // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
- int code = cid.first;
- reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
- bool programmed = (it != G_reactingAnswers2C.end());
- anna::diameter::comm::Entity *entity = my_app.getEntity();
-
- if (!programmed && entity) { // forward condition (no programmed answer + entity available)
- anna::diameter::comm::Message *msg = G_commMessages.create();
- msg->setBody(message);
- msg->setRequestServerSessionKey(serverSession->getKey());
- bool success = entity->send(msg, cl.exists("balance"));
-
- // Detailed log:
- if (my_app.logEnabled()) {
- anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
- anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
- std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // 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 = (*it).second;
- // Prepare answer:
- my_app.getCommunicator()->prepareAnswer(answer_message, message);
- } else return; // nothing done
- }
-
- anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (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);
-}
-
-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 <Launcher&>(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<anna::diameter::comm::Message*>(response.getRequest());
- const anna::DataBlock* message = response.getMessage();
- const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(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() : "<null client session>"; // esto no deberia ocurrir
-
- try {
- 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 <Launcher&>(anna::app::functions::getApp());
- // CommandId:
- anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
- LOGDEBUG
- (
- std::string msg = "Out-of-context response received from client: ";
- msg += anna::diameter::functions::commandIdAsPairString(cid);
- msg += " | DiameterServer: ";
- msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
- msg += " | EventTime: ";
- msg += anna::time::functions::currentTimeAsString();
- anna::Logger::debug(msg, ANNA_FILE_LOCATION);
- );
-
- if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
-}
-
-
-anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
-throw() {
- anna::xml::Node* result = parent->createChild("launcher");
- anna::comm::Application::asXML(result);
- // Timming:
- result->createAttribute("StartTime", a_start_time.asString());
- result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
- // Diameter:
- (anna::functions::component <anna::diameter::codec::Engine> (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;
-}
-