// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
+// Standard
+#include <sstream> // std::istringstream
+#include <iostream> // std::cout
+#include <math.h> // ceil
+#include <climits>
+#include <unistd.h> // chdir
+//#include <regex> TODO: use this from gcc4.9.0: http://stackoverflow.com/questions/8060025/is-this-c11-regex-error-me-or-the-compiler
+#include <stdio.h>
+
// Project
+#include <anna/timex/Engine.hpp>
#include <anna/statistics/Engine.hpp>
+#include <anna/diameter/codec/functions.hpp>
#include <anna/diameter/codec/Engine.hpp>
+#include <anna/diameter/codec/EngineManager.hpp>
#include <anna/http/Transport.hpp>
#include <anna/diameter/stack/Engine.hpp>
#include <anna/diameter/helpers/base/functions.hpp>
-#include <anna/diameter/helpers/dcca/functions.hpp>
#include <anna/time/functions.hpp>
#include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
+#include <anna/testing/defines.hpp>
+#include <anna/xml/xml.hpp>
+#include <anna/diameter.comm/OriginHost.hpp>
+#include <anna/diameter.comm/OriginHostManager.hpp>
// Process
-#include "Launcher.hpp"
-
+#include <Launcher.hpp>
+#include <Procedure.hpp>
+#include <EventOperation.hpp>
+#include <MyDiameterEngine.hpp>
+#include <anna/testing/TestManager.hpp>
+#include <anna/testing/TestCase.hpp>
+
+
+#define SIGUSR2_TASKS_INPUT_FILENAME "sigusr2.in"
+#define SIGUSR2_TASKS_OUTPUT_FILENAME "sigusr2.out"
+
+
+const char *ServicesDTD = "\
+<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
+<!-- Diameter services DTD -->\n\
+\n\
+<!ELEMENT services ((stack*, node*)|(node*, stack*))>\n\
+\n\
+<!ELEMENT stack EMPTY>\n\
+<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED validationMode (BeforeEncoding | AfterDecoding | Always | Never) #IMPLIED validationDepth (Complete | FirstError) #IMPLIED fixMode (BeforeEncoding | AfterDecoding | Always | Never) #IMPLIED ignoreFlagsOnValidation (yes | no) #IMPLIED>\n\
+<!--\n\
+ Stack record\n\
+\n\
+ id: Normally the id corresponds to the Application-Id for which the dictionary provided is designed\n\
+ (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
+ for processed messages).\n\
+ dictionary: Path to the dictionary file.\n\
+ validationMode: Sets the validation mode. Default is 'AfterDecoding'.\n\
+ validationDepth: Sets the validation depth. Default is 'FirstError'.\n\
+ fixMode: Sets the fix mode. Default is 'BeforeEncoding'.\n\
+ ignoreFlagsOnValidation: Ignore flags during message validation. Default is 'no'.\n\
+-->\n\
+\n\
+<!ELEMENT node EMPTY>\n\
+<!ATTLIST node originHost CDATA #REQUIRED applicationId CDATA #REQUIRED originRealm CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED cea CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>\n\
+<!--\n\
+ Node record\n\
+\n\
+ originHost: Node identifier as diameter application host name.\n\
+ applicationId: The Application-Id provided must exists as a registered 'stack id'.\n\
+ originRealm: Origin-Realm (domain-name internally used by default).\n\
+\n\
+\n\
+ - Diameter clients:\n\
+\n\
+ entity: Target diameter entity (comma-separated '<address>:<port>' format).\n\
+ For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled.\n\
+ entityServerSessions: Diameter entity server sessions (0: diameter entity disabled). Default value of 1.\n\
+ cer: User defined CER path file to be encoded to establish diameter connections.\n\
+ If missing, will be harcoded.\n\
+ dwr: User defined DWR path file to be encoded for diameter protocol keep alive.\n\
+ If missing, will be harcoded.\n\
+ tcpConnectDelay: Milliseconds to wait TCP connect to any server. If missing, default value of 200 will\n\
+ be assigned\n\
+ ceaTimeout: Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'\n\
+ will be assigned.\n\
+ watchdogPeriod: Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default\n\
+ value of 30000 will be assigned.\n\
+ balance: Balance over entity servers instead of doing standard behaviour (first primary, secondary\n\
+ if fails, etc.). Default value 'no'.\n\
+ sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part\n\
+ will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR\n\
+ analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;\n\
+ usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart').\n\
+\n\
+\n\
+ - Diameter servers:\n\
+\n\
+ diameterServer: Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.\n\
+ If missing, no local server will be enabled.\n\
+ diameterServerSessions: Diameter own server available connections (0: diameter server disabled). Default value of 1.\n\
+ Negative value implies no limit accepting incoming connections.\n\
+ cea: User defined CEA path file to be encoded to answer client CERs.\n\
+ If missing, will be harcoded.\n\
+ allowedInactivityTime: Milliseconds for the maximum allowed inactivity time on server sessions born over the\n\
+ local server before being reset. If missing, default value of 90000 will be assigned.\n\
+\n\
+\n\
+ - General:\n\
+\n\
+ answersTimeout: Milliseconds to wait pending application answers from diameter peers. If missing,\n\
+ default value of 10000 will be assigned.\n\
+ retries: Expired responses will cause a number of request retransmissions. Disabled by default (0 retries).\n\
+ log: Process log file (operations result, traffic log, etc.). By default '<originHost>.launcher.log'.\n\
+ Empty string or \"null\" name, to disable. Warning: there is no rotation for log files\n\
+ (use logrotate or whatever you consider).\n\
+ splitLog: Splits log file (appends to log filename, extensions with the type of event.\n\
+ (Check 'HELP.md' for more information). No log files for code/decode and load operations are created.\n\
+ Default value 'no'.\n\
+ detailedLog: Insert detailed information at log files (timestamps, communication resources, etc.). Useful\n\
+ to analyze the messages flow along the sockets (specially on 'balance' mode). Default 'no'.\n\
+ dumpLog: Write to disk every incoming/outcoming message named as:\n\
+ '<unix ms timestamp>.<originHost>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'\n\
+ Default value 'no'.\n\
+ burstLog: Burst operations log file. By default '<originHost>.launcher.burst'. Empty string or \"null\" name, to disable.\n\
+ Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each\n\
+ burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst\n\
+ list size, plus OTA requests when changed.\n\
+\n\
+-->\n\
+\n\
+";
-#define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
-#define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
-#define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine"
Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
- a_myDiameterEngine = new MyDiameterEngine();
- a_myDiameterEngine->setRealm("ADL.ericsson.com");
- a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
- a_logFile = "launcher.log";
- a_burstLogFile = "launcher.burst";
- a_splitLog = false;
- a_detailedLog = false;
- a_dumpLog = false;
a_timeEngine = NULL;
a_counterRecorder = NULL;
+ a_admlMinResolution = 2 * anna::timex::Engine::minResolution; // 2*10 = 20 ms; 1000/20 = 50 ticks per second;
+ //a_admlMinResolution = (anna::Millisecond)100;
a_counterRecorderClock = NULL;
- a_entity = NULL;
- a_diameterLocalServer = NULL;
- a_cerPathfile = "cer.xml";
- a_dwrPathfile = "dwr.xml";
- // Burst
- a_burstCycle = 1;
- a_burstRepeat = false;
- a_burstActive = false;
- a_burstLoadIndx = 0;
- a_burstDeliveryIt = a_burstMessages.begin();
- a_otaRequest = 0;
- a_burstPopCounter = 0;
+
+ a_workingNode = NULL;
+ a_operatedHost = NULL;
+
+ a_httpServerSocket = NULL;
}
-anna::diameter::comm::Message *Launcher::createCommMessage() throw(anna::RuntimeException) {
- return a_commMessages.create();
+
+std::string Launcher::getSignalUSR2InputFile() const {
+ return (getInitialWorkingDirectory() + "/" + SIGUSR2_TASKS_INPUT_FILENAME);
}
-void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
- a_commMessages.release(msg);
+std::string Launcher::getSignalUSR2OutputFile() const {
+ return (getInitialWorkingDirectory() + "/" + SIGUSR2_TASKS_OUTPUT_FILENAME);
}
-void Launcher::baseProtocolSetupAsClient(anna::diameter::codec::Engine *codecEngine) throw(anna::RuntimeException) {
- // Build CER
- // <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(codecEngine);
- 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;
- }
+void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool bindResources) noexcept(false) {
- 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|<ip address>"
- 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);
- }
+ CommandLine& cl(anna::CommandLine::instantiate());
+ bool allLogsDisabled = cl.exists("disableLogs");
- // Build DWR
- // <DWR> ::= < Diameter Header: 280, REQ >
- // { Origin-Host }
- // { Origin-Realm }
- anna::diameter::codec::Message diameterDWR(codecEngine);
- loadingError = false;
+ //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
+ const anna::xml::Attribute *id, *dictionary;
- try {
- diameterDWR.loadXML(a_dwrPathfile);
- } catch(anna::RuntimeException &ex) {
- //ex.trace();
- loadingError = true;
+ // <!ATTLIST node originHost CDATA #REQUIRED applicationId CDATA #REQUIRED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
+ const anna::xml::Attribute *originHost, *appId, *originRealm, *cer, *dwr, *cea, *allowedInactivityTime, *tcpConnectDelay,
+ *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
+ *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
+ *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
+ // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
+
+ // Stacks
+ anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
+ anna::diameter::stack::Dictionary *d;
+ const anna::diameter::stack::Dictionary *bpd = NULL; // base protocol dictionary
+
+ // Codec engine manager:
+ anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
+ anna::diameter::codec::Engine *ce;
+
+ ///////////////////////////////////////////
+ // APPLICATION MESSAGE OAM MODULE SCOPES //
+ ///////////////////////////////////////////
+ // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
+ anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
+ appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
+ static int scope_id = 3 + appMsgOamModule.scopes();
+
+ unsigned int id_value;
+ std::string codecEngineName;
+
+ for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
+ std::string nodeName = (*it)->getName();
+
+ if(nodeName == "stack") {
+ // Input data:
+ id = (*it)->getAttribute("id");
+ dictionary = (*it)->getAttribute("dictionary");
+ id_value = id->getIntegerValue();
+
+ if (stackEngine.getDictionary(id_value)) { // Ignore (but don't fail) dictionary load with same stack id already registered
+ LOGWARNING(anna::Logger::warning(anna::functions::asString("Ignore dictionary load for stack id already registered: %llu", id_value), ANNA_FILE_LOCATION));
+ // Delta loads, in case we provide base protocol already registered (comm::Engine will need 'bpd')
+ if (id_value == 0)
+ bpd = stackEngine.getDictionary(0);
+ continue;
+ }
+
+ try {
+ d = stackEngine.createDictionary(id_value, dictionary->getValue());
+ LOGDEBUG(anna::Logger::debug(anna::functions::asString("Created dictionary (%p) for stack id %llu", d, id_value), ANNA_FILE_LOCATION));
+
+ // OAM module for counters:
+ appMsgOamModule.createStackCounterScope(scope_id, id_value /* application-id */);
+ scope_id++;
+
+ } catch(anna::RuntimeException &ex) {
+ //_exit(ex.asString());
+ throw ex;
+ }
+
+ bpd = d; // base protocol dictionary in case of monostack. If multistack, will be calculated later
+
+ // Create codec engine and register it in the codec engine manager:
+ codecEngineName = anna::functions::asString("CodecEngineForStackId_%llu", id_value);
+ ce = new anna::diameter::codec::Engine(codecEngineName.c_str(), d);
+ em.registerCodecEngine(id_value, ce);
+
+ // Codec engine configuration:
+ const anna::xml::Attribute *vm_attr = (*it)->getAttribute("validationMode", false /* no exception */);
+ const anna::xml::Attribute *vd_attr = (*it)->getAttribute("validationDepth", false /* no exception */);
+ const anna::xml::Attribute *fm_attr = (*it)->getAttribute("fixMode", false /* no exception */);
+ const anna::xml::Attribute *if_attr = (*it)->getAttribute("ignoreFlagsOnValidation", false /* no exception */);
+
+ std::string vm_value = vm_attr ? vm_attr->getValue() : "AfterDecoding";
+ std::string vd_value = vd_attr ? vd_attr->getValue() : "FirstError";
+ std::string fm_value = fm_attr ? fm_attr->getValue() : "BeforeEncoding";
+
+ anna::diameter::codec::Engine::ValidationMode::_v vm;
+ if (vm_value == "BeforeEncoding") vm = anna::diameter::codec::Engine::ValidationMode::BeforeEncoding;
+ else if (vm_value == "AfterDecoding") vm = anna::diameter::codec::Engine::ValidationMode::AfterDecoding;
+ else if (vm_value == "Always") vm = anna::diameter::codec::Engine::ValidationMode::Always;
+ else if (vm_value == "Never") vm = anna::diameter::codec::Engine::ValidationMode::Never;
+ ce->setValidationMode(vm);
+
+ anna::diameter::codec::Engine::ValidationDepth::_v vd;
+ if (vd_value == "Complete") vd = anna::diameter::codec::Engine::ValidationDepth::Complete;
+ else if (vd_value == "FirstError") vd = anna::diameter::codec::Engine::ValidationDepth::FirstError;
+ ce->setValidationDepth(vd);
+
+ anna::diameter::codec::Engine::FixMode::_v fm;
+ if (fm_value == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
+ else if (fm_value == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
+ else if (fm_value == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
+ else if (fm_value == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
+ ce->setFixMode(fm);
+
+ bool if_value = (if_attr ? (if_attr->getValue() == "yes") : false);
+ ce->ignoreFlagsOnValidation(if_value);
+ }
}
- 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);
+ // Show loaded stacks:
+ std::cout << "Stacks currently loaded:" << std::endl;
+ std::cout << anna::functions::tab(stackEngine.asString(false /* light */)) << std::endl;
+
+ // Basic checking for multistack:
+ bool multistack = (stackEngine.stack_size() > 1);
+ if (multistack) {
+ bpd = stackEngine.getDictionary(0);
+ if(!bpd)
+ throw anna::RuntimeException("In multistack applications is mandatory register a stack id = 0 using a dictionary which contains the needed elements to build base protocol messages (CER/A, DWR/A, DPR/A, STR/A, etc.)", ANNA_FILE_LOCATION);
}
- // Assignment for CER/DWR and CEA/DWA:
- a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
- //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
-}
+ // REALMS:
+ for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
+ std::string nodeName = (*it)->getName();
+
+ if(nodeName == "node") {
+ // Input data:
+ originHost = (*it)->getAttribute("originHost");
+ appId = (*it)->getAttribute("applicationId");
+ originRealm = (*it)->getAttribute("originRealm", false /* no exception */);
+ cer = (*it)->getAttribute("cer", false /* no exception */);
+ dwr = (*it)->getAttribute("dwr", false /* no exception */);
+ cea = (*it)->getAttribute("cea", false /* no exception */);
+ allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */);
+ tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */);
+ answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */);
+ ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */);
+ watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */);
+ entity = (*it)->getAttribute("entity", false /* no exception */);
+ entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */);
+ diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */);
+ diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */);
+ balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no)
+ sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin)
+ retries = (*it)->getAttribute("retries", false /* no exception */);
+ log = (*it)->getAttribute("log", false /* no exception */);
+ splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no)
+ detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no)
+ dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no)
+ burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no)
+
+ // Basic checkings:
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ anna::diameter::comm::OriginHost *oh = ohm.getOriginHost(originHost->getValue());
+ if (oh) {
+ std::string msg = "Already registered such Origin-Host: "; msg += originHost->getValue();
+ throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
+ }
-void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail, anna::diameter::codec::Engine *codecEngine) const throw() {
-// if (!logEnabled()) return;
- anna::diameter::codec::Message codecMsg(codecEngine);
- try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
- writeLogFile(codecMsg, logExtension, detail);
+ unsigned int applicationId = appId->getIntegerValue();
+ if (!stackEngine.getDictionary(applicationId)) {
+ std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
+ throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
+ }
+
+ // Engine time measures checking & assignment:
+ anna::Millisecond allowedInactivityTimeMs(90000);
+ anna::Millisecond tcpConnectDelayMs(200);
+ anna::Millisecond answersTimeoutMs(10000);
+ anna::Millisecond ceaTimeoutMs(10000);
+ anna::Millisecond watchdogPeriodMs(30000);
+
+ if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue());
+ if (tcpConnectDelay) tcpConnectDelayMs = checkTimeMeasure("tcpConnectDelay", tcpConnectDelay->getValue());
+ if (answersTimeout) answersTimeoutMs = checkTimeMeasure("answersTimeout", answersTimeout->getValue());
+ if (ceaTimeout) ceaTimeoutMs = checkTimeMeasure("ceaTimeout", ceaTimeout->getValue());
+ if (watchdogPeriod) watchdogPeriodMs = checkTimeMeasure("watchdogPeriod", watchdogPeriod->getValue());
+
+ // Checking command line parameters
+ std::string sessionBasedModelsType;
+ anna::diameter::comm::Entity::SessionBasedModelsType::_v sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdLowPart;
+ if(sessionBasedModelsClientSocketSelection) {
+ sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue();
+ if (sessionBasedModelsType == "RoundRobin") {
+ sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::RoundRobin;
+ }
+ else if (sessionBasedModelsType == "SessionIdOptionalPart") {
+ sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdOptionalPart;
+ }
+ else if (sessionBasedModelsType == "SessionIdHighPart") {
+ sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdHighPart;
+ }
+ else if (sessionBasedModelsType == "SessionIdLowPart") {
+ sessionBasedModelsTypeEnum = anna::diameter::comm::Entity::SessionBasedModelsType::SessionIdLowPart;
+ }
+ else {
+ throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdLowPart'/'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
+ }
+ }
+
+ int retransmissions = retries ? retries->getIntegerValue() : 0;
+ if(retransmissions < 0) {
+ throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION);
+ }
+
+ /////////////////////////////////////////////////////////////////////////////////////////////
+ // Diameter communication engine: ONE ENGINE PER OWN ORIGIN HOST
+ std::string commEngineName = originHost->getValue() + "_DiameterCommEngine";
+ MyDiameterEngine *commEngine = new MyDiameterEngine(commEngineName.c_str(), bpd);
+ commEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
+ commEngine->setMaxConnectionDelay(tcpConnectDelayMs);
+ commEngine->setWatchdogPeriod(watchdogPeriodMs);
+ commEngine->setOriginHostName(originHost->getValue());
+ if (originRealm) commEngine->setOriginRealmName(originRealm->getValue());
+
+ // Origin host node:
+ a_workingNode = new anna::diameter::comm::OriginHost((anna::diameter::comm::Engine*)commEngine, applicationId /* OriginHost constructor extracts corresponding stack codec engine */);
+ a_workingNode->setRequestRetransmissions(retransmissions);
+ /////////////////////////////////////////////////////////////////////////////////////////////
+
+
+ // Diameter entity:
+ if(entity) {
+ int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1;
+
+ if(sessions > 0) {
+ // Number of sessions:
+ commEngine->setNumberOfClientSessionsPerServer(sessions);
+
+ // Client CER and DWR
+ if (cer) { // pathfile provided
+ commEngine->setClientCER(cer->getValue());
+ }
+ else {
+ commEngine->setClientCER(applicationId); // default engine CER
+ }
+ commEngine->setClientDWR(dwr ? dwr->getValue() : "" /* default DWR */);
+
+ // Register one entity for this engine:
+ a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs);
+ a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsTypeEnum);
+ a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings
+ if (bindResources) a_workingNode->getEntity()->bind();
+ }
+ }
+
+ // Diameter Server:
+ if(diameterServer) {
+ // Server CEA
+ std::string ceaPathfile = cea ? cea->getValue() : "";
+
+ int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1;
+ a_workingNode->createDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs, answersTimeoutMs, ceaPathfile);
+ }
+
+ // Logs:
+ if (!allLogsDisabled) {
+ std::string host = commEngine->getOriginHostName();
+ std::string s_log = host + ".launcher.log"; if (log) s_log = log->getValue();
+ bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false);
+ bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false);
+ bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false);
+ std::string s_burstLog = host + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue();
+ a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog);
+ }
-}
-// 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;
+ // Lazy initialization for comm engine:
+ if (bindResources) commEngine->lazyInitialize();
- if(a_splitLog) {
- targetFile += ".";
- targetFile += logExtension;
+ // Node and Codec Engine registration ///////////////////////////////////////////////////////
+ ohm.registerOriginHost(originHost->getValue(), a_workingNode);
+ /////////////////////////////////////////////////////////////////////////////////////////////
+ }
}
- std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app);
- // Set text to dump:
- std::string title = "[";
- title += logExtension;
- title += "]";
- // Build complete log:
- std::string log = "\n";
- std::string xml = decodedMessage.asXMLString();
-
-
- if(a_detailedLog) {
- anna::time::Date now;
- now.setNow();
- title += " ";
- title += now.asString();
- log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
- log += xml;
- log += "\n";
- log += anna::functions::highlight("Used resource");
- log += detail;
- log += "\n";
- } else {
- log += title;
- log += "\n";
- log += xml;
- log += "\n";
+ if (!uniqueOriginHost())
+ a_workingNode = NULL; // by default, mode auto
+
+ // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started,
+ // but this don't care because application startComponents() -> initialize() -> do_initialize() -> do nothing.
+ // And when stopped, running state is not checked and it will be stopped anyway.
+}
+
+
+void Launcher::loadServicesFromFile(const std::string & xmlPathFile, bool bindResources) noexcept(false) {
+
+ if (xmlPathFile == "null" || xmlPathFile == "") {
+ LOGWARNING(anna::Logger::warning("Ignoring services configuration on start: empty or 'null' string provided as xml file. Use management interface (operation 'services') in order to add services", ANNA_FILE_LOCATION));
+ return;
}
- if(a_dumpLog) {
- std::string name = anna::functions::asString(decodedMessage.getHopByHop());
- name += ".";
- name += anna::functions::asString(decodedMessage.getEndToEnd());
- name += ".";
- name += anna::functions::asString(decodedMessage.getId().first);
- name += ".";
- name += ((decodedMessage.getId().second) ? "request.":"answer.");
- name += logExtension;
- name += ".xml";
- std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app);
- outMsg.write(xml.c_str(), xml.size());
- outMsg.close();
+ LOGDEBUG(
+ std::string trace = "Loading ADML services file '";
+ trace += xmlPathFile;
+ trace += "'";
+ anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+ );
+ anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
+ anna::xml::DTDMemory xmlDTD;
+ const anna::xml::Node *rootNode;
+ xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
+ xmlDTD.initialize(ServicesDTD);
+ try {
+ rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
+ }
+ catch (anna::RuntimeException &ex) {
+ LOGWARNING(
+ std::string msg = "Services DTD schema:\n\n";
+ msg += ServicesDTD;
+ anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+ );
+ throw ex;
}
- // Write and close
- out.write(log.c_str(), log.size());
- out.close();
+ LOGDEBUG(
+ std::string trace = "Loaded XML file (";
+ trace += xmlPathFile;
+ trace += "):\n";
+ trace += anna::xml::Compiler().apply(rootNode);
+ anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+ );
+ servicesFromXML(rootNode, bindResources);
}
-void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
- std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app);
- out.write(buffer.c_str(), buffer.size());
- out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
- // you'd call close() only if you indeed for some reason wanted to close the filestream
- // earlier than it goes out of scope.
-}
-void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
- CommandLine& cl(anna::CommandLine::instantiate());
+void Launcher::loadServicesFromXMLString(const std::string & xmlString, bool bindResources) noexcept(false) {
- if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory
+ anna::xml::DocumentMemory xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
+ anna::xml::DTDMemory xmlDTD;
+ const anna::xml::Node *rootNode;
+ xmlDocument.initialize(xmlString.c_str());
+ xmlDTD.initialize(ServicesDTD);
+ try {
+ rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
+ }
+ catch (anna::RuntimeException &ex) {
+ LOGWARNING(
+ std::string msg = "Services DTD schema:\n\n";
+ msg += ServicesDTD;
+ anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+ );
+ throw ex;
+ }
- std::string parameter = cl.getValue(commandLineParameter);
+ LOGDEBUG(
+ std::string trace = "Loaded XML String:\n";
+ trace += anna::xml::Compiler().apply(rootNode);
+ anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+ );
+ servicesFromXML(rootNode, bindResources);
+}
+
+
+anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const std::string &value) noexcept(false) {
- if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
- int msecs = cl.getIntegerValue(commandLineParameter);
+ if(anna::functions::isLike("^[0-9]+$", value)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
+ int msecs;
+ std::istringstream ( value ) >> msecs;
if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
- std::string msg = "Commandline parameter '";
- msg += commandLineParameter;
- msg += "' is greater than allowed max timeout for timming engine: ";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: ";
msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
throw RuntimeException(msg, ANNA_FILE_LOCATION);
}
if(msecs > 300000) {
- std::string msg = "Commandline parameter '";
- msg += commandLineParameter;
- msg += "' is perhaps very big (over 5 minutes). Take into account memory consumption issues.";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes).";
LOGWARNING(anna::Logger::warning(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: ";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: ";
msg += anna::functions::asString(a_timeEngine->getResolution());
throw RuntimeException(msg, ANNA_FILE_LOCATION);
}
- return; // ok
+ return (anna::Millisecond)msecs; // ok
}
- // Excepcion (por no ser entero):
- std::string msg = "Error at commandline parameter '";
- msg += commandLineParameter;
- msg += "' = '";
+ // Non-integer exception:
+ std::string msg = "Configuration error for '";
msg += parameter;
+ msg += "' = '";
+ msg += value;
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;
+bool Launcher::setWorkingNode(const std::string &name) {
+ bool result = false;
- std::string address;
- int port;
- CommandLine& cl(anna::CommandLine::instantiate());
- anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
- //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
- a_diameterLocalServer = (MyLocalServer*)(a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions));
- a_diameterLocalServer->setDescription("Launcher diameter local server");
- a_diameterLocalServer->setCodecEngine(getCodecEngine()); // this is for automatic answers (failed-avp) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX el del nodo correspondiente
- int allowedInactivityTime = 90000; // ms
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ anna::diameter::comm::OriginHost *oh = ohm.getOriginHost(name);
+
+ if (oh) {
+ a_workingNode = const_cast<anna::diameter::comm::OriginHost*>(oh);
+ result = true;
+ }
+
+ return result;
+}
+
+anna::diameter::comm::OriginHost *Launcher::getOriginHost(const std::string &name) const noexcept(false) {
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ anna::diameter::comm::OriginHost *result = ohm.getOriginHost(name);
+
+ if (!result)
+ throw anna::RuntimeException(anna::functions::asString("There is no origin host registered as '%s' (set Origin-Host avp correctly or force a specific host with 'node' operation)", name.c_str()), ANNA_FILE_LOCATION);
+
+ return result;
+}
+
+anna::diameter::comm::OriginHost *Launcher::getOriginHost(const anna::diameter::codec::Message &message) const noexcept(false) {
+ std::string originHost = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
+ return (getOriginHost(originHost));
+}
+
+anna::diameter::comm::OriginHost *Launcher::getOriginHost(const anna::DataBlock &messageDataBlock) const noexcept(false) {
+ std::string originHost = anna::diameter::helpers::base::functions::getOriginHost(messageDataBlock);
+ return (getOriginHost(originHost));
+}
+
+bool Launcher::uniqueOriginHost() const {
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ return (ohm.size() == 1);
+}
+
+void Launcher::updateOperatedOriginHostWithMessage(const anna::diameter::codec::Message &message) noexcept(false) {
+ if (!a_operatedHost) // priority for working node by mean 'node' operation
+ a_operatedHost = getOriginHost(message);
+}
+
+void Launcher::updateOperatedOriginHostWithMessage(const anna::DataBlock &messageDataBlock) noexcept(false) {
+ if (!a_operatedHost) // priority for working node by mean 'node' operation
+ a_operatedHost = getOriginHost(messageDataBlock);
+}
+
+anna::diameter::comm::OriginHost *Launcher::getWorkingNode() const noexcept(false) {
+ if(!a_workingNode)
+ throw anna::RuntimeException("Working node not identified (try to load services)", ANNA_FILE_LOCATION);
+
+ return a_workingNode;
+}
+
+anna::diameter::comm::OriginHost *Launcher::getOperatedHost() const noexcept(false) {
+ if(!a_operatedHost)
+ throw anna::RuntimeException("Node not identified (try to force a specific Origin-Host with 'node' operation)", ANNA_FILE_LOCATION);
- if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
+ return a_operatedHost;
+}
+
+void Launcher::setOperatedHost(anna::diameter::comm::OriginHost *op) {
+ a_operatedHost = op;
+}
+
+MyDiameterEntity *Launcher::getOperatedEntity() const noexcept(false) {
+ MyDiameterEntity *result = (MyDiameterEntity *)(getOperatedHost()->getEntity());
+ if (!result)
+ throw anna::RuntimeException("No entity configured for the operated node", ANNA_FILE_LOCATION);
+ return result;
+}
+
+MyLocalServer *Launcher::getOperatedServer() const noexcept(false) {
+ MyLocalServer *result = (MyLocalServer *)(getOperatedHost()->getDiameterServer());
+ if (!result)
+ throw anna::RuntimeException("No local server configured for the operated node", ANNA_FILE_LOCATION);
+ return result;
+}
- a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
+MyDiameterEngine *Launcher::getOperatedEngine() const noexcept(false) {
+ return (MyDiameterEngine *)getOperatedHost()->getCommEngine(); // never will be NULL
}
void Launcher::initialize()
-throw(anna::RuntimeException) {
+noexcept(false) {
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)600000, (anna::Millisecond)150);
- // Counters record procedure:
- anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
+ a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, a_admlMinResolution);
+ anna::testing::TestManager::instantiate().setTimerController(a_timeEngine);
- if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
+ // Counters record procedure:
+ const char *varname = "cntRecordPeriod";
+ anna::Millisecond cntRecordPeriod;
+ try {
+ cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000;
+ }
+ catch(anna::RuntimeException &ex) {
+ if (cntRecordPeriod != 0) throw ex;
+ }
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()));
}
+
+ // Testing framework:
+ std::string tmDir = ".";
+ if(cl.exists("tmDir")) tmDir = cl.getValue("tmDir");
+ anna::testing::TestManager::instantiate().setReportsDirectory(tmDir);
+
+ // Tracing:
+ if(cl.exists("trace"))
+ anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
+
+ // Load launcher services:
+ loadServicesFromFile(cl.getValue("services"), false /* no bind at the moment */); // before run (have components to be created)
}
void Launcher::run()
-throw(anna::RuntimeException) {
+noexcept(false) {
LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
CommandLine& cl(anna::CommandLine::instantiate());
+ anna::diameter::stack::Engine::instantiate();
+
// Start time:
a_start_time.setNow();
- // Statistics:
- anna::statistics::Engine::instantiate().enable();
-
- // 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);
- }
- }
+ // Initial working directory:
+ char cwd[1024];
+ if (getcwd(cwd, sizeof(cwd)) == NULL)
+ throw anna::RuntimeException("Cannot retrieve initial working directory !!", ANNA_FILE_LOCATION);
+ a_initialWorkingDirectory = cwd;
- // Tracing:
- if(cl.exists("trace"))
- anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
+ // Statistics:
+ anna::statistics::Engine::instantiate().enable();
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);
+ // Test messages dtd:
+ std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n";
+ msg += anna::diameter::codec::MessageDTD;
+ anna::Logger::information(msg, ANNA_FILE_LOCATION);
);
// HTTP Server:
a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
}
- // Stack:
- a_codecEngine = new anna::diameter::codec::Engine(DIAMETER_CODEC_ENGINE_NAME_PREFIX);
- 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);
- }
- }
-
- getCodecEngine()->setDictionary(d); // XXXX esto cambiara...
- LOGDEBUG(anna::Logger::debug(getCodecEngine()->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;
- }
-
///////////////////////////////
// Diameter library COUNTERS //
///////////////////////////////
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);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmitted, "", 58);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnClientSession, "", 59);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnServerSession, "", 60);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 61);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 62);
+ oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 63);
//////////////////
// CODEC MODULE //
//////////////////
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*/);
- ///////////////////////////////////////////
- // APPLICATION MESSAGE OAM MODULE SCOPES //
- ///////////////////////////////////////////
- // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
- anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
- int scope_id = 3;
- for (anna::diameter::stack::Engine::const_stack_iterator it = stackEngine.stack_begin(); it != stackEngine.stack_end(); it++) {
- appMsgOamModule.createStackCounterScope(scope_id, it->first);
- scope_id++;
- }
- appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
/////////////////////////////////
if(a_counterRecorderClock) {
oamDiameterComm.setCounterRecorder(a_counterRecorder);
oamDiameterCodec.setCounterRecorder(a_counterRecorder);
- appMsgOamModule.setCounterRecorder(a_counterRecorder);
+ anna::diameter::comm::ApplicationMessageOamModule::instantiate().setCounterRecorder(a_counterRecorder);
a_timeEngine->activate(a_counterRecorderClock); // start clock
}
-
- // 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")) {
- getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // XXXXXXXXXXXXXXXXXXXXXXXXX
- getCodecEngine()->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));
- getCodecEngine()->setFixMode(fm); // XXXXXXXXXXXXXXXXXXXXXXX
- }
-
- getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); // XXXXXXXXXXXXXXXXXXXXXXX
-
- // 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(getCodecEngine()); // Same CER/CEA, DWR/DWA for all diameter servers XXXXXXXXXXXXXXXXXXXXXXXXX
- anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
- a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
- a_entity = (MyDiameterEntity*)(a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"));
- a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
- a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
- a_entity->setCodecEngine(getCodecEngine()); // XXXXXXXXXXXXXXXXXXXXXXX
- 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));
- }
- }
- }
+ /////////////////////////////
+ // Log statistics concepts //
+ /////////////////////////////
+ if(cl.exists("logStatisticSamples"))
+ logStatisticsSamples(cl.getValue("logStatisticSamples"));
+
+ // Start client connections //////////////////////////////////////////////////////////////////////////////////
+ MyDiameterEntity *entity;
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ for (diameter::comm::origin_hosts_it it = ohm.begin(); it != ohm.end(); it++) {
+ entity = (MyDiameterEntity *)(it->second->getEntity());
+ if (entity) entity->bind();
}
- a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
+ // Go into communicator poll
+ // Reconnection period (tcp reconnect retry time):
+ const char *varname = "reconnectionPeriod";
+ anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000;
+ a_communicator->setRecoveryTime(reconnectionPeriod);
if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
-
a_communicator->accept();
}
-bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
+bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const noexcept(false) {
// Get hex string
static char buffer[8192];
std::ifstream infile(pathfile.c_str(), std::ifstream::in);
// 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);
+ std::string msg = "Hex string (remove colons if exists): ";
+ msg += hexString;
+ anna::Logger::debug(msg, ANNA_FILE_LOCATION);
);
- anna::functions::fromHexString(hexString, db);
+
+ anna::functions::fromHexString(hexString, db); // could launch exception
// Close file
infile.close();
return true;
return false;
}
-int Launcher::clearBurst() throw() {
- int size = a_burstMessages.size();
-
- if(size) {
- std::map<int, anna::diameter::comm::Message*>::const_iterator it;
- std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
- std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
-
- for(it = it_min; it != it_max; it++) releaseCommMessage((*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 = createCommMessage();
- 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;
- }
- }
+void Launcher::resetStatistics() {
+ if (a_workingNode) {
+ a_workingNode->getCommEngine()->resetStatistics();
}
-
- 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));
- }
+ else {
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ for (diameter::comm::origin_hosts_it it = ohm.begin(); it != ohm.end(); it++) {
+ it->second->getCommEngine()->resetStatistics();
}
}
-
- // 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() : "<null client session>"; // esto no deberia ocurrir
- writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail, getCodecEngine()); // el del nodo de trabajo
- }
-
- 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<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
-
- if(it != a_burstMessages.end()) {
- // Decode
- anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXXXX el del nodo de trabajo
- try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
- result = codecMsg.asXMLString();
- }
-
- return result;
+void Launcher::resetCounters() {
+ anna::diameter::comm::OamModule::instantiate().resetCounters();
+ anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
+ anna::diameter::codec::OamModule::instantiate().resetCounters();
}
-std::string Launcher::gotoBurst(int order) throw() {
- std::string result = "Position not found for order provided (";
- std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
+void Launcher::signalTerminate() noexcept(false) {
+ LOGMETHOD(anna::TraceMethod tm("Launcher", "signalTerminate", ANNA_FILE_LOCATION));
- if(it != a_burstMessages.end()) {
- a_burstDeliveryIt = it;
- result = "Position updated for order provided (";
- }
+ forceCountersRecord();
- result += anna::functions::asString(order);
- result += ")";
- return result;
+ a_communicator->terminate ();
+ comm::Application::signalTerminate ();
}
-void Launcher::resetCounters() throw() {
- anna::diameter::comm::OamModule::instantiate().resetCounters();
- anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
- anna::diameter::codec::OamModule::instantiate().resetCounters();
-}
+void Launcher::signalUSR2() noexcept(false) {
+
+ std::string inputFile = getSignalUSR2InputFile();
+ std::string outputFile = getSignalUSR2OutputFile();
-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);
+ std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
+ msg += inputFile;
+ msg += "' (results will be written at '";
+ msg += outputFile;
+ 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);
+ std::ifstream in_file(inputFile);
+ std::ofstream out_file(outputFile);
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)) {
+
+ // Ignore comments and blank lines:
+ if (line[0] == '#') continue;
+ if (std::string::npos == line.find_first_not_of(" \t")) continue;
+
LOGDEBUG(
- std::string msg = "Processing line: ";
- msg += line;
- anna::Logger::debug(msg, ANNA_FILE_LOCATION);
+ std::string msg = "Processing line: ";
+ msg += line;
+ anna::Logger::debug(msg, ANNA_FILE_LOCATION);
);
try {
ex.trace();
}
- out_file << response_content;
+ out_file << response_content << "\n";
}
in_file.close();
+ out_file << "EOF\n";
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 <pid>";
- result += "\n or";
- result += "\n kill -s SIGUSR1 <pid>";
- result += "\n and then";
- result += "\n vi /var/tmp/anna.context.<pid>";
- 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 <path to dictionary file>";
- 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 <xml message file>' and '--dwr <xml message file>'.";
- 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|<source_file>|<target_file> Encodes source file (pathfile) into target file (pathfile).";
- result += "\ndecode|<source_file>|<target_file> Decodes source file (pathfile) into target file (pathfile).";
- result += "\nloadxml|<source_file> Reinterpret xml source file (pathfile).";
- result += "\n";
- result += "\n------------------------------------------------------------------------------------------- Hot changes";
- result += "\n";
- result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter";
- result += "\n server socket.";
- result += "\ncontext|[target file] Application context could also be written by mean this operation,";
- result += "\n and not only through SIGUSR1. If optional path file is missing,";
- result += "\n default '/var/tmp/anna.context.<pid>' will be used.";
- result += "\ncollect Reset statistics and counters to start a new test stage of";
- result += "\n performance measurement. Context data can be written at";
- result += "\n '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
- result += "\n or sending operation 'context|[target file]'.";
- result += "\nforceCountersRecord Forces dump to file the current counters of the process.";
- result += "\n";
- result += "\n<visibility action>|[<address>:<port>]|[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|<source_file> Sends xml source file (pathfile) through configured entity.";
- result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to client.";
- result += "\nsendxml|<source_file> 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.<message code>.<sequence>',";
- 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|<source_file> Sends hex source file (pathfile) through configured entity.";
- result += "\nsendhex2c|<source_file> Sends hex source file (pathfile) to client.";
- result += "\nsendhex|<source_file> 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|<action>|[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|<source_file> Loads the next diameter message into launcher burst.";
- result += "\n burst|start|<initial load> Starts (or restarts if already in progress) the message sending with";
- result += "\n a certain initial load.";
- result += "\n burst|push|<load amount> Sends specific non-aynchronous load.";
- result += "\n burst|pop|<release amount> 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|<amount> 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|<order> Updates current burst pointer position.";
- result += "\n burst|look|<order> 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 \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
- result += "\n then";
- result += "\n kill -12 <pid>";
- result += "\n or";
- result += "\n kill -s SIGUSR2 <pid>";
- result += "\n and then see the results:";
- result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
- result += "\n";
- result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
- result += "\n case over the output file. Take into account that all the content of the task file will be executed";
- result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
- result += "\n interface.";
- result += "\n";
- result += "\n";
- return result;
+
+void Launcher::logStatisticsSamples(const std::string &conceptsList) {
+ anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
+
+ if(conceptsList == "all") {
+ if(statEngine.enableSampleLog(/* -1: all concepts */))
+ LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
+ }
+ else if(conceptsList == "none") {
+ if(statEngine.disableSampleLog(/* -1: all concepts */))
+ LOGDEBUG(anna::Logger::debug("Sample log deactivation for all statistic concepts", ANNA_FILE_LOCATION));
+ } else {
+ anna::Tokenizer lst;
+ lst.apply(conceptsList, ",");
+
+ 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));
+ }
+ }
+ }
}
-void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
+
+bool Launcher::eventOperation(const std::string &operation, std::string &response) noexcept(false) {
+
+ bool result = true;
+
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 = "";
+ if (operation == "") return result; // ignore
+ LOGDEBUG(anna::Logger::debug(anna::functions::asString("Operation: %s", operation.c_str()), ANNA_FILE_LOCATION));
+
+ EventOperation eop(false /* not HTTP, it is SIGUSR2 */);
+
+ // Default response:
+ //response = "Operation processed with exception: ";
+ response = "Internal error (check ADML traces): ";
+ response += operation;
+ std::string opt_response = ""; // aditional response content
anna::DataBlock db_aux(true);
- anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXX el del nodo de trabajo
+ anna::diameter::codec::Message codecMsg; // auxiliary codec message
+
+ // Singletons:
+ anna::testing::TestManager &testManager = anna::testing::TestManager::instantiate();
+
///////////////////////////////////////////////////////////////////
// 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;
+ // Dynamic operation:
+ if(operation.find("dynamic") == 0) {
+ Procedure p(this);
+ int op_size = operation.size();
+ std::string args = ((operation.find("dynamic|") == 0) && (op_size > 8)) ? operation.substr(8) : "";
+ if (args == "" && op_size != 7)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ try {
+ p.execute(args, response);
+ }
+ catch(anna::RuntimeException &ex) {
+ ex.trace();
+ response = ex.asString();
+ return false;
+ }
+ return true; // OK
}
// Reset performance data:
if(operation == "collect") {
- resetCounters();
- resetStatistics();
- response_content = "All process counters & statistic information have been reset\n";
- return;
+ return eop.collect(response);
}
// Counters dump on demand:
if(operation == "forceCountersRecord") {
- forceCountersRecord();
- response_content = "Current counters have been dump to disk\n";
- return;
+ return eop.forceCountersRecord(response);
+ }
+
+ // OAM & statistics:
+ if(operation == "show-oam") {
+ return eop.show_oam(response);
+ }
+ if(operation == "show-stats") {
+ return eop.show_stats(response);
}
///////////////////////////////////////////////////////////////////
// Tokenize operation
Tokenizer params;
- params.apply(operation, "|");
+ params.apply(operation, "|", "<null>" /* allow contiguous separators */);
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:
+ // Get the operation type and parameters:
Tokenizer::const_iterator tok_iter = params.begin();
std::string opType = Tokenizer::data(tok_iter);
+ std::string param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11;
+ if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
+ if(numParams >= 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
+ if(numParams >= 3) { tok_iter++; param3 = Tokenizer::data(tok_iter); }
+ // Tests conditions
+ if(numParams >= 4) { tok_iter++; param4 = Tokenizer::data(tok_iter); }
+ if(numParams >= 5) { tok_iter++; param5 = Tokenizer::data(tok_iter); }
+ if(numParams >= 6) { tok_iter++; param6 = Tokenizer::data(tok_iter); }
+ if(numParams >= 7) { tok_iter++; param7 = Tokenizer::data(tok_iter); }
+ if(numParams >= 8) { tok_iter++; param8 = Tokenizer::data(tok_iter); }
+ if(numParams >= 9) { tok_iter++; param9 = Tokenizer::data(tok_iter); }
+ if(numParams >= 10) { tok_iter++; param10 = Tokenizer::data(tok_iter); }
+ if(numParams >= 11) { tok_iter++; param11 = Tokenizer::data(tok_iter); }
+ // Remove '<null>' artificial token to ease further checkings:
+ if (param1 == "<null>") param1 = "";
+ if (param2 == "<null>") param2 = "";
+ if (param3 == "<null>") param3 = "";
+ if (param4 == "<null>") param4 = "";
+ if (param5 == "<null>") param5 = "";
+ if (param6 == "<null>") param6 = "";
+ if (param7 == "<null>") param7 = "";
+ if (param8 == "<null>") param8 = "";
+ if (param9 == "<null>") param9 = "";
+ if (param10 == "<null>") param10 = "";
+ if (param11 == "<null>") param11 = "";
+
+ // No operation has more than 2 arguments except 'test' ...
+ if(opType != "test" && numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+
// Check the number of parameters:
bool wrongBody = false;
+ if((opType == "change-dir") && (numParams > 1)) wrongBody = true;
+ if((opType == "log-statistics-samples") && (numParams != 1)) wrongBody = true;
+ if((opType == "node") && (numParams > 1)) wrongBody = true;
+
+ if((opType == "node-auto") && (numParams > 0)) wrongBody = true;
+
if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
- if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
+ if(((opType == "sendxml2e") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
if((opType == "burst") && (numParams < 1)) wrongBody = true;
+ if((opType == "test") && (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)";
+ msg += "' operation (missing parameter/s). Check 'HELP.md' for more information.";
throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
}
- // All seems ok:
- std::string param1, param2;
+ // Operations:
+ if(opType == "context") {
+ return eop.context(response, (numParams == 1) ? param1 : "");
+ }
- if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
+ if(opType == "log-statistics-samples") {
+ return eop.log_statistics_samples(response, param1);
+ }
- if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
+ // Change execution directory:
+ if(opType == "change-dir") {
+ return eop.change_dir(response, param1);
+ }
- // Operations:
- if(opType == "context") {
- std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
- writeContext(contextFile);
- response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
- return;
+ if(opType == "services") {
+ std::string servicesFile = ((numParams == 1) ? param1 : "services.xml");
+ try {
+ loadServicesFromFile(servicesFile, true /* bind entities */);
+ }
+ catch(anna::RuntimeException &ex) {
+ ex.trace();
+ response = anna::functions::asString("Loaded services from file '%s' with errors", servicesFile.c_str());
+ return false;
+ }
+ response = anna::functions::asString("Loaded services from file '%s'", servicesFile.c_str());
+ return true; // OK
+ }
+
+ // Host switch:
+ if(opType == "node") {
+ return eop.node(response, param1);
+ }
+ else if(opType == "node-auto") {
+ return eop.node_auto(response);
}
if(opType == "code") {
- codecMsg.loadXML(param1);
+ codecMsg.loadXMLFile(param1);
std::string hexString = anna::functions::asHexString(codecMsg.code());
// write to outfile
std::ofstream outfile(param2.c_str(), std::ifstream::out);
outfile.write(xmlString.c_str(), xmlString.size());
outfile.close();
} else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
- MyDiameterEntity *entity = getEntity();
-
- if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
-
- if(param1 != "") {
- if(param2 != "") {
- std::string key = param1;
- key += "|";
- key += param2;
-
- if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
+ result = eop.visibility(opt_response, opType, param1, (param2 != "") ? atoi(param2.c_str()) : -1);
- if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
+ } else if((opType == "sendxml2e") || (opType == "sendhex2e")) {
+ anna::diameter::comm::Message *msg;
- 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";
- }
+ if(opType == "sendxml2e") {
+ codecMsg.loadXMLFile(param1);
+ updateOperatedOriginHostWithMessage(codecMsg);
+ msg = getOperatedHost()->createCommMessage();
+ msg->clearBody();
+ try { 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)
+ msg->setBody(codecMsg.code());
} else {
- if(opType == "hide") entity->hide();
-
- if(opType == "show") entity->show();
+ // Get DataBlock from file with hex content:
+ if(!getDataBlockFromHexFile(param1, db_aux))
+ throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
+ updateOperatedOriginHostWithMessage(db_aux);
+ msg = getOperatedHost()->createCommMessage();
+ msg->setBody(db_aux);
+ try { if(getOperatedHost()->logEnabled()) codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
+ }
- if(opType == "hidden") result = entity->hidden() ? "true" : "false";
+ bool success = getOperatedEntity()->send(msg);
+ getOperatedHost()->releaseCommMessage(msg);
- if(opType == "shown") result = entity->shown() ? "true" : "false";
+ // Detailed log:
+ if(getOperatedHost()->logEnabled()) {
+ anna::diameter::comm::Server *usedServer = getOperatedEntity()->getLastUsedResource();
+ anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
+ std::string detail = usedClientSession ? usedClientSession->asString() : "[null client session]"; // shouldn't happen
+ getOperatedHost()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
}
- } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
- MyDiameterEntity *entity = getEntity();
-
- if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
- anna::diameter::comm::Message *msg = createCommMessage();
+ } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
+ anna::diameter::comm::Message *msg;
- if((opType == "sendxml") || (opType == "sendxml2e")) {
- codecMsg.loadXML(param1);
+ if(opType == "sendxml2c") {
+ codecMsg.loadXMLFile(param1);
+ updateOperatedOriginHostWithMessage(codecMsg);
+ msg = getOperatedHost()->createCommMessage();
msg->clearBody();
try { 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)
// Get DataBlock from file with hex content:
if(!getDataBlockFromHexFile(param1, db_aux))
throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
-
+ updateOperatedOriginHostWithMessage(db_aux);
+ msg = getOperatedHost()->createCommMessage();
msg->setBody(db_aux);
}
- bool success = entity->send(msg, cl.exists("balance"));
- releaseCommMessage(msg);
+ bool success = getOperatedServer()->send(msg);
+ getOperatedHost()->releaseCommMessage(msg);
// 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() : "<null client session>"; // esto no deberia ocurrir
- writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
+ if(getOperatedHost()->logEnabled()) {
+ anna::diameter::comm::ServerSession *usedServerSession = getOperatedServer()->getLastUsedResource();
+ std::string detail = usedServerSession ? usedServerSession->asString() : "[null server session]"; // shouldn't happen
+ getOperatedHost()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
+ }
+ } else if(opType == "answerxml2e") {
+
+ if(param1 == "") { // programmed answers FIFO's to stdout
+ response = getOperatedHost()->getReactingAnswers()->asString("ANSWERS TO ENTITY");
+ return true; // OK
+ } else if (param1 == "rotate") {
+ getOperatedHost()->getReactingAnswers()->rotate(true);
+ } else if (param1 == "exhaust") {
+ getOperatedHost()->getReactingAnswers()->rotate(false);
+ } else if (param1 == "clear") {
+ getOperatedHost()->getReactingAnswers()->clear();
+ } else if (param1 == "dump") {
+ getOperatedHost()->getReactingAnswers()->dump("programmed_answer");
+ } else {
+ codecMsg.loadXMLFile(param1);
+ updateOperatedOriginHostWithMessage(codecMsg);
+ anna::diameter::codec::Message *message = getOperatedHost()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
+ 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));
+ getOperatedHost()->getReactingAnswers()->addMessage(code, message);
+ }
+ } else if(opType == "answerxml2c") {
+
+ if(param1 == "") { // programmed answers FIFO's to stdout
+ response = getOperatedHost()->getReactingAnswers()->asString("ANSWERS TO CLIENT");
+ return true; // OK
+ } else if (param1 == "rotate") {
+ getOperatedHost()->getReactingAnswers()->rotate(true);
+ } else if (param1 == "exhaust") {
+ getOperatedHost()->getReactingAnswers()->rotate(false);
+ } else if (param1 == "clear") {
+ getOperatedHost()->getReactingAnswers()->clear();
+ } else if (param1 == "dump") {
+ getOperatedHost()->getReactingAnswers()->dump("programmed_answer");
+ } else {
+ codecMsg.loadXMLFile(param1);
+ updateOperatedOriginHostWithMessage(codecMsg);
+ anna::diameter::codec::Message *message = getOperatedHost()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
+ 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));
+ getOperatedHost()->getReactingAnswers()->addMessage(code, message);
}
} 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);
+ if (!uniqueOriginHost())
+ throw anna::RuntimeException("Burst category operations are only allowed in single host node configuration. This is only to simplify user experience.", ANNA_FILE_LOCATION);
// burst|clear clears all loaded burst messages.
// burst|load|<source_file> loads the next diameter message into launcher burst.
// 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.
+ // burst|look|<order> Show programmed burst message for order provided, current when missing.
if(param1 == "clear") {
- result = "Removed ";
- result += anna::functions::asString(clearBurst());
- result += " elements.";
+ opt_response = "removed ";
+ opt_response += anna::functions::asString(getOperatedHost()->clearBurst());
+ opt_response += " elements";
} else if(param1 == "load") {
if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
- codecMsg.loadXML(param2);
-
+ codecMsg.loadXMLFile(param2);
if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
try { 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(codecMsg.code());
- result = "Loaded '";
- result += param2;
- result += "' file into burst list position ";
- result += anna::functions::asString(position);
+ int position = getOperatedHost()->loadBurstMessage(codecMsg.code());
+ opt_response = "loaded '";
+ opt_response += param2;
+ opt_response += "' file into burst list position ";
+ opt_response += 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);
+ int processed = getOperatedHost()->startBurst(initialLoad);
if(processed > 0) {
- result = "Initial load completed for ";
- result += anna::functions::entriesAsString(processed, "message");
- result += ".";
+ opt_response = "initial load completed for ";
+ opt_response += anna::functions::entriesAsString(processed, "message");
}
} 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()));
+ int pushed = getOperatedHost()->pushBurst(atoi(param2.c_str()));
if(pushed > 0) {
- result = "Pushed ";
- result += anna::functions::entriesAsString(pushed, "message");
- result += ".";
+ opt_response = "pushed ";
+ opt_response += anna::functions::entriesAsString(pushed, "message");
}
} 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);
+ int popped = getOperatedHost()->popBurst(releaseLoad);
if(popped > 0) {
- result = "Burst popped for ";
- result += anna::functions::entriesAsString(popped, "message");
- result += ".";
+ opt_response = "burst popped for ";
+ opt_response += anna::functions::entriesAsString(popped, "message");
}
} else if(param1 == "stop") {
- int left = stopBurst();
+ int left = getOperatedHost()->stopBurst();
if(left != -1) {
- result += anna::functions::entriesAsString(left, "message");
- result += " left to the end of the cycle.";
+ opt_response += anna::functions::entriesAsString(left, "message");
+ opt_response += " 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.");
+ getOperatedHost()->repeatBurst(repeat);
+ opt_response += (repeat ? "repeat enabled" : "repeat disabled");
} 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()));
+ int sent = getOperatedHost()->sendBurst(atoi(param2.c_str()));
if(sent > 0) {
- result = "Sent ";
- result += anna::functions::entriesAsString(sent, "message");
- result += ".";
+ opt_response = "sent ";
+ opt_response += anna::functions::entriesAsString(sent, "message");
}
} 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 += ".";
+ opt_response = getOperatedHost()->gotoBurst(atoi(param2.c_str()));
} 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";
+ int order = ((param2 != "") ? atoi(param2.c_str()) : -1);
+ opt_response = "\n\n";
+ opt_response += getOperatedHost()->lookBurst(order);
} else {
- throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
+ throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
}
- } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
- MyLocalServer *localServer = getDiameterLocalServer();
- if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
- anna::diameter::comm::Message *msg = createCommMessage();
+ } else if((opType == "test")) {
+ // test|<id>|<command>[|parameters] Add a new step to the test case ...
+ // test|ttps|<amount> Starts/resume the provided number of time ticks per second (ttps). The ADML starts ...
+ // test|next[|<sync-amount>] Forces the execution of the next test case(s) without waiting for test manager tick ...
+ // test|ip-limit[|amount] In-progress limit of test cases. No new test cases will be launched over this value ...
+ // test|repeats|<amount> Restarts the whole programmed test list when finished the amount number of times ...
+ // test|report|<initialized/in-progress/failed/success/[all]/none>[|[yes]|no]
+ // Enables/disables report generation for a certain test case state: initialized, in-progress ...
+ // test|report-hex[|[yes]|no] Reports could include the diameter messages in hexadecimal format. Disabled by default.
+ // test|goto|<id> Updates current test pointer position.
+ // test|run|<id> Executes the given test case
+ // test|look[|id] Show programmed test case for id provided, current when missing ...
+ // test|state[|id] Show test case state for id provided, current when missing ...
+ // test|interact|amount|id Makes interactive a specific test case id. The amount is the margin of execution steps ...
+ // test|reset|<[soft]/hard>[|id] Reset the test case for id provided, all the tests when missing ...
+ // test|auto-reset|<soft|hard> When cycling, current test cases can be soft (default) or hard reset ...
+ // test|clear Clears all the programmed test cases.
+ // test|summary Test manager general report (number of test cases, counts by state ...
+
+
+ if(param1 == "ttps") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ bool success = ((param2 != "") ? testManager.configureTTPS(atoi(param2.c_str())) : false);
+ if (success) {
+ opt_response = "assigned new test launch rate to ";
+ opt_response += anna::functions::asString(atoi(param2.c_str()));
+ opt_response += " events per second";
+ }
+ else {
+ opt_response += "unable to configure the test rate provided";
+ }
+ }
+ else if (param1 == "next") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(opType == "sendxml2c") {
- codecMsg.loadXML(param1);
- msg->clearBody();
- try { 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)
+ int sync_amount = ((param2 != "") ? atoi(param2.c_str()) : 1);
- msg->setBody(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);
+ if (sync_amount < 1)
+ throw anna::RuntimeException("The parameter 'sync-amount' must be a positive integer value", ANNA_FILE_LOCATION);
- msg->setBody(db_aux);
+ bool success = testManager.execTestCases(sync_amount);
+
+ opt_response = (success ? "" : "not completely " /* completed cycle and no repeats, rare case */);
+ opt_response += "processed ";
+ opt_response += anna::functions::asString(sync_amount);
+ opt_response += ((sync_amount > 1) ? " test cases synchronously" : " test case");
+ }
+ else if(param1 == "ip-limit") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ unsigned int limit;
+ if (param2 != "") {
+ limit = atoi(param2.c_str());
+ testManager.setInProgressLimit(limit);
+ opt_response = "new in-progress limit: ";
+ opt_response += (limit != UINT_MAX) ? anna::functions::asString(limit) : "[no limit]";
+ }
+ else {
+ opt_response = "in-progress limit amount: ";
+ limit = testManager.getInProgressLimit();
+ opt_response += (limit != UINT_MAX) ? anna::functions::asString(limit) : "[no limit]";
+ opt_response += "; currently there are ";
+ opt_response += anna::functions::asString(testManager.getInProgressCount());
+ opt_response += " test cases running";
+ }
}
+ else if(param1 == "repeats") {
+ if (numParams != 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ int repeats = atoi(param2.c_str());
+ if (repeats < 0) repeats = -1;
+ testManager.setPoolRepeats(repeats);
+ std::string nolimit = (repeats != -1) ? "":" [no limit]";
+ opt_response += anna::functions::asString("Pool repeats: %d%s (current cycle: %d)", repeats, nolimit.c_str(), testManager.getPoolCycle());
+ }
+ else if(param1 == "report") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ if(param2 == "") param2 = "all";
+ if(param3 == "") param3 = "yes";
+ bool enable = (param3 == "yes");
+
+ if(param2 == "initialized")
+ testManager.setDumpInitializedReports(enable);
+ else if(param2 == "in-progress")
+ testManager.setDumpInProgressReports(enable);
+ else if(param2 == "failed")
+ testManager.setDumpFailedReports(enable);
+ else if(param2 == "success")
+ testManager.setDumpSuccessReports(enable);
+ else if(param2 == "all") {
+ param2 = "any";
+ testManager.setDumpAllReports(enable);
+ }
+ else if(param2 == "none") {
+ enable = !enable;
+ param2 = "any";
+ testManager.setDumpAllReports(enable);
+ }
+ else
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- bool success = localServer->send(msg);
- releaseCommMessage(msg);
+ opt_response += (enable ? "report enabled " : "report disabled ");
+ opt_response += "for tests in '";
+ opt_response += param2;
+ opt_response += "' state";
+ }
+ else if(param1 == "report-hex") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- // Detailed log:
- if(logEnabled()) {
- anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
- std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
- writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
+ if(param2 == "") param2 = "yes";
+ testManager.setDumpHex((param2 == "yes"));
+ opt_response += (testManager.getDumpHex() ? "report includes hexadecimal messages" : "report excludes hexadecimal messages");
}
- } else if(opType == "loadxml") {
- codecMsg.loadXML(param1);
- std::string xmlString = codecMsg.asXMLString();
- std::cout << xmlString << std::endl;
- } else if(opType == "diameterServerSessions") {
- int diameterServerSessions = atoi(param1.c_str());
+ else if(param1 == "dump-stdout") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(!getDiameterLocalServer())
- startDiameterServer(diameterServerSessions);
- else
- getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
- } else if((opType == "answerxml") || (opType == "answerxml2c")) {
- MyLocalServer *localServer = getDiameterLocalServer();
+ if(param2 == "") param2 = "yes";
+ testManager.setDumpStdout((param2 == "yes"));
+ opt_response += (testManager.getDumpHex() ? "test manager dumps progress into stdout" : "test manager does not dump progress into stdout");
+ }
+ else if(param1 == "goto") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ if(param2 == "") throw anna::RuntimeException("Missing id for test goto operation", ANNA_FILE_LOCATION);
+ int id = atoi(param2.c_str());
+ if (testManager.gotoTestCase(id)) {
+ opt_response = "position updated for id provided (";
+ }
+ else {
+ opt_response = "cannot found test id (";
+ }
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ else if(param1 == "run") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ if(param2 == "") throw anna::RuntimeException("Missing id for test run operation", ANNA_FILE_LOCATION);
+ int id = atoi(param2.c_str());
+ if (testManager.runTestCase(id)) {
+ opt_response = "test executed for id provided (";
+ }
+ else {
+ opt_response = "cannot found test id (";
+ }
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ else if(param1 == "look") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(!localServer)
- throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
+ int id = ((param2 != "") ? atoi(param2.c_str()) : -1);
+ anna::testing::TestCase *testCase = testManager.findTestCase(id);
- if(param1 == "") { // programmed answers FIFO's to stdout
- std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl;
- response_content = "Programmed answers dumped on stdout\n";
- return;
- } else if (param1 == "rotate") {
- localServer->getReactingAnswers()->rotate(true);
- } else if (param1 == "exhaust") {
- localServer->getReactingAnswers()->rotate(false);
- } else if (param1 == "clear") {
- localServer->getReactingAnswers()->clear();
- } else if (param1 == "dump") {
- localServer->getReactingAnswers()->dump();
- } else {
- anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1); // // XXXXXXXXXXXXXX el del nodo de trabajo
- LOGDEBUG
- (
- anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
- );
+ if (testCase) {
+ response = testCase->asXMLString();
+ return true; // OK
+ }
+ else {
+ result = false;
+ if (id == -1) {
+ opt_response = "no current test case detected (testing started ?)";
+ }
+ else {
+ opt_response = "cannot found test id (";
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ }
+ }
+ else if(param1 == "state") {
+ if (numParams > 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(message->isRequest())
- throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
+ int id = ((param2 != "") ? atoi(param2.c_str()) : -1);
+ anna::testing::TestCase *testCase = testManager.findTestCase(id);
- int code = message->getId().first;
- LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
- localServer->getReactingAnswers()->addMessage(code, message);
+ if (testCase) {
+ response = anna::testing::TestCase::asText(testCase->getState());
+ return testCase->isSuccess();
+ }
+ else {
+ result = false;
+ if (id == -1) {
+ opt_response = "no current test case detected (testing started ?)";
+ }
+ else {
+ opt_response = "cannot found test id (";
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ }
}
- } else if(opType == "answerxml2e") {
- MyDiameterEntity *entity = getEntity();
+ else if (param1 == "interact") {
+ if (numParams != 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ int amount = atoi(param2.c_str());
+ if (amount < -1)
+ throw anna::RuntimeException("Interactive amount must be -1 (to disable interactive mode) or a positive number.", ANNA_FILE_LOCATION);
+
+ int id = ((param3 != "") ? atoi(param3.c_str()) : -1);
+ anna::testing::TestCase *testCase = testManager.findTestCase(id);
+ if (testCase) {
+ if (amount == -1) {
+ testCase->makeInteractive(false);
+ opt_response = "interactive mode disabled";
+ }
+ else {
+ testCase->addInteractiveAmount(amount);
+ opt_response = "added interactive amount of ";
+ opt_response += anna::functions::asString(amount);
+ opt_response += " units";
+ if (amount == 0) opt_response += " (0: freezing a non-interactive testcase, no effect on already interactive)";
+ }
+ opt_response += " for test case id ";
+ opt_response += anna::functions::asString(id);
+ }
+ else {
+ result = false;
+ opt_response = "cannot found test id (";
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ }
+ else if(param1 == "reset") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ if(param2 == "") param2 = "soft";
+ if (param2 != "soft" && param2 != "hard")
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+
+ int id = ((param3 != "") ? atoi(param3.c_str()) : -1);
+ anna::testing::TestCase *testCase = ((id != -1) ? testManager.findTestCase(id) : NULL);
+
+ if (testCase) {
+ bool done = testCase->reset(param2 == "hard");
+ opt_response = "test ";
+ opt_response += param2;
+ opt_response += " reset for id ";
+ opt_response += anna::functions::asString(id);
+ opt_response += done ? ": done": ": not done";
+ }
+ else {
+ if (id == -1) {
+ bool anyReset = testManager.resetPool(param2 == "hard");
+ opt_response = param2; opt_response += " reset have been sent to all programmed tests: "; opt_response += anyReset ? "some/all have been reset" : "nothing was reset";
+ }
+ else {
+ result = false;
+ opt_response = "cannot found test id (";
+ opt_response += anna::functions::asString(id);
+ opt_response += ")";
+ }
+ }
+ }
+ else if(param1 == "auto-reset") {
+ if (numParams != 2)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(!entity)
- throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
+ if (param2 != "soft" && param2 != "hard")
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(param1 == "") { // programmed answers FIFO's to stdout
- std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl;
- response_content = "Programmed answers dumped on stdout\n";
- return;
- } else if (param1 == "rotate") {
- entity->getReactingAnswers()->rotate(true);
- } else if (param1 == "exhaust") {
- entity->getReactingAnswers()->rotate(false);
- } else if (param1 == "clear") {
- entity->getReactingAnswers()->clear();
- } else if (param1 == "dump") {
- entity->getReactingAnswers()->dump();
- } else {
- anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1); // XXXXXXXXXXXXXX el del nodo de trabajo
- LOGDEBUG
- (
- anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
- );
+ testManager.setAutoResetHard(param2 == "hard");
+ opt_response += anna::functions::asString("Auto-reset configured to '%s'", param2.c_str());
+ }
+ else if(param1 == "initialized") {
+ if (numParams > 1)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- if(message->isRequest())
- throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
+ opt_response = anna::functions::asString("%lu", testManager.getInitializedCount());
+ }
+ else if(param1 == "finished") {
+ if (numParams > 1)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
- int code = message->getId().first;
- LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
- entity->getReactingAnswers()->addMessage(code, message);
+ opt_response = anna::functions::asString("%lu", testManager.getFinishedCount());
}
- } 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);
- }
+ else if(param1 == "clear") {
+ if (numParams > 1)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", 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;
+ result = testManager.clearPool(opt_response);
+ }
+ else if(param1 == "junit") {
+ response = testManager.junitAsXMLString();
+ return true; // OK
+ }
+ else if(param1 == "summary-counts") {
+ response = testManager.summaryCounts();
+ return true; // OK
+ }
+ else if(param1 == "summary-states") {
+ response = testManager.summaryStates();
+ return true; // OK
+ }
+ else if(param1 == "summary") {
+ response = testManager.asXMLString();
+ return true; // OK
+ }
+ else {
+ int id = atoi(param1.c_str());
+ if(id < 0)
+ throw anna::RuntimeException("Invalid test case identifier: must be a non-negative number", ANNA_FILE_LOCATION);
+
+ // PARAM: 1 2 3 4 5 6 7 8 9 10 11
+ // test|<id>|<command>
+ // description|<description>
+ // ip-limit[|<iplimit>]
+ // timeout| <msecs>
+ // sendxml2e| <file>[|<step number>]
+ // sendxml2c| <file>[|<step number>]
+ // delay| [msecs]
+ // wait<fe/fc>|[code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId]
+ // wait<fe/fc>-answer|<step number>
+ // wait<fe/fc>-xml |<source_file>[|strict]
+ // wait<fe/fc>-hex |<source_file>[|strict]
+ if(param2 == "") throw anna::RuntimeException("Missing command for test id operation", ANNA_FILE_LOCATION);
+
+ // Commands:
+ if (param2 == "description") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException("Missing description for test case", ANNA_FILE_LOCATION);
+ testManager.getTestCase(id)->setDescription(param3); // creates / reuses
+ }
+ else if (param2 == "ip-limit") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ unsigned int limit = (param3 == "") ? 1 : atoi(param3.c_str());
+ testManager.getTestCase(id)->addIpLimit(limit); // creates / reuses
+ }
+ else if (param2 == "timeout") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'timeout' command in test id operation", ANNA_FILE_LOCATION);
+ anna::Millisecond timeout = checkTimeMeasure("Test case timeout", param3);
+ testManager.getTestCase(id)->addTimeout(timeout); // creates / reuses
+ }
+ else if ((param2 == "sendxml2e")||(param2 == "sendxml2c")) {
+ if (numParams > 4)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException(anna::functions::asString("Missing xml file for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
+ codecMsg.loadXMLFile(param3);
+ LOGWARNING(
+ if (!codecMsg.isRequest() && (param4 == ""))
+ anna::Logger::warning("Step number has not been provided. Take into account that this answer message will be sent 'as is' and sequence information could be wrong at the remote peer", ANNA_FILE_LOCATION);
+ );
+
+ updateOperatedOriginHostWithMessage(codecMsg);
+ int stepNumber = ((param4 != "") ? atoi(param4.c_str()):-1);
+
+ if (param2 == "sendxml2e")
+ testManager.getTestCase(id)->addSendDiameterXml2e(codecMsg.code(), getOperatedHost(), stepNumber); // creates / reuses
+ else
+ testManager.getTestCase(id)->addSendDiameterXml2c(codecMsg.code(), getOperatedHost(), stepNumber); // creates / reuses
+ }
+ else if (param2 == "delay") {
+ if (numParams > 3)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'delay' command in test id operation", ANNA_FILE_LOCATION);
+ anna::Millisecond delay = ((param3 == "0" /* special case */) ? (anna::Millisecond)0 : checkTimeMeasure("Test case delay step", param3));
+ testManager.getTestCase(id)->addDelay(delay); // creates / reuses
+ }
+
+// TODO(***)
+// The way to identify the test case, is through registered Session-Id values for
+// programmed requests. But this depends on the type of node. Acting as clients,
+// requests received have Session-Id values which are already registered with
+// one test case, causing an error if not found. Acting as servers, requests are
+// received over a diameter local server from a client which are generating that
+// Session-Id values. Then we know nothing about such values. The procedure in
+// this case is find out a test case not-started containing a condition which
+// comply with the incoming message, and reactivates it.
+// The other solution: register Session-Id values for answers send to client from a local diameter server.
+ else if ((param2 == "waitfe")||(param2 == "waitfc")) {
+ if (numParams > 11)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if (param3 != "" || param4 != "" || param5 != "" || param6 != "" || param7 != "" || param8 != "" || param9 != "" || param10 != "" || param11 != "") {
+ bool fromEntity = (param2.substr(4,2) == "fe");
+ testManager.getTestCase(id)->addWaitDiameter(fromEntity, param3, param4, param5, param6, param7, param8, param9, param10, param11);
+ }
+ else {
+ throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
+ }
+ }
+ else if ((param2 == "waitfe-hex")||(param2 == "waitfc-hex")) {
+ if (numParams > 4)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException(anna::functions::asString("Missing hex file for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
+
+ // Get DataBlock from file with hex content:
+ if(!getDataBlockFromHexFile(param3, db_aux))
+ throw anna::RuntimeException("Error reading hex content from file provided", ANNA_FILE_LOCATION);
+
+ // Hexadecimal representation read from file:
+ std::string regexp = anna::functions::asHexString(db_aux);
+
+ // optional 'full':
+ if(param4 != "strict") {
+ //// If request, we will ignore sequence data:
+ //if (anna::diameter::codec::functions::requestBit(db_aux))
+ regexp.replace (24, 16, "[0-9A-Fa-f]{16}");
+
+ regexp.insert(0, "^");
+ regexp += "$";
+ }
+
+ bool fromEntity = (param2.substr(4,2) == "fe");
+ testManager.getTestCase(id)->addWaitDiameterRegexpHex(fromEntity, regexp);
+ }
+ else if ((param2 == "waitfe-xml")||(param2 == "waitfc-xml")) {
+ if (numParams > 4)
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException(anna::functions::asString("Missing xml file for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
+
+ codecMsg.loadXMLFile(param3);
+ std::string regexp = codecMsg.asXMLString(true /* normalization */);
+
+ // Now we must insert regular expressions in hop-by-hop, end-to-end and Origin-State-Id:
+
+ // optional 'full':
+ if(param4 != "strict") {
+ std::string::size_type pos, pos_1, pos_2;
+
+ pos = regexp.find("end-to-end-id=", 0u);
+ if (pos != std::string::npos) {
+ pos = regexp.find("\"", pos);
+ pos_1 = pos;
+ pos = regexp.find("\"", pos+1);
+ pos_2 = pos;
+ regexp.replace(pos_1 + 1, pos_2 - pos_1 - 1, "[0-9]+");
+ }
+
+ pos = regexp.find("hop-by-hop-id=", 0u);
+ if (pos != std::string::npos) {
+ pos = regexp.find("\"", pos);
+ pos_1 = pos;
+ pos = regexp.find("\"", pos+1);
+ pos_2 = pos;
+ regexp.replace(pos_1 + 1, pos_2 - pos_1 - 1, "[0-9]+");
+ }
+
+ // For this representation: <avp name="Origin-State-Id" data="1428633668"/>
+ //pos = regexp.find("Origin-State-Id", 0u);
+ //pos = regexp.find("\"", pos);
+ //pos = regexp.find("\"", pos+1);
+ //pos_1 = pos;
+ //pos = regexp.find("\"", pos+1);
+ //pos_2 = pos;
+ //regexp.replace(pos_1 + 1, pos_2 - pos_1 - 1, "[0-9]+");
+ // But we have this one: <avp data="1428633668" name="Origin-State-Id"/>
+ pos = regexp.find("Origin-State-Id", 0u);
+ if (pos != std::string::npos) {
+ pos = regexp.rfind("\"", pos);
+ pos = regexp.rfind("\"", pos-1);
+ pos = regexp.rfind("\"", pos-1);
+ pos_1 = pos;
+ pos = regexp.find("\"", pos+1);
+ pos_2 = pos;
+ regexp.replace(pos_1 + 1, pos_2 - pos_1 - 1, "[0-9]+");
+ }
+
+ //regexp.insert(0, "^");
+ //regexp += "$";
+ }
+
+ bool fromEntity = (param2.substr(4,2) == "fe");
+ testManager.getTestCase(id)->addWaitDiameterRegexpXml(fromEntity, regexp);
+ }
+ else if (param2 == "sh-command") {
+ // Allow pipes in command:
+ //if (numParams > 4)
+ // throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ if(param3 == "") throw anna::RuntimeException("Missing script/executable command-line for 'sh-command' in test id operation", ANNA_FILE_LOCATION);
+ std::string token = "|sh-command|";
+ std::string command = operation.substr(operation.find(token) + token.size());
+ testManager.getTestCase(id)->addCommand(command); // creates / reuses
+ }
+ else {
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ }
}
- 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";
+ codecMsg.loadXMLFile(param1);
+ response = codecMsg.asXMLString();
+ return true; // OK
} 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");
+ int diameterServerSessions = atoi(param1.c_str());
+ getOperatedServer()->setMaxConnections(diameterServerSessions);
- 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);
+ } else {
+ throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION);
+ }
- 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);
- );
+ // HTTP response
+ response = "Operation correctly processed: "; response += operation;
+ if (opt_response != "") {
+ response += " => ";
+ response += opt_response;
}
- return -1;
+ return result;
}
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("InitialWorkingDirectory", a_initialWorkingDirectory);
result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
// Diameter:
- getCodecEngine()->asXML(result); // XXXXXXXXXXXXXXX todos los nodos ...
+ anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate();
+ for (diameter::comm::origin_hosts_it it = ohm.begin(); it != ohm.end(); it++) {
+ it->second->asXML(result);
+ }
+
+ // Registered codec engines:
+ anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
+ em.asXML(result);
+
+ // OAM & statistics:
+ oamAsXML(result);
+ statsAsXML(result);
+
+ // Testing: could be heavy if test case reports are enabled
+ anna::testing::TestManager::instantiate().asXML(result);
+
+ return result;
+}
+
+anna::xml::Node* Launcher::oamAsXML(anna::xml::Node* parent) const
+{
+ anna::xml::Node* result = parent->createChild("Oam");
+
// OAM:
anna::diameter::comm::OamModule::instantiate().asXML(result);
anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
anna::diameter::codec::OamModule::instantiate().asXML(result);
+
+ return result;
+}
+
+anna::xml::Node* Launcher::statsAsXML(anna::xml::Node* parent) const
+{
+ anna::xml::Node* result = parent->createChild("Statistics");
+
// Statistics:
anna::statistics::Engine::instantiate().asXML(result);
+
return result;
}