X-Git-Url: https://git.teslayout.com/public/public/public/?p=anna.git;a=blobdiff_plain;f=example%2Fdiameter%2Flauncher%2FLauncher.cpp;h=60a9cb0cfb7a0fec3dcc13f668d50713fc9af26c;hp=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391;hb=415985b3f67878c2e3cee785a0b1cb36f4eff901;hpb=68a8fe342d8337ec1a86b57920bc7dcf7faf2413 diff --git a/example/diameter/launcher/Launcher.cpp b/example/diameter/launcher/Launcher.cpp index e69de29..60a9cb0 100644 --- a/example/diameter/launcher/Launcher.cpp +++ b/example/diameter/launcher/Launcher.cpp @@ -0,0 +1,1976 @@ +// ANNA - Anna is Not Nothingness Anymore // +// // +// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo // +// // +// See project site at http://redmine.teslayout.com/projects/anna-suite // +// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE // + + +// Standard +#include // std::istringstream +#include // std::cout +#include // ceil +#include +#include // chdir +//#include TODO: use this from gcc4.9.0: http://stackoverflow.com/questions/8060025/is-this-c11-regex-error-me-or-the-compiler +#include + +// Project +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Process +#include +#include +#include +#include +#include +#include + + +#define SIGUSR2_TASKS_INPUT_FILENAME "sigusr2.in" +#define SIGUSR2_TASKS_OUTPUT_FILENAME "sigusr2.out" + + +const char *ServicesDTD = "\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +\n\ +"; + + +Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) { + 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_workingNode = NULL; + + a_httpServerSocket = NULL; +} + + +std::string Launcher::getSignalUSR2InputFile() const throw() { + return (a_initialWorkingDirectory + "/" + SIGUSR2_TASKS_INPUT_FILENAME); +} + +std::string Launcher::getSignalUSR2OutputFile() const throw() { + return (a_initialWorkingDirectory + "/" + SIGUSR2_TASKS_OUTPUT_FILENAME); +} + + +void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) { + + CommandLine& cl(anna::CommandLine::instantiate()); + bool allLogsDisabled = cl.exists("disableLogs"); + + // + const anna::xml::Attribute *id, *dictionary; + + // + 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; + 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)); + 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); + } + } + + // 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); + } + + // 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); + } + + 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: + 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); + 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 + std::string cerPathfile = cer ? cer->getValue() : ""; + std::string dwrPathfile = dwr ? dwr->getValue() : ""; + commEngine->setClientCERandDWR(cerPathfile, dwrPathfile); + + // 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 (eventOperation) 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); + } + + + // Lazy initialization for comm engine: + if (eventOperation) commEngine->lazyInitialize(); + + // Node and Codec Engine registration /////////////////////////////////////////////////////// + ohm.registerOriginHost(originHost->getValue(), a_workingNode); + ///////////////////////////////////////////////////////////////////////////////////////////// + } + } + + 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::loadServices(const std::string & xmlPathFile, bool eventOperation) throw(anna::RuntimeException) { + + 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; + } + + 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; + } + + 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, eventOperation); +} + + +anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const std::string &value) throw(anna::RuntimeException) { + + 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 = "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 = "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 = "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 (anna::Millisecond)msecs; // ok + } + + // 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); +} + +bool Launcher::setWorkingNode(const std::string &name) throw() { + bool result = false; + + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + anna::diameter::comm::OriginHost *oh = ohm.getOriginHost(name); + + if (oh) { + a_workingNode = const_cast(oh); + result = true; + } + + return result; +} + +anna::diameter::comm::OriginHost *Launcher::getOriginHost(const std::string &name) const throw(anna::RuntimeException) { + 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 throw(anna::RuntimeException) { + std::string originHost = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue(); + return (getOriginHost(originHost)); +} + +bool Launcher::uniqueOriginHost() const throw() { + anna::diameter::comm::OriginHostManager &ohm = anna::diameter::comm::OriginHostManager::instantiate(); + return (ohm.size() == 1); +} + + +void Launcher::updateOperatedOriginHostWithMessage(const anna::diameter::codec::Message &message) throw(anna::RuntimeException) { + if (!a_operatedHost) // priority for working node by mean 'node' operation + a_operatedHost = getOriginHost(message); +} + +anna::diameter::comm::OriginHost *Launcher::getWorkingNode() const throw(anna::RuntimeException) { + 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 throw(anna::RuntimeException) { + if(!a_operatedHost) + throw anna::RuntimeException("Node not identified (try to force a specific Origin-Host with 'node' operation)", ANNA_FILE_LOCATION); + + return a_operatedHost; +} + +MyDiameterEntity *Launcher::getOperatedEntity() const throw(anna::RuntimeException) { + 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 throw(anna::RuntimeException) { + MyLocalServer *result = (MyLocalServer *)(getOperatedHost()->getDiameterServer()); + if (!result) + throw anna::RuntimeException("No local server configured for the operated node", ANNA_FILE_LOCATION); + return result; +} + +MyDiameterEngine *Launcher::getOperatedEngine() const throw(anna::RuntimeException) { + return (MyDiameterEngine *)getOperatedHost()->getCommEngine(); // never will be NULL +} + +void Launcher::initialize() +throw(anna::RuntimeException) { + anna::comm::Application::initialize(); + CommandLine& cl(anna::CommandLine::instantiate()); + anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single); + a_communicator = new MyCommunicator(workMode); + a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, a_admlMinResolution); + anna::testing::TestManager::instantiate().setTimerController(a_timeEngine); + + // 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) { + 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: + loadServices(cl.getValue("services")); // before run (have components to be created) +} + +void Launcher::run() +throw(anna::RuntimeException) { + 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(); + + // 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; + + // Statistics: + anna::statistics::Engine::instantiate().enable(); + + LOGINFORMATION( + // Test messages dtd: + std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n"; + msg += anna::diameter::codec::MessageDTD; + anna::Logger::information(msg, ANNA_FILE_LOCATION); + ); + + // HTTP Server: + if(cl.exists("httpServer")) { + anna::comm::Network& network = anna::comm::Network::instantiate(); + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port); + //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP + const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve + a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory()); + } + + /////////////////////////////// + // Diameter library COUNTERS // + /////////////////////////////// + anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate(); + oamDiameterComm.initializeCounterScope(1); // 1000 - 1999 + oamDiameterComm.enableCounters(); + oamDiameterComm.enableAlarms(); + anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate(); + oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999 + oamDiameterCodec.enableCounters(); + oamDiameterCodec.enableAlarms(); + ///////////////// + // COMM MODULE // + ///////////////// + /* Main events */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17); + /* Diameter Base (capabilities exchange & keep alive) */ + // as client + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26); + // as server + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35); + /* server socket operations (enable/disable listening port for any local server) */ + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37); + /* Connectivity */ + // clients + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46); + // servers + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57); + oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::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 // + ////////////////// + /* Avp decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/); + /* Message decoding */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/); + /* Avp validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/); + /* Message validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/); + /* Level validation */ + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/); + oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/); + + + ///////////////////////////////// + // Counter recorder associated // + ///////////////////////////////// + if(a_counterRecorderClock) { + oamDiameterComm.setCounterRecorder(a_counterRecorder); + oamDiameterCodec.setCounterRecorder(a_counterRecorder); + anna::diameter::comm::ApplicationMessageOamModule::instantiate().setCounterRecorder(a_counterRecorder); + a_timeEngine->activate(a_counterRecorderClock); // start clock + } + + ///////////////////////////// + // 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(); + } + + // 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(anna::RuntimeException) { + // Get hex string + static char buffer[8192]; + std::ifstream infile(pathfile.c_str(), std::ifstream::in); + + if(infile.is_open()) { + infile >> buffer; + std::string hexString(buffer, strlen(buffer)); + // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString': + hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end()); + LOGDEBUG( + std::string msg = "Hex string (remove colons if exists): "; + msg += hexString; + anna::Logger::debug(msg, ANNA_FILE_LOCATION); + ); + + anna::functions::fromHexString(hexString, db); // could launch exception + // Close file + infile.close(); + return true; + } + + return false; +} + +void Launcher::resetStatistics() throw() { + if (a_workingNode) { + a_workingNode->getCommEngine()->resetStatistics(); + } + 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(); + } + } +} + +void Launcher::resetCounters() throw() { + anna::diameter::comm::OamModule::instantiate().resetCounters(); + anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters(); + anna::diameter::codec::OamModule::instantiate().resetCounters(); +} + +void Launcher::signalTerminate() throw(anna::RuntimeException) { + LOGMETHOD(anna::TraceMethod tm("Launcher", "signalTerminate", ANNA_FILE_LOCATION)); + + forceCountersRecord(); + + a_communicator->terminate (); + comm::Application::signalTerminate (); +} + +void Launcher::signalUSR2() throw(anna::RuntimeException) { + + std::string inputFile = getSignalUSR2InputFile(); + std::string outputFile = getSignalUSR2OutputFile(); + + LOGNOTICE( + 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(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); + ); + + try { + eventOperation(line, response_content); + } catch(RuntimeException &ex) { + ex.trace(); + } + + out_file << response_content << "\n"; + } + + in_file.close(); + out_file << "EOF\n"; + out_file.close(); +} + + +void Launcher::logStatisticsSamples(const std::string &conceptsList) throw() { + 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)); + } + } + } +} + + +bool Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) { + + bool result = true; + + LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION)); + if (operation == "") return result; // ignore + LOGDEBUG(anna::Logger::debug(anna::functions::asString("Operation: %s", operation.c_str()), ANNA_FILE_LOCATION)); + + // Default response: + response_content = "Operation processed with exception: "; + response_content += operation; + std::string opt_response_content = ""; // aditional response content + anna::DataBlock db_aux(true); + anna::diameter::codec::Message codecMsg; // auxiliary codec message + + // Singletons: + anna::testing::TestManager &testManager = anna::testing::TestManager::instantiate(); + + + /////////////////////////////////////////////////////////////////// + // Simple operations without arguments: + + // 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_content); + } + catch(anna::RuntimeException &ex) { + ex.trace(); + response_content = 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"; + return true; // OK + } + + // Counters dump on demand: + if(operation == "forceCountersRecord") { + forceCountersRecord(); + response_content = "Current counters have been dump to disk"; + return true; // OK + } + + // OAM & statistics: + if(operation == "show-oam") { + anna::xml::Node root("root"); + response_content = anna::xml::Compiler().apply(oamAsXML(&root)); + return true; // OK + } + if(operation == "show-stats") { + anna::xml::Node root("root"); + response_content = anna::xml::Compiler().apply(statsAsXML(&root)); + return true; // OK + } + + /////////////////////////////////////////////////////////////////// + // Tokenize operation + Tokenizer params; + params.apply(operation, "|", "" /* allow contiguous separators */); + int numParams = params.size() - 1; + + // 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 '' artificial token to ease further checkings: + if (param1 == "") param1 = ""; + if (param2 == "") param2 = ""; + if (param3 == "") param3 = ""; + if (param4 == "") param4 = ""; + if (param5 == "") param5 = ""; + if (param6 == "") param6 = ""; + if (param7 == "") param7 = ""; + if (param8 == "") param8 = ""; + if (param9 == "") param9 = ""; + if (param10 == "") param10 = ""; + if (param11 == "") 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 == "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). Check 'HELP.md' for more information."; + throw anna::RuntimeException(msg, ANNA_FILE_LOCATION); + } + + // 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'", contextFile.c_str()); + return true; // OK + } + + if(opType == "log-statistics-samples") { + logStatisticsSamples(param1); + response_content = anna::functions::asString("Log statistics samples for '%s' concepts", param1.c_str()); + return true; // OK + } + + // Change execution directory: + if(opType == "change-dir") { + if (param1 == "") param1 = a_initialWorkingDirectory; + result = (chdir(param1.c_str()) == 0); + + if (result) + response_content = "New execution directory configured: "; + else + response_content = "Cannot assign provided execution directory: "; + + response_content += param1; + return result; + } + + if(opType == "services") { + std::string servicesFile = ((numParams == 1) ? param1 : "services.xml"); + try { + loadServices(servicesFile, true /* bind entities */); + } + catch(anna::RuntimeException &ex) { + ex.trace(); + response_content = anna::functions::asString("Loaded services from file '%s' with errors", servicesFile.c_str()); + return false; + } + response_content = anna::functions::asString("Loaded services from file '%s'", servicesFile.c_str()); + return true; // OK + } + + // Host switch: + if(opType == "node") { + if (param1 != "") { + if (setWorkingNode(param1)) response_content = anna::functions::asString("Forced node is now '%s'", param1.c_str()); + } + else { + if (a_workingNode) { + response_content = "Working node is forced to be: \n\n"; + response_content += a_workingNode->asXMLString(); + } + else { + response_content = "Working node is automatic"; + } + } + return true; // OK + } + if(opType == "node_auto") { + a_workingNode = NULL; + response_content = "Working node has been set to automatic"; + return true; // OK + } + + // Operated host from possible forced-working node: + a_operatedHost = a_workingNode ? a_workingNode /* priority */: NULL /* auto */; + // Use later: + // If any message is managed: updateOperatedOriginHostWithMessage(codecMessage) + // To operate, use the exception-protected methods which never will return NULL: + // getOperatedHost(), getOperatedEntity(), getOperatedServer(), getOperatedEngine() + + + if(opType == "code") { + 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(hexString.c_str(), hexString.size()); + outfile.close(); + } else if(opType == "decode") { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + + // Decode + try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); } + + std::string xmlString = codecMsg.asXMLString(); + // write to outfile + std::ofstream outfile(param2.c_str(), std::ifstream::out); + outfile.write(xmlString.c_str(), xmlString.size()); + outfile.close(); + } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) { + + if(param1 != "") { + if(param2 != "") { + std::string key = param1; + key += "|"; + key += param2; + + if(opType == "hide") getOperatedEngine()->findClientSession(key)->hide(); + + if(opType == "show") getOperatedEngine()->findClientSession(key)->show(); + + if(opType == "hidden") opt_response_content = getOperatedEngine()->findClientSession(key)->hidden() ? "true" : "false"; + + if(opType == "shown") opt_response_content = getOperatedEngine()->findClientSession(key)->shown() ? "true" : "false"; + } else { + std::string address; + int port; + anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port); + + if(opType == "hide") getOperatedEngine()->findServer(address, port)->hide(); + + if(opType == "show") getOperatedEngine()->findServer(address, port)->show(); + + if(opType == "hidden") opt_response_content = getOperatedEngine()->findServer(address, port)->hidden() ? "true" : "false"; + + if(opType == "shown") opt_response_content = getOperatedEngine()->findServer(address, port)->shown() ? "true" : "false"; + } + } else { + if(opType == "hide") getOperatedEntity()->hide(); + + if(opType == "show") getOperatedEntity()->show(); + + if(opType == "hidden") opt_response_content = getOperatedEntity()->hidden() ? "true" : "false"; + + if(opType == "shown") opt_response_content = getOperatedEntity()->shown() ? "true" : "false"; + } + } else if((opType == "sendxml2e") || (opType == "sendhex2e")) { + anna::diameter::comm::Message *msg; + + 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 { + // Get DataBlock from file with hex content: + if(!getDataBlockFromHexFile(param1, db_aux)) + throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION); + msg = getOperatedHost()->createCommMessage(); + msg->setBody(db_aux); + try { if(getOperatedHost()->logEnabled()) codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); } + } + + bool success = getOperatedEntity()->send(msg); + getOperatedHost()->releaseCommMessage(msg); + + // 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() : ""; // shouldn't happen + getOperatedHost()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail); + } + } else if((opType == "burst")) { + + 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| loads the next diameter message into launcher burst. + // burst|start| starts the message sending with a certain initial load. + // burst|push| sends specific non-aynchronous load. + // burst|stop stops the burst cycle. + // burst|repeat|[[yes]|no] restarts the burst launch when finish. + // burst|send| send messages from burst list. The main difference with + // start/push operations is that burst won't be awaken. + // Externally we could control sending time (no request + // will be sent for answers). + // burst|goto| Updates current burst pointer position. + // burst|look| Show programmed burst message for order provided, current when missing. + + if(param1 == "clear") { + opt_response_content = "removed "; + opt_response_content += anna::functions::asString(getOperatedHost()->clearBurst()); + opt_response_content += " elements"; + } else if(param1 == "load") { + if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION); + + 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 = getOperatedHost()->loadBurstMessage(codecMsg.code()); + opt_response_content = "loaded '"; + opt_response_content += param2; + opt_response_content += "' file into burst list position "; + opt_response_content += 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 = getOperatedHost()->startBurst(initialLoad); + + if(processed > 0) { + opt_response_content = "initial load completed for "; + opt_response_content += 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 = getOperatedHost()->pushBurst(atoi(param2.c_str())); + + if(pushed > 0) { + opt_response_content = "pushed "; + opt_response_content += 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 = getOperatedHost()->popBurst(releaseLoad); + + if(popped > 0) { + opt_response_content = "burst popped for "; + opt_response_content += anna::functions::entriesAsString(popped, "message"); + } + } else if(param1 == "stop") { + int left = getOperatedHost()->stopBurst(); + + if(left != -1) { + opt_response_content += anna::functions::entriesAsString(left, "message"); + opt_response_content += " left to the end of the cycle"; + } + } else if(param1 == "repeat") { + if(param2 == "") param2 = "yes"; + + bool repeat = (param2 == "yes"); + getOperatedHost()->repeatBurst(repeat); + opt_response_content += (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 = getOperatedHost()->sendBurst(atoi(param2.c_str())); + + if(sent > 0) { + opt_response_content = "sent "; + opt_response_content += anna::functions::entriesAsString(sent, "message"); + } + } else if(param1 == "goto") { + if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION); + + opt_response_content = getOperatedHost()->gotoBurst(atoi(param2.c_str())); + } else if(param1 == "look") { + int order = ((param2 != "") ? atoi(param2.c_str()) : -1); + opt_response_content = "\n\n"; + opt_response_content += getOperatedHost()->lookBurst(order); + } else { + 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 == "test")) { + // test||[|parameters] Add a new step to the test case ... + // test|ttps| Starts/resume the provided number of time ticks per second (ttps). The ADML starts ... + // test|next[|] 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| Restarts the whole programmed test list when finished the amount number of times ... + // test|report|[|[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| Updates current test pointer position. + // 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| 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_content = "assigned new test launch rate to "; + opt_response_content += anna::functions::asString(atoi(param2.c_str())); + opt_response_content += " events per second"; + } + else { + opt_response_content += "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); + + int sync_amount = ((param2 != "") ? atoi(param2.c_str()) : 1); + + if (sync_amount < 1) + throw anna::RuntimeException("The parameter 'sync-amount' must be a positive integer value", ANNA_FILE_LOCATION); + + bool success = testManager.execTestCases(sync_amount); + + opt_response_content = (success ? "" : "not completely " /* completed cycle and no repeats, rare case */); + opt_response_content += "processed "; + opt_response_content += anna::functions::asString(sync_amount); + opt_response_content += ((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_content = "new in-progress limit: "; + opt_response_content += (limit != UINT_MAX) ? anna::functions::asString(limit) : ""; + } + else { + opt_response_content = "in-progress limit amount: "; + limit = testManager.getInProgressLimit(); + opt_response_content += (limit != UINT_MAX) ? anna::functions::asString(limit) : ""; + opt_response_content += "; currently there are "; + opt_response_content += anna::functions::asString(testManager.getInProgressCount()); + opt_response_content += " 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_content += 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); + + opt_response_content += (enable ? "report enabled " : "report disabled "); + opt_response_content += "for tests in '"; + opt_response_content += param2; + opt_response_content += "' 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); + + if(param2 == "") param2 = "yes"; + testManager.setDumpHex((param2 == "yes")); + opt_response_content += (testManager.getDumpHex() ? "report includes hexadecimal messages" : "report excludes hexadecimal messages"); + } + 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(param2 == "") param2 = "yes"; + testManager.setDumpStdout((param2 == "yes")); + opt_response_content += (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_content = "position updated for id provided ("; + } + else { + opt_response_content = "cannot found test id ("; + } + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + 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_content = "test executed for id provided ("; + } + else { + opt_response_content = "cannot found test id ("; + } + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + 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); + + int id = ((param2 != "") ? atoi(param2.c_str()) : -1); + anna::testing::TestCase *testCase = testManager.findTestCase(id); + + if (testCase) { + response_content = testCase->asXMLString(); + return true; // OK + } + else { + result = false; + if (id == -1) { + opt_response_content = "no current test case detected (testing started ?)"; + } + else { + opt_response_content = "cannot found test id ("; + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + } + } + 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); + + int id = ((param2 != "") ? atoi(param2.c_str()) : -1); + anna::testing::TestCase *testCase = testManager.findTestCase(id); + + if (testCase) { + response_content = anna::testing::TestCase::asText(testCase->getState()); + return testCase->isSuccess(); + } + else { + result = false; + if (id == -1) { + opt_response_content = "no current test case detected (testing started ?)"; + } + else { + opt_response_content = "cannot found test id ("; + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + } + } + 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_content = "interactive mode disabled"; + } + else { + testCase->addInteractiveAmount(amount); + opt_response_content = "added interactive amount of "; + opt_response_content += anna::functions::asString(amount); + opt_response_content += " units"; + if (amount == 0) opt_response_content += " (0: freezing a non-interactive testcase, no effect on already interactive)"; + } + opt_response_content += " for test case id "; + opt_response_content += anna::functions::asString(id); + } + else { + result = false; + opt_response_content = "cannot found test id ("; + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + } + 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_content = "test "; + opt_response_content += param2; + opt_response_content += " reset for id "; + opt_response_content += anna::functions::asString(id); + opt_response_content += done ? ": done": ": not done"; + } + else { + if (id == -1) { + bool anyReset = testManager.resetPool(param2 == "hard"); + opt_response_content = param2; opt_response_content += " reset have been sent to all programmed tests: "; opt_response_content += anyReset ? "some/all have been reset" : "nothing was reset"; + } + else { + result = false; + opt_response_content = "cannot found test id ("; + opt_response_content += anna::functions::asString(id); + opt_response_content += ")"; + } + } + } + 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 (param2 != "soft" && param2 != "hard") + throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION); + + testManager.setAutoResetHard(param2 == "hard"); + opt_response_content += 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); + + opt_response_content = 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); + + opt_response_content = anna::functions::asString("%lu", testManager.getFinishedCount()); + } + 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); + + if (testManager.clearPool()) { + opt_response_content = "all the programmed test cases have been dropped"; + } + else { + opt_response_content = "there are not programmed test cases to be removed"; + } + } + else if(param1 == "junit") { + response_content = testManager.junitAsXMLString(); + return true; // OK + } + else if(param1 == "summary-counts") { + response_content = testManager.summaryCounts(); + return true; // OK + } + else if(param1 == "summary-states") { + response_content = testManager.summaryStates(); + return true; // OK + } + else if(param1 == "summary") { + response_content = 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|| + // description| + // ip-limit[|] + // timeout| + // sendxml2e| [|] + // sendxml2c| [|] + // delay| [msecs] + // wait|[code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId] + // wait-answer| + // wait-xml |[|strict] + // wait-hex |[|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); + 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); + 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: + //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: + pos = regexp.find("Origin-State-Id", 0u); + 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); + } + } + + } else if((opType == "sendxml2c") || (opType == "sendhex2c")) { + anna::diameter::comm::Message *msg; + + 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) + + 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); + msg = getOperatedHost()->createCommMessage(); + msg->setBody(db_aux); + } + + bool success = getOperatedServer()->send(msg); + getOperatedHost()->releaseCommMessage(msg); + + // Detailed log: + if(getOperatedHost()->logEnabled()) { + anna::diameter::comm::ServerSession *usedServerSession = getOperatedServer()->getLastUsedResource(); + std::string detail = usedServerSession ? usedServerSession->asString() : ""; // shouldn't happen + getOperatedHost()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail); + } + } else if(opType == "loadxml") { + codecMsg.loadXMLFile(param1); + response_content = codecMsg.asXMLString(); + return true; // OK + } else if(opType == "diameterServerSessions") { + int diameterServerSessions = atoi(param1.c_str()); + getOperatedServer()->setMaxConnections(diameterServerSessions); + + } else if(opType == "answerxml2c") { + if(param1 == "") { // programmed answers FIFO's to stdout + response_content = getOperatedServer()->getReactingAnswers()->asString("ANSWERS TO CLIENT"); + return true; // OK + } else if (param1 == "rotate") { + getOperatedServer()->getReactingAnswers()->rotate(true); + } else if (param1 == "exhaust") { + getOperatedServer()->getReactingAnswers()->rotate(false); + } else if (param1 == "clear") { + getOperatedServer()->getReactingAnswers()->clear(); + } else if (param1 == "dump") { + getOperatedServer()->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)); + getOperatedServer()->getReactingAnswers()->addMessage(code, message); + } + } else if(opType == "answerxml2e") { + + if(param1 == "") { // programmed answers FIFO's to stdout + response_content = getOperatedEntity()->getReactingAnswers()->asString("ANSWERS TO ENTITY"); + return true; // OK + } else if (param1 == "rotate") { + getOperatedEntity()->getReactingAnswers()->rotate(true); + } else if (param1 == "exhaust") { + getOperatedEntity()->getReactingAnswers()->rotate(false); + } else if (param1 == "clear") { + getOperatedEntity()->getReactingAnswers()->clear(); + } else if (param1 == "dump") { + getOperatedEntity()->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)); + getOperatedEntity()->getReactingAnswers()->addMessage(code, message); + } + } else { + throw anna::RuntimeException("Wrong body content format on HTTP Request. Check 'HELP.md' for more information.", ANNA_FILE_LOCATION); + } + + // HTTP response + response_content = "Operation correctly processed: "; response_content += operation; + if (opt_response_content != "") { + response_content += " => "; + response_content += opt_response_content; + } + + 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: + 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 +throw() { + 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 +throw() { + anna::xml::Node* result = parent->createChild("Statistics"); + + // Statistics: + anna::statistics::Engine::instantiate().asXML(result); + + return result; +}