1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
10 #include <sstream> // std::istringstream
11 #include <iostream> // std::cout
12 #include <math.h> // ceil
16 #include <anna/timex/Engine.hpp>
17 #include <anna/statistics/Engine.hpp>
18 #include <anna/diameter/codec/functions.hpp>
19 #include <anna/diameter/codec/Engine.hpp>
20 #include <anna/diameter/codec/EngineManager.hpp>
21 #include <anna/http/Transport.hpp>
22 #include <anna/diameter/stack/Engine.hpp>
23 #include <anna/diameter/helpers/base/functions.hpp>
24 #include <anna/time/functions.hpp>
25 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
26 #include <anna/xml/xml.hpp>
29 #include <Launcher.hpp>
30 #include <RealmNode.hpp>
31 #include <MyDiameterEngine.hpp>
32 #include <TestManager.hpp>
33 #include <TestCase.hpp>
36 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.in"
37 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.out"
40 const char *ServicesDTD = "\
41 <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
42 <!-- Diameter services DTD -->\n\
44 <!ELEMENT services (stack*, node*)>\n\
46 <!ELEMENT stack EMPTY>\n\
47 <!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\
51 id: Normally the id corresponds to the Application-Id for which the dictionary provided is designed\n\
52 (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
53 for processed messages).\n\
54 dictionary: Path to the dictionary file.\n\
55 validationMode: Sets the validation mode. Default is 'AfterDecoding'.\n\
56 validationDepth: Sets the validation depth. Default is 'FirstError'.\n\
57 fixMode: Sets the fix mode. Default is 'BeforeEncoding'.\n\
58 ignoreFlagsOnValidation: Ignore flags during message validation. Default is 'no'.\n\
61 <!ELEMENT node EMPTY>\n\
62 <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED 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>\n\
66 originRealm: Node identifier (Origin-Realm name).\n\
67 applicationId: The Application-Id provided must exists as a registered 'stack id'.\n\
68 originHost: Diameter application host name (system name). If missing, process sets o.s. hostname.\n\
69 Note that if you have two or more realms, the names must be different.\n\
70 cer: User defined CER path file to be encoded to establish diameter connections.\n\
71 If missing, will be harcoded.\n\
72 dwr: User defined DWR path file to be encoded for diameter protocol keep alive.\n\
73 If missing, will be harcoded.\n\
74 allowedInactivityTime: Milliseconds for the maximum allowed inactivity time on server sessions born over the\n\
75 local server before being reset. If missing, default value of 90000 will be assigned.\n\
76 tcpConnectDelay: Milliseconds to wait TCP connect to any server. If missing, default value of 200 will\n\
78 answersTimeout: Milliseconds to wait pending application answers from diameter peers. If missing,\n\
79 default value of 10000 will be assigned.\n\
80 ceaTimeout: Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'\n\
82 watchdogPeriod: Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default\n\
83 value of 30000 will be assigned.\n\
84 entity: Target diameter entity (comma-separated '<address>:<port>' format).\n\
85 For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled.\n\
86 entityServerSessions: Diameter entity server sessions (0: diameter entity disabled). Default value of 1.\n\
87 diameterServer: Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.\n\
88 If missing, no local server will be enabled.\n\
89 diameterServerSessions: Diameter own server available connections (0: diameter server disabled). Default value of 1.\n\
90 Negative value implies no limit accepting incoming connections.\n\
91 balance: Balance over entity servers instead of doing standard behaviour (first primary, secondary\n\
92 if fails, etc.). Default value 'no'.\n\
93 sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part\n\
94 will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR\n\
95 analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;\n\
96 usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart').\n\
97 retries: Expired responses will cause a number of request retransmissions. Disabled by default (0 retries).\n\
98 log: Process log file (operations result, traffic log, etc.). By default '<originRealm>.launcher.log'.\n\
99 Empty string or \"null\" name, to disable. Warning: there is no rotation for log files\n\
100 (use logrotate or whatever you consider).\n\
101 splitLog: Splits log file (appends to log filename, extensions with the type of event: see help on\n\
102 startup information-level traces). No log files for code/decode and load operations are created.\n\
103 Default value 'no'.\n\
104 detailedLog: Insert detailed information at log files. Should be disabled on automatic tests. Useful on\n\
105 'balance' mode to know messages flow along the sockets. Default value 'no'.\n\
106 dumpLog: Write to disk every incoming/outcoming message named as:\n\
107 '<originRealm>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'\n\
108 Default value 'no'.\n\
109 burstLog: Burst operations log file. By default '<originRealm>.launcher.burst'. Empty string or \"null\" name, to disable.\n\
110 Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each\n\
111 burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst\n\
112 list size, plus OTA requests when changed.\n\
119 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
121 a_counterRecorder = NULL;
122 a_admlMinResolution = 2 * anna::timex::Engine::minResolution; // 2*10 = 20 ms; 1000/20 = 50 ticks per second;
123 //a_admlMinResolution = (anna::Millisecond)100;
124 a_counterRecorderClock = NULL;
127 a_workingNode = NULL;
129 a_httpServerSocket = NULL;
135 void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) {
137 CommandLine& cl(anna::CommandLine::instantiate());
138 bool allLogsDisabled = cl.exists("disableLogs");
140 //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
141 const anna::xml::Attribute *id, *dictionary;
143 // <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED 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>
144 const anna::xml::Attribute *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
145 *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
146 *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
147 *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
148 // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
151 anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
152 anna::diameter::stack::Dictionary *d;
153 const anna::diameter::stack::Dictionary *bpd = NULL; // base protocol dictionary
155 // Codec engine manager:
156 anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
157 anna::diameter::codec::Engine *ce;
159 ///////////////////////////////////////////
160 // APPLICATION MESSAGE OAM MODULE SCOPES //
161 ///////////////////////////////////////////
162 // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
163 anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
164 appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
165 static int scope_id = 3;
166 unsigned int id_value;
167 std::string codecEngineName;
169 for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
170 std::string nodeName = (*it)->getName();
172 if(nodeName == "stack") {
174 id = (*it)->getAttribute("id");
175 dictionary = (*it)->getAttribute("dictionary");
176 id_value = id->getIntegerValue();
178 if (stackEngine.getDictionary(id_value)) { // Ignore (but don't fail) dictionary load with same stack id already registered
179 LOGWARNING(anna::Logger::warning(anna::functions::asString("Ignore dictionary load for stack id already registered: %llu", id_value), ANNA_FILE_LOCATION));
184 d = stackEngine.createDictionary(id_value, dictionary->getValue());
185 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Created dictionary (%p) for stack id %llu", d, id_value), ANNA_FILE_LOCATION));
187 // OAM module for counters:
188 appMsgOamModule.createStackCounterScope(scope_id, id_value /* application-id */);
191 } catch(anna::RuntimeException &ex) {
192 //_exit(ex.asString());
196 bpd = d; // base protocol dictionary in case of monostack. If multistack, will be calculated later
198 // Create codec engine and register it in the codec engine manager:
199 codecEngineName = anna::functions::asString("CodecEngineForStackId_%llu", id_value);
200 ce = new anna::diameter::codec::Engine(codecEngineName.c_str(), d);
201 em.registerCodecEngine(id_value, ce);
203 // Codec engine configuration:
204 const anna::xml::Attribute *vm_attr = (*it)->getAttribute("validationMode", false /* no exception */);
205 const anna::xml::Attribute *vd_attr = (*it)->getAttribute("validationDepth", false /* no exception */);
206 const anna::xml::Attribute *fm_attr = (*it)->getAttribute("fixMode", false /* no exception */);
207 const anna::xml::Attribute *if_attr = (*it)->getAttribute("ignoreFlags", false /* no exception */);
209 std::string vm_value = vm_attr ? vm_attr->getValue() : "AfterDecoding";
210 std::string vd_value = vd_attr ? vd_attr->getValue() : "FirstError";
211 std::string fm_value = fm_attr ? fm_attr->getValue() : "BeforeEncoding";
213 anna::diameter::codec::Engine::ValidationMode::_v vm;
214 if (vm_value == "BeforeEncoding") vm = anna::diameter::codec::Engine::ValidationMode::BeforeEncoding;
215 else if (vm_value == "AfterDecoding") vm = anna::diameter::codec::Engine::ValidationMode::AfterDecoding;
216 else if (vm_value == "Always") vm = anna::diameter::codec::Engine::ValidationMode::Always;
217 else if (vm_value == "Never") vm = anna::diameter::codec::Engine::ValidationMode::Never;
218 ce->setValidationMode(vm);
220 anna::diameter::codec::Engine::ValidationDepth::_v vd;
221 if (vd_value == "Complete") vd = anna::diameter::codec::Engine::ValidationDepth::Complete;
222 else if (vd_value == "FirstError") vd = anna::diameter::codec::Engine::ValidationDepth::FirstError;
223 ce->setValidationDepth(vd);
225 anna::diameter::codec::Engine::FixMode::_v fm;
226 if (fm_value == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
227 else if (fm_value == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
228 else if (fm_value == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
229 else if (fm_value == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
232 bool if_value = (if_attr ? (if_attr->getValue() == "yes") : false);
233 ce->ignoreFlagsOnValidation(if_value);
237 // Show loaded stacks:
238 std::cout << "Stacks currently loaded:" << std::endl;
239 std::cout << anna::functions::tab(stackEngine.asString(false /* light */)) << std::endl;
241 // Basic checking for multistack:
242 bool multistack = (stackEngine.stack_size() > 1);
244 bpd = stackEngine.getDictionary(0);
246 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);
250 for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
251 std::string nodeName = (*it)->getName();
253 if(nodeName == "node") {
255 originRealm = (*it)->getAttribute("originRealm");
256 appId = (*it)->getAttribute("applicationId");
257 originHost = (*it)->getAttribute("originHost", false /* no exception */);
258 cer = (*it)->getAttribute("cer", false /* no exception */);
259 dwr = (*it)->getAttribute("dwr", false /* no exception */);
260 allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */);
261 tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */);
262 answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */);
263 ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */);
264 watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */);
265 entity = (*it)->getAttribute("entity", false /* no exception */);
266 entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */);
267 diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */);
268 diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */);
269 balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no)
270 sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin)
271 retries = (*it)->getAttribute("retries", false /* no exception */);
272 log = (*it)->getAttribute("log", false /* no exception */);
273 splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no)
274 detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no)
275 dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no)
276 burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no)
279 realm_nodes_it nodeIt = a_nodes.find(originRealm->getValue());
280 if (nodeIt != a_nodes.end()) {
281 std::string msg = "Already registered node name (Origin-Realm): "; msg += originRealm->getValue();
282 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
285 unsigned int applicationId = appId->getIntegerValue();
286 if (!stackEngine.getDictionary(applicationId)) {
287 std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
288 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
291 // Engine time measures checking & assignment:
292 anna::Millisecond allowedInactivityTimeMs(90000);
293 anna::Millisecond tcpConnectDelayMs(200);
294 anna::Millisecond answersTimeoutMs(10000);
295 anna::Millisecond ceaTimeoutMs(10000);
296 anna::Millisecond watchdogPeriodMs(30000);
298 if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue());
299 if (tcpConnectDelay) tcpConnectDelayMs = checkTimeMeasure("tcpConnectDelay", tcpConnectDelay->getValue());
300 if (answersTimeout) answersTimeoutMs = checkTimeMeasure("answersTimeout", answersTimeout->getValue());
301 if (ceaTimeout) ceaTimeoutMs = checkTimeMeasure("ceaTimeout", ceaTimeout->getValue());
302 if (watchdogPeriod) watchdogPeriodMs = checkTimeMeasure("watchdogPeriod", watchdogPeriod->getValue());
304 // Checking command line parameters
305 std::string sessionBasedModelsType;
306 if(sessionBasedModelsClientSocketSelection) {
307 sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue();
308 if((sessionBasedModelsType != "SessionIdHighPart") && (sessionBasedModelsType != "SessionIdOptionalPart") && (sessionBasedModelsType != "RoundRobin")) {
309 throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
313 int retransmissions = retries ? retries->getIntegerValue() : 0;
314 if(retransmissions < 0) {
315 throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION);
318 // Create new Node instance /////////////////////////////////////////////////////////////////
319 a_workingNode = new RealmNode(originRealm->getValue(), applicationId, bpd);
320 MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine();
321 /////////////////////////////////////////////////////////////////////////////////////////////
324 commEngine->setMaxConnectionDelay(tcpConnectDelayMs);
325 commEngine->setWatchdogPeriod(watchdogPeriodMs);
327 // Realm information:
328 if (originHost) commEngine->setHost(originHost->getValue());
329 commEngine->setRealm(originRealm->getValue());
333 int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1;
336 // Number of sessions:
337 commEngine->setNumberOfClientSessionsPerServer(sessions);
339 // Client CER and DWR
340 std::string cerPathfile = cer ? cer->getValue() : "";
341 std::string dwrPathfile = dwr ? dwr->getValue() : "";
342 commEngine->setClientCERandDWR(cerPathfile, dwrPathfile);
344 // Register one entity for this engine:
345 a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs);
346 a_workingNode->setRequestRetransmissions(retransmissions);
347 a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsType);
348 a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings
349 if (eventOperation) a_workingNode->getEntity()->bind();
355 int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1;
356 a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs);
360 if (!allLogsDisabled) {
361 std::string realm = commEngine->getRealm();
362 std::string s_log = realm + ".launcher.log"; if (log) s_log = log->getValue();
363 bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false);
364 bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false);
365 bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false);
366 std::string s_burstLog = realm + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue();
367 a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog);
371 // Lazy initialization for comm engine:
372 if (eventOperation) commEngine->lazyInitialize();
374 // Node and Codec Engine registration ///////////////////////////////////////////////////////
375 a_nodes[originRealm->getValue()] = a_workingNode;
376 /////////////////////////////////////////////////////////////////////////////////////////////
381 a_workingNode = NULL; // by default, mode auto
383 // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started,
384 // but this don't care because application startComponents() -> initialize() -> do_initialize() -> do nothing.
385 // And when stopped, running state is not checked and it will be stopped anyway.
389 void Launcher::loadServices(const std::string & xmlPathFile, bool eventOperation) throw(anna::RuntimeException) {
391 if (xmlPathFile == "null" || xmlPathFile == "") {
392 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));
397 std::string trace = "Loading ADML services file '";
398 trace += xmlPathFile;
400 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
402 anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
403 anna::xml::DTDMemory xmlDTD;
404 const anna::xml::Node *rootNode;
405 xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
406 xmlDTD.initialize(ServicesDTD);
408 rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
410 catch (anna::RuntimeException &ex) {
412 std::string msg = "Services DTD schema:\n\n";
414 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
420 std::string trace = "Loaded XML file (";
421 trace += xmlPathFile;
423 trace += anna::xml::Compiler().apply(rootNode);
424 anna::Logger::debug(trace, ANNA_FILE_LOCATION);
426 servicesFromXML(rootNode, eventOperation);
430 anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const std::string &value) throw(anna::RuntimeException) {
432 if(anna::functions::isLike("^[0-9]+$", value)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
434 std::istringstream ( value ) >> msecs;
436 if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
437 std::string msg = "Configuration value for '";
439 msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: ";
440 msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
441 throw RuntimeException(msg, ANNA_FILE_LOCATION);
445 std::string msg = "Configuration value for '";
447 msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes).";
448 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
451 if(msecs <= a_timeEngine->getResolution()) {
452 std::string msg = "Configuration value for '";
454 msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: ";
455 msg += anna::functions::asString(a_timeEngine->getResolution());
456 throw RuntimeException(msg, ANNA_FILE_LOCATION);
459 return (anna::Millisecond)msecs; // ok
462 // Non-integer exception:
463 std::string msg = "Configuration error for '";
467 msg += "': must be a non-negative integer number";
468 throw RuntimeException(msg, ANNA_FILE_LOCATION);
471 bool Launcher::setWorkingNode(const std::string &name) throw() {
474 realm_nodes_it nodeIt = a_nodes.find(name);
475 if (nodeIt == a_nodes.end()) {
477 std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
478 anna::Logger::warning(msg, ANNA_FILE_LOCATION);
482 a_workingNode = const_cast<RealmNode*>(nodeIt->second);
489 RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw(anna::RuntimeException) {
490 realm_nodes_it it = a_nodes.find(realmName);
491 if (it != a_nodes.end()) return it->second;
492 throw anna::RuntimeException(anna::functions::asString("There is no realm node registered as '%s' (set Origin-Realm avp correctly or force a specific realm with 'node' operation)", realmName.c_str()), ANNA_FILE_LOCATION);
495 RealmNode *Launcher::getRealmNode(const anna::diameter::codec::Message &message) const throw(anna::RuntimeException) {
496 std::string originRealm = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
497 return (getRealmNode(originRealm));
500 void Launcher::updateOperatedRealmNodeWithMessage(const anna::diameter::codec::Message &message) throw(anna::RuntimeException) {
501 if (!a_operatedRealm) // priority for working node by mean 'node' operation
502 a_operatedRealm = getRealmNode(message);
505 RealmNode *Launcher::getOperatedRealm() const throw(anna::RuntimeException) {
507 throw anna::RuntimeException("Realm Node not identified (try to force a specific realm with 'node' operation)", ANNA_FILE_LOCATION);
509 return a_operatedRealm;
512 MyDiameterEntity *Launcher::getOperatedEntity() const throw(anna::RuntimeException) {
513 MyDiameterEntity *result = getOperatedRealm()->getEntity();
515 throw anna::RuntimeException("No entity configured for the operated Realm Node", ANNA_FILE_LOCATION);
519 MyLocalServer *Launcher::getOperatedServer() const throw(anna::RuntimeException) {
520 MyLocalServer *result = getOperatedRealm()->getDiameterServer();
522 throw anna::RuntimeException("No local server configured for the operated Realm Node", ANNA_FILE_LOCATION);
526 MyDiameterEngine *Launcher::getOperatedEngine() const throw(anna::RuntimeException) {
527 return getOperatedRealm()->getMyDiameterEngine(); // never will be NULL
530 void Launcher::initialize()
531 throw(anna::RuntimeException) {
532 anna::comm::Application::initialize();
533 CommandLine& cl(anna::CommandLine::instantiate());
534 anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
535 a_communicator = new MyCommunicator(workMode);
536 a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, a_admlMinResolution);
537 TestManager::instantiate().setTimerController(a_timeEngine);
539 // Counters record procedure:
540 const char *varname = "cntRecordPeriod";
541 anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000;
542 if(cntRecordPeriod != 0) {
543 a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
544 std::string cntDir = ".";
545 if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
546 a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
549 // Testing framework:
550 std::string tmDir = ".";
551 if(cl.exists("tmDir")) tmDir = cl.getValue("tmDir");
552 TestManager::instantiate().setReportsDirectory(tmDir);
555 if(cl.exists("trace"))
556 anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
558 // Load launcher services:
559 loadServices(cl.getValue("services")); // before run (have components to be created)
563 throw(anna::RuntimeException) {
564 LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
565 CommandLine& cl(anna::CommandLine::instantiate());
566 anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
569 a_start_time.setNow();
571 anna::statistics::Engine::instantiate().enable();
574 // Help on startup traces:
575 anna::Logger::information(help(), ANNA_FILE_LOCATION);
576 // Test messages dtd:
577 std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n";
578 msg += anna::diameter::codec::MessageDTD;
579 anna::Logger::information(msg, ANNA_FILE_LOCATION);
583 if(cl.exists("httpServer")) {
584 anna::comm::Network& network = anna::comm::Network::instantiate();
587 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
588 //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
589 const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
590 a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
593 ///////////////////////////////
594 // Diameter library COUNTERS //
595 ///////////////////////////////
596 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
597 oamDiameterComm.initializeCounterScope(1); // 1000 - 1999
598 oamDiameterComm.enableCounters();
599 oamDiameterComm.enableAlarms();
600 anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
601 oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999
602 oamDiameterCodec.enableCounters();
603 oamDiameterCodec.enableAlarms();
608 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
609 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/);
610 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
611 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/);
612 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
613 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5);
614 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6);
615 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7);
616 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8);
617 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9);
618 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10);
619 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11);
620 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12);
621 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13);
622 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14);
623 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15);
624 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16);
625 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17);
626 /* Diameter Base (capabilities exchange & keep alive) */
628 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18);
629 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19);
630 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
631 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21);
632 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22);
633 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
634 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24);
635 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25);
636 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
638 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
639 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28);
640 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29);
641 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
642 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31);
643 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32);
644 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
645 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34);
646 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35);
647 /* server socket operations (enable/disable listening port for any local server) */
648 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
649 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
652 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38);
653 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39);
654 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40);
655 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41);
656 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42);
657 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43);
658 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44);
659 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45);
660 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
662 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47);
663 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48);
664 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
665 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50);
666 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51);
667 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52);
668 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53);
669 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54);
670 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55);
671 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56);
672 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57);
673 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmitted, "", 58);
674 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnClientSession, "", 59);
675 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnServerSession, "", 60);
676 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 61);
677 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 62);
678 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 63);
683 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/);
684 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
685 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/);
686 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/);
687 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/);
688 /* Message decoding */
689 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
690 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/);
692 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
693 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/);
694 /* Message validation */
695 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
696 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/);
697 /* Level validation */
698 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/);
699 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/);
700 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/);
701 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/);
702 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
703 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/);
706 /////////////////////////////////
707 // Counter recorder associated //
708 /////////////////////////////////
709 if(a_counterRecorderClock) {
710 oamDiameterComm.setCounterRecorder(a_counterRecorder);
711 oamDiameterCodec.setCounterRecorder(a_counterRecorder);
712 anna::diameter::comm::ApplicationMessageOamModule::instantiate().setCounterRecorder(a_counterRecorder);
713 a_timeEngine->activate(a_counterRecorderClock); // start clock
716 // Log statistics concepts
717 if(cl.exists("logStatisticSamples")) {
718 std::string list = cl.getValue("logStatisticSamples");
719 anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
722 if(statEngine.enableSampleLog(/* -1: all concepts */))
723 LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
726 lst.apply(cl.getValue("logStatisticSamples"), ",");
728 if(lst.size() >= 1) {
729 anna::Tokenizer::const_iterator tok_min(lst.begin());
730 anna::Tokenizer::const_iterator tok_max(lst.end());
731 anna::Tokenizer::const_iterator tok_iter;
734 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
735 conceptId = atoi(anna::Tokenizer::data(tok_iter));
737 if(statEngine.enableSampleLog(conceptId))
738 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
745 // Start client connections //////////////////////////////////////////////////////////////////////////////////
746 MyDiameterEntity *entity;
747 for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
748 entity = it->second->getEntity();
749 if (entity) entity->bind();
752 // Go into communicator poll
753 // Reconnection period (tcp reconnect retry time):
754 const char *varname = "reconnectionPeriod";
755 anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000;
757 a_communicator->setRecoveryTime(reconnectionPeriod);
758 if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
759 a_communicator->accept();
763 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
765 static char buffer[8192];
766 std::ifstream infile(pathfile.c_str(), std::ifstream::in);
768 if(infile.is_open()) {
770 std::string hexString(buffer, strlen(buffer));
771 // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
772 hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
774 std::string msg = "Hex string (remove colons if exists): ";
776 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
778 anna::functions::fromHexString(hexString, db);
787 void Launcher::resetStatistics() throw() {
789 a_workingNode->getMyDiameterEngine()->resetStatistics();
792 for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
793 it->second->getMyDiameterEngine()->resetStatistics();
798 void Launcher::resetCounters() throw() {
799 anna::diameter::comm::OamModule::instantiate().resetCounters();
800 anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
801 anna::diameter::codec::OamModule::instantiate().resetCounters();
804 void Launcher::signalUSR2() throw(anna::RuntimeException) {
806 std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
807 msg += SIGUSR2_TASKS_INPUT_FILENAME;
808 msg += "' (results will be written at '";
809 msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
811 anna::Logger::notice(msg, ANNA_FILE_LOCATION);
816 std::string response_content;
817 std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
818 std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
820 if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
821 if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
823 while(getline(in_file, line)) {
825 std::string msg = "Processing line: ";
827 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
831 eventOperation(line, response_content);
832 } catch(RuntimeException &ex) {
836 out_file << response_content << "\n";
844 std::string Launcher::help() const throw() {
845 std::string result = "\n";
846 result += "\n ------------- HELP -------------\n";
848 result += "\nOVERVIEW";
849 result += "\n--------";
851 result += "\nThe ADML (ANNA Diameter Multirealm Launcher) process is a multi-realm node with client and server";
852 result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server (i.e. to";
853 result += "\n simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.), and balancer";
854 result += "\n systems to provide failover to external round-robin launchers. Also, auxiliary encoder/decoder/loader";
855 result += "\n function could be deployed to reinterpret certain external flow and send it to another process.";
857 result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
858 result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
859 result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
860 result += "\n generation, expiration control and many more features.";
862 result += "\nThe ADML process can easily configure a many realm nodes as needed, which will have own endpoints.";
863 result += "\nYou should avoid loop configurations (client and server for that client) because automatic forwarding,";
864 result += "\n is implemented and this would get in a never ending cycle when a request is sent.";
866 result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
867 result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
869 result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
870 result += "\n kill -10 <pid>";
872 result += "\n kill -s SIGUSR1 <pid>";
873 result += "\n and then";
874 result += "\n vi /var/tmp/anna.context.<pid>";
876 result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
877 result += "\n handlers, diameter stacks, etc.), and a powerful log module could dump all the events";
878 result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
879 result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
880 result += "\n measurements.";
882 result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
885 result += "\nCOMMAND LINE";
886 result += "\n------------";
888 result += "\nStart the launcher process without arguments in order to see all the startup configuration";
889 result += "\n posibilities, many of which could be modified on the air through the management interface";
890 result += "\n (we will talk later about this great feature). There is only one mandatory parameter which";
891 result += "\n is the services definition: --services <services xml file>. You must follow the dtd schema";
892 result += "\n to build a valid services xml file. Some basic examples are:";
894 result += "\nClient configuration:";
896 result += "\n<services>";
897 result += "\n <!-- Stacks -->";
898 result += "\n <stack id=\"0\" dictionary=\"dictionary.xml\"/>";
900 result += "\n <!-- Nodes -->";
901 result += "\n <node originRealm=\"ADML-client\" applicationId=\"0\" entity=\"localhost:3868\"/>";
902 result += "\n</services>";
904 result += "\nServer configuration:";
906 result += "\n<services>";
907 result += "\n <!-- Stacks -->";
908 result += "\n <stack id=\"0\" dictionary=\"dictionary.xml\"/>";
910 result += "\n <!-- Nodes -->";
911 result += "\n <node originRealm=\"ADML-server\" applicationId=\"0\" diameterServer=\"localhost:3868\"/>";
912 result += "\n</services>";
914 result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
915 result += "\n will need to program the answers to be replied through the operations interface. To balance the";
916 result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
917 result += "\n arguments in order to define the balancing behaviour. To make hybrid setups you only must mix the realms:";
919 result += "\nClient and server configuration:";
921 result += "\n<services>";
922 result += "\n <!-- Stacks -->";
923 result += "\n <stack id=\"16777236\" dictionary=\"dictionary_Rx.xml\"/>";
924 result += "\n <stack id=\"16777238\" dictionary=\"dictionary_Gx.xml\"/>";
925 result += "\n <stack id=\"0\" dictionary=\"dictionary_base.xml\"/>";
927 result += "\n <!-- Nodes -->";
928 result += "\n <node originRealm=\"ADML-Rx-client\" applicationId=\"16777236\" entity=\"localhost:3868\" cer=\"cer_Rx.xml\"/>";
929 result += "\n <node originRealm=\"ADML-Gx-client\" applicationId=\"16777238\" entity=\"localhost:3868\" cer=\"cer_Gx.xml\"/>";
930 result += "\n</services>";
933 result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
934 result += "\n as shown in the hybrid former example. Note that the base protocol stack must be registered because";
935 result += "\n the configuration corresponds to a multistack process which change the stack using the application-id";
936 result += "\n processed (0 in the case of base protocol messages: CER, CEA, DWR, DWA, DPR, DPA).";
938 result += "\nDYNAMIC OPERATIONS";
939 result += "\n------------------";
941 result += "\nADML supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
942 result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
943 result += "\n separated by pipes. These are the available commands:";
945 result += "\n--------------------------------------------------------------------------------------- General purpose";
947 result += "\nhelp This help.";
949 result += "\n--------------------------------------------------------------------------------------- Node management";
951 result += "\nnode[|<name>] Selects a context working node by mean a registered name.";
952 result += "\n All the subsequent operations will be forced to work with";
953 result += "\n this node, which makes possible some rare scenarios like";
954 result += "\n sending unexpected messages on remote peers. This is also";
955 result += "\n useful for some operations in order to restrict the scope";
956 result += "\n of action (statistics, communication visibility, etc.).";
957 result += "\n Empty parameter will show the current configuration.";
959 result += "\nnode_auto Returns to the default behaviour (smart node selection).";
960 result += "\n Depending on the operation, this could imply a global";
961 result += "\n action scope, affecting to all the registered realms.";
962 result += "\n This should be the normal configuration. Take into";
963 result += "\n account that if you fix the working node, this could";
964 result += "\n affect to things like test programming: communication";
965 result += "\n resources will override those which would be inferred";
966 result += "\n from programmed messages Origin-Realm avps.";
968 result += "\n------------------------------------------------------------------------------------ Parsing operations";
970 result += "\ncode|<source_file>|<target_file> Encodes source file (pathfile) into target file (pathfile).";
971 result += "\ndecode|<source_file>|<target_file> Decodes source file (pathfile) into target file (pathfile).";
972 result += "\nloadxml|<source_file> Reinterpret xml source file (pathfile).";
974 result += "\n------------------------------------------------------------------------------------------- Hot changes";
976 result += "\nservices[|source file] Adds and starts the services specified in the xml file provided.";
977 result += "\n (if missing, the file 'services.xml' will be used). This is used";
978 result += "\n to load new nodes once the ADML is started, regardless if command";
979 result += "\n line '--services' parameter was used or not. Those services which";
980 result += "\n are not correctly loaded will be ignored to keep the process alive.";
981 result += "\n If you need to load services as deltas, you must firstly load the";
982 result += "\n diameter base dictionary with stack id 0, because all the realms";
983 result += "\n will use this dictionary to encode/decode base protocol messages";
984 result += "\n managed by the communication engine.";
986 result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter";
987 result += "\n server socket.";
988 result += "\ncontext[|target file] Application context could also be written by mean this operation,";
989 result += "\n and not only through SIGUSR1. If optional path file is missing,";
990 result += "\n default '/var/tmp/anna.context.<pid>' will be used.";
991 result += "\ncollect Reset statistics and counters to start a new test stage of";
992 result += "\n performance measurement. Context data can be written at";
993 result += "\n '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
994 result += "\n or sending operation 'context|[target file]'.";
995 result += "\n This operation applies over all the registered realm nodes";
996 result += "\n except if one specific working node has been set.";
997 result += "\nforceCountersRecord Forces dump to file the current counters of the process.";
998 result += "\nshow-oam Dumps current counters of the process. This is also done at";
999 result += "\n process context dump.";
1000 result += "\nshow-stats Dumps statistics of the process. This is also done at process";
1001 result += "\n context dump.";
1003 result += "\n<visibility action>[|<address>:<port>][|socket id]";
1005 result += "\n Actions: hide, show (update state) and hidden, shown (query state).";
1006 result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
1007 result += "\n If missing server (first parameter) all applications sockets will be affected.";
1008 result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected.";
1010 result += "\n All application client sessions are shown on startup, but standard delivery only use primary";
1011 result += "\n server ones except if fails. Balance configuration use all the allowed sockets. You could also";
1012 result += "\n use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
1013 result += "\n client sessions, but for this, hide/show feature seems easier.";
1015 result += "\n--------------------------------------------------------------------------------------- Flow operations";
1017 result += "\nsendxml2e|<source_file> Sends xml source file (pathfile) through configured entity.";
1018 result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to client.";
1019 result += "\nanswerxml2e[|source_file] Answer xml source file (pathfile) for incoming request with same code from entity.";
1020 result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
1021 result += "\n as many queues as different message codes have been programmed.";
1022 result += "\nanswerxml2c[|source_file] Answer xml source file (pathfile) for incoming request with same code from client.";
1023 result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
1024 result += "\n as many queues as different message codes have been programmed.";
1025 result += "\nanswerxml<2e/2c> List programmed answers (to entity/client) if no parameter provided.";
1026 result += "\nanswerxml<2e/2c>|dump Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
1027 result += "\n where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
1028 result += "\nanswerxml<2e/2c>|clear Clear programmed answers (to entity/client).";
1029 result += "\nanswerxml<2e/2c>|exhaust Disable the corresponding queue rotation, which is the default behaviour.";
1030 result += "\nanswerxml<2e/2c>|rotate Enable the corresponding queue rotation, useful in performance tests.";
1031 result += "\n Rotation consists in add again to the queue, each element retrieved for answering.";
1033 result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
1034 result += "\nspecial scenarios (protocol errors):";
1036 result += "\nsendhex2e|<source_file> Sends hex source file (pathfile) through configured entity.";
1037 result += "\nsendhex2c|<source_file> Sends hex source file (pathfile) to client.";
1039 result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
1040 result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
1041 result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
1043 result += "\nIf a request is received, answer map (built with 'answerxml<2e/2c>' operations) will be";
1044 result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
1045 result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
1046 result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
1047 result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
1049 result += "\nIn the most complete situation (process with both client and server side) there are internally";
1050 result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
1051 result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
1052 result += "\n each one we could program different answers corresponding to different request codes received.";
1054 result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
1055 result += "\n to the peer which sent the request. If user wants to test a specific answer without changing it,";
1056 result += "\n use sendxml<2e/2c>/sendhex<2e/2c> operations better than programming.";
1058 result += "\nBalance ('--balance' command line parameter) could be used to forward server socket receptions through";
1059 result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
1060 result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
1061 result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
1063 result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
1065 result += "\nUsed as log file extensions (when '--splitLog' is provided on command line) and context preffixes on log";
1066 result += "\n details when unique log file is dumped:";
1068 result += "\n [sent2e/send2eError] Send to entity (success/error)";
1069 result += "\n [sent2c/send2cError] Send to client (success/error)";
1070 result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)";
1071 result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)";
1072 result += "\n [recvfc] Reception from client";
1073 result += "\n [recvfe] Reception from entity";
1074 result += "\n [req2c-expired] A request sent to client has been expired";
1075 result += "\n [req2e-expired] A request sent to entity has been expired";
1076 result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired]";
1077 result += "\n has been logged)";
1078 result += "\n [recvfe-ans-unknown] Reception from entity of an unknown answer (probably former [req2e-expired]";
1079 result += "\n has been logged)";
1080 result += "\n [retry] Request retransmission";
1082 result += "\n------------------------------------------------------------------------------------------- Burst tests";
1084 result += "\nIn order to simplify user experience, burst category operations are only allowed in single realm node";
1085 result += "\n configuration. Indeed, you could send messages with incorrect Origin-Realm, and no warning is shown.";
1086 result += "\nAll the operations are performed through the unique realm: if you need to use more interfaces, you may";
1087 result += "\n launch different ADML instances. Is nonsense to allow burst in a multi-realm configured ADML, because";
1088 result += "\n this feature is not able to coordinate the messages.";
1090 result += "\nburst|<action>[|parameter] Used for performance testing, we first program diameter requests";
1091 result += "\n messages in order to launch them from client side to the configured";
1092 result += "\n diameter entity. We could start the burst with an initial load";
1093 result += "\n (non-asynchronous sending), after this, a new request will be sent";
1094 result += "\n per answer received or expired context. There are 10 actions: clear,";
1095 result += "\n load, start, push, pop, stop, repeat, send, goto and look.";
1097 result += "\n burst|clear Clears all loaded burst messages.";
1098 result += "\n burst|load|<source_file> Loads the next diameter message into launcher burst.";
1099 result += "\n burst|start|<initial load> Starts (or restarts if already in progress) the message sending with";
1100 result += "\n a certain initial load.";
1101 result += "\n burst|push|<load amount> Sends specific non-aynchronous load.";
1102 result += "\n burst|pop|<release amount> Skip send burst messages in order to reduce over-the-air requests.";
1103 result += "\n Popping all OTA requests implies burst stop because no more answer";
1104 result += "\n will arrive to the process. Burst output file (--burstLog command";
1105 result += "\n line parameter) shows popped messages with crosses (x). Each cross";
1106 result += "\n represents one received answer for which no new request is sent.";
1107 result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount.";
1108 result += "\n burst|repeat[|[yes]|no] Restarts the burst launch when finish. If initial load or push load";
1109 result += "\n amount is greater than burst list size, they will be limited when";
1110 result += "\n the list is processed except when repeat mode is enabled.";
1111 result += "\n burst|send|<amount> Sends messages from burst list. The main difference with start/push";
1112 result += "\n operations is that burst won't be awaken. Externally we could control";
1113 result += "\n sending time (no request will be sent for answers).";
1114 result += "\n burst|goto|<order> Updates current burst pointer position.";
1115 result += "\n burst|look[|order] Show programmed burst message for order provided, current when missing.";
1117 result += "\n-------------------------------------------------------------------------------------- Advanced testing";
1119 result += "\n Burst mode only allows single interface interaction. For multiple interface";
1120 result += "\n (realm) coordination, you could use the advanced test cases programming:";
1123 result += "\n test|<id>|<command>[|parameters]";
1125 result += "\n Adds a new step to the test case with provided identifier. If provided identifier";
1126 result += "\n is not registered yet, a new test case will be created with that value and the";
1127 result += "\n step will be added as the first. For a specific 'id', the steps are stored in";
1128 result += "\n order as they are programmed. Check possible runtime exceptions when adding a";
1129 result += "\n new step because those which fail, will be ignored/skipped during test case";
1130 result += "\n programming giving an incomplete sequence invalid for the testing purpose.";
1132 result += "\n <id>: integer number, normally monotonically increased for each test case. Some external";
1133 result += "\n script/procedure shall clone a test case template in order to build a collection";
1134 result += "\n of independent and coherent test cases (normally same type) with different context";
1135 result += "\n values (Session-Id, Subscriber-Id, etc.).";
1137 result += "\n <command>: commands to be executed for the test id provided. Each command programmed";
1138 result += "\n constitutes a test case 'step', numbered from 1 to N.";
1140 result += "\n timeout|<msecs> Sets an asynchronous timer to restrict the maximum timeout";
1141 result += "\n until last test step. Normally, this command is invoked";
1142 result += "\n in the first step, anyway it measures the time from the";
1143 result += "\n execution point whatever it is. The expiration will abort";
1144 result += "\n the test if still running. One or more timeouts could be";
1145 result += "\n programmed (not usual), but the more restrict will apply.";
1146 result += "\n It is highly recommended to program a initial timeout step,";
1147 result += "\n or the test case could be eternally in-progress.";
1149 result += "\n sendxml2e|<source_file>[|<step number>]";
1150 result += "\n Sends xml source file (pathfile) to entity (it would be a";
1151 result += "\n 'forward' event if it came through local server endpoint).";
1152 result += "\n The step number should be provided for answers to indicate";
1153 result += "\n the 'wait for request' corresponding step. If you miss this";
1154 result += "\n reference, the sequence information (hop-by-hop, end-to-end)";
1155 result += "\n will be sent as they are in the answer xml message (realize";
1156 result += "\n the difficulty of predicting these information). Be sure to";
1157 result += "\n refer to a 'wait for request' step. Conditions like 'regexp'";
1158 result += "\n (as we will see later) are not verified.";
1160 result += "\n sendxml2c|<source_file>[|<step number>]";
1161 result += "\n Sends xml source file (pathfile) to client (it would be a";
1162 result += "\n 'forward' event if it came through remote server endpoint).";
1163 result += "\n Same commented for 'sendxml2e' regarding the step number.";
1165 result += "\n delay|<msecs> Blocking step until the time lapse expires. Useful to give ";
1166 result += "\n some cadence control and time schedule for a specific case.";
1167 result += "\n A value of 0 could be used as a dummy step.";
1168 result += "\n wait<fe/fc>|<condition> Blocking step until condition is fulfilled. The message could";
1169 result += "\n received from entity (waitfe) or from client (waitfc).";
1171 result += "\n wait<fe/fc>-regexp|<regexp>";
1172 result += "\n Wait condition, from entity (waitfe-regexp) or client (waitfc-regexp)";
1173 result += "\n to match the serialized xml content for received messages. CPU cost";
1174 result += "\n is bigger than the former ones because the whole message must be";
1175 result += "\n decoded and converted to xml instead of doing a direct hexadecimal";
1176 result += "\n buffer search. The main advantage is the great flexibility to identify";
1177 result += "\n any content with a regular expression.";
1179 result += "\n sh-command|<script> External execution for script/executable via shell through a dedicated";
1180 result += "\n thread, providing the command and parameters. You could use dynamic";
1181 result += "\n variables ##<tag> to have more flexibility:";
1182 result += "\n Test pool cycle id: "; result += SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID;
1183 result += "\n Test case id: "; result += SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID;
1184 result += "\n Test step id: "; result += SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID;
1186 result += "\n For example, your command could be something like this:";
1187 result += "\n insert_sql_"; result += SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID; result += ".sh -db dbname --verbose";
1188 result += "\n > /tmp/cycle-"; result += SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID;
1189 result += ".testcase-"; result += SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID;
1190 result += ".teststep-"; result += SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID;
1192 result += "\n Try to redirect stdout and stderr to avoid ADML output contamination";
1193 result += "\n with the possible outputs from the scripts. You could also put your";
1194 result += "\n job in background although sh-command will return 0-value immediately.";
1196 result += "\n <condition>: Optional parameters which must be fulfilled to continue through the next step.";
1197 result += "\n Any received message over diameter interfaces will be evaluated against the";
1198 result += "\n corresponding test case starting from the current step until the first one";
1199 result += "\n whose condition is fulfilled. If no condition is fulfilled the event will be";
1200 result += "\n classified as 'uncovered' (normally a test case bad configuration, or perhaps";
1201 result += "\n a real unexpected message).";
1204 // result += "\n The way to identify the test case, is through registered Session-Id values for";
1205 // result += "\n programmed requests. But this depends on the type of node. Acting as clients,";
1206 // result += "\n requests received have Session-Id values which are already registered with";
1207 // result += "\n one test case, causing an error if not found. Acting as servers, requests are";
1208 // result += "\n received over a diameter local server from a client which are generating that";
1209 // result += "\n Session-Id values. Then we know nothing about such values. The procedure in";
1210 // result += "\n this case is find out a test case not-started containing a condition which";
1211 // result += "\n comply with the incoming message, and reactivates it.";
1212 // The other solution: register Session-Id values for answers send to client from a local diameter server.
1214 result += "\n How to answer: a wait condition for a request will store the incoming message";
1215 result += "\n which fulfills that condition. This message is useful together with the peer";
1216 result += "\n connection source in a further send step configured with the corresponding";
1217 result += "\n response. You could also insert a delay between wait and send steps to be";
1218 result += "\n more realistic (processing time simulation in a specific ADML realm node).";
1219 result += "\n Always, a response send step will get the needed information from the most";
1220 result += "\n recent wait step finding in reverse order (note that some race conditions";
1221 result += "\n could happen if your condition is not specific enough).";
1224 result += "\n Condition format:";
1226 result += "\n [code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId]";
1228 result += "\n code: integer number";
1229 result += "\n bitR: 1 (request), 0 (answer)";
1230 result += "\n hopByHop: integer number or request send step reference: #<step number>";
1232 result += "\n Using the hash reference, you would indicate a specific wait condition";
1233 result += "\n for answers. The step number provided must correspond to any of the";
1234 result += "\n previous send commands (sendxml2e/sendxml2c) configured for a request.";
1235 result += "\n This 'hop-by-hop' variant eases the wait condition for answers in the";
1236 result += "\n safest way.";
1238 result += "\n applicationId: integer number";
1239 result += "\n sessionId: string";
1240 result += "\n resultCode: integer number";
1241 result += "\n msisdn: string";
1242 result += "\n imsi: string";
1243 result += "\n serviceContextId: string";
1245 result += "\n Take into account these rules, useful in general:";
1247 result += "\n - Be as much specific as possible defining conditions to avoid ambiguity sending";
1248 result += "\n messages out of context due to race conditions. Although you could program several";
1249 result += "\n times similar conditions, some risky practices will throw a warning trace (if you";
1250 result += "\n repeat the same condition within the same test case).";
1251 result += "\n - Adding a ResultCode and/or HopByHop to the condition are only valid waiting answers.";
1252 result += "\n - Requests hop-by-hop values must be different for all the test case requests.";
1253 result += "\n RFC says that a hop by hop must be unique for a specific connection, something that";
1254 result += "\n could be difficult to manage if we have multiple available connections from client";
1255 result += "\n side endpoint (entity or local server), even if we would have only one connection but";
1256 result += "\n several realm interfaces. It is enough to configure different hop-by-hop values within";
1257 result += "\n each test case, because on reception, the Session-Id is used to identify that test case.";
1262 result += "\n Programming example:";
1264 result += "\n Basic Rx/Gx scenary: PCEF (Gx) - PCRF - AF (Rx)";
1266 result += "\n test|1|timeout|5000 (step 1: whole time requirement is 5 seconds)";
1267 result += "\n test|1|sendxml2e|CCR-I.xml (step 2: imagine this xml uses the Session-Id 'SGx')";
1268 result += "\n test|1|waitfe|272|0|||SGx|2001 (step 3: waits the CCA for the CCR-I with Result-Code = DIAMETER_SUCCESS)";
1269 result += "\n test|1|sendxml2e|AAR-flows.xml (step 4: imagine this xml uses the Session-Id 'SRx')";
1270 result += "\n test|1|waitfe|265|0|||SRx|2001 (step 5: waits the AAA for the AAR-flows with Result-Code = DIAMETER_SUCCESS)";
1271 result += "\n test|1|waitfe|258|1|||SGx (step 6: waits the RAR (install policies) from the PCRF server)";
1272 result += "\n test|1|sendxml2e|RAA-install.xml|6 (step 7: sends the response for the RAR)";
1273 result += "\n test|1|sendxml2e|CCR-T.xml (step 8: termination of the Gx session, imagine this xml puts hop-by-hop 'H1')";
1274 result += "\n test|1|waitfe|272|0|H1||SGx|2001 (step 9: waits the CCA for the CCR-T with Result-Code = DIAMETER_SUCCESS and hop-by-hop 'H1')";
1275 result += "\n test|1|waitfe|258|1|||SGx (step 10: waits the RAR (remove policies) from the PCRF server)";
1276 result += "\n test|1|sendxml2e|RAA-remove.xml|10 (step 11: sends the response for the RAR)";
1278 result += "\n Notes: We added an additional condition in step 9: the hop-by-hop. When we program the corresponding";
1279 result += "\n source request (CCR-T), we configured the value 'H1' for the hop-by-hop. This is an 'application";
1280 result += "\n value' because the real hop-by-hop transported through the client connection is managed by the";
1281 result += "\n diameter stack. But when returned, the transaction pool resolve the original value. This feature";
1282 result += "\n is necessary to ease the implementation of certain diameter agents (proxies for example). In our";
1283 result += "\n case, we could format the hop-by-hop values within the request templates with total freedom to";
1284 result += "\n improve the programmed conditions.";
1286 result += "\n In the case of 'waiting for requests' is not such easy. Indeed, steps 6 and 10 will write a warning";
1287 result += "\n because they are the same condition. We know that we are not going to have any problem because";
1288 result += "\n such events are blocking-protected regarding logic-dependent messages (CCR-T), and race condition";
1289 result += "\n is absolutely strange in this case.";
1291 result += "\n You could speed up the test case moving forward steps like 3 & 5, understood as non-strict requirements";
1292 result += "\n to continue testing. Anyway, remember that test cases should be as real as possible, and that there";
1293 result += "\n are many ways to increase the load rate as we will see in next section (test cases execution).";
1295 result += "\n Other simplifications: the steps 3, 5 and 9 can be replaced by";
1297 result += "\n test|1|waitfe||0|#2";
1298 result += "\n test|1|waitfe||0|#4";
1299 result += "\n test|1|waitfe||0|#8";
1301 result += "\n which means that hop-by-hop must be retrieved from steps 2, 4 and 8 respectively,";
1302 result += "\n and the expected message shall be an answer. Normally you will add other conditions,";
1303 result += "\n for example a DIAMETER_SUCCESS result (adding 2001 as Result-Code).";
1305 result += "\nTest cases execution:";
1308 result += "\n test|ttps|<amount> Starts/resume the provided number of test ticks per second (ttps). The ADML starts";
1309 result += "\n with the event trigger system suspended, and this operation is neccessary to begin";
1310 result += "\n those cases which need this time event (internal triggering). Some other test cases";
1311 result += "\n could be started through external events (first test case event could be programmed";
1312 result += "\n to wait specific message), but is not usual this external mode and neither usual to";
1313 result += "\n mix triggering types. Normally, you will pause/stop new test launchs providing 0 as";
1314 result += "\n ttps value, and also you could dynamically modify the load rate updating that value.";
1315 result += "\n If a test case has N messages then 'ttps * N' will be the virtual number of messages";
1316 result += "\n managed per second when no bottleneck exists.";
1318 result += "\n Provide 0 in order to stop the timer triggering.";
1320 result += "\n The timer manager resolution currently harcoded allows a maximum of ";
1321 result += anna::functions::asString(1000/a_admlMinResolution); result += " events";
1322 result += "\n per second. To reach greater rates ADML will join synchronously the needed number of";
1323 result += "\n new time-triggered test cases per a single event, writting a warning-level trace to";
1324 result += "\n advice about the risk of burst sendings and recommend launching multiple instances";
1325 result += "\n to achieve such load with a lower rate per instance.";
1327 result += "\n test|next[|<sync-amount>] Forces the execution of the next test case(s) without waiting for test manager tick.";
1328 result += "\n Provide an integer value for 'sync-amount' to send a burst synchronous amount of the";
1329 result += "\n next programmed test cases (1 by default). This event works regardless the timer tick";
1330 result += "\n function, but it is normally used with the test manager tick stopped.";
1332 result += "\n test|ip-limit[|amount] In-progress limit of test cases. No new test cases will be launched over this value";
1333 result += "\n (test Manager tick work will be ignored). Zero-value is equivalent to stop the clock.";
1334 result += "\n tick, -1 is used to specify 'no limit' which is the default. If missing amount, the";
1335 result += "\n limit and current amount of in-progress test cases will be shown.";
1337 result += "\n test|goto|<id> Updates current test pointer position.";
1339 result += "\n test|look[|id] Show programmed test case for id provided, current 'in-process' test case when missing.";
1340 result += "\n Test cases reports are not dumped on process context (too many information in general).";
1341 result += "\n The report contains context information in every moment: this operation acts as a snapshot.";
1343 result += "\n test|interact|amount|id Makes interactive a specific test case id. The amount is the margin of execution steps";
1344 result += "\n to be done. Normally, we will execute 'test|interact|0|<test case id>', which means that";
1345 result += "\n the test case is selected to be interactive, but no step is executed. Then you have to";
1346 result += "\n interact with positive amounts (usually 1), executing the provided number of steps if";
1347 result += "\n they are ready and fulfill the needed conditions. The value of 0, implies no execution";
1348 result += "\n steps margin, which could be useful to 'freeze' a test in the middle of its execution.";
1349 result += "\n You could also provide -1 to make it non-interactive resuming it from the current step.";
1351 result += "\n test|reset|<soft/hard>[|id] Reset the test case for id provided, all the tests when missing. It could be hard/soft:";
1352 result += "\n - hard: you probably may need to stop the load rate before. This operation initializes";
1353 result += "\n all test cases regardless their states.";
1354 result += "\n - soft: only for finished cases (those with 'Success' or 'Failed' states). It does not";
1355 result += "\n affect to test cases with 'InProgress' state.";
1357 result += "\n test|repeats|<amount> Restarts the whole programmed test list when finished the amount number of times (repeats";
1358 result += "\n forever if value -1 is provided). This is disabled by default (amount = 0): testing trigger";
1359 result += "\n system will enter suspended state until new ttps operation is received and a soft reset has";
1360 result += "\n been done before. Test cases state & data will be reset (when achieved again), but general";
1361 result += "\n statistics and counters will continue measuring until reset with 'collect' operation.";
1363 result += "\n test|clear Clears all the programmed test cases and stop testing (if in progress).";
1365 result += "\n test|summary Test manager general report (number of test cases, counts by state, global configuration,";
1366 result += "\n forced in-progress limitation, reports visibility, etc.). Be careful when you have reports";
1367 result += "\n enabled because the programmed test cases dumps could be heavy (anyway you could enable the";
1368 result += "\n dumps separately, for any of the possible states: Initialized, InProgress, Failed, Success).";
1370 result += "\n test|report|<initialized/in-progress/failed/success/all>[|[yes]|no]";
1372 result += "\n Enables/disables report generation for a certain test case state: initialized, in-progress,";
1373 result += "\n failed or success. This applies to report summary (former described operation) and automatic";
1374 result += "\n dumps during testing where only failed or success states will appear: every time a test case";
1375 result += "\n is finished its xml representation will be dump on a file under the execution directory (or";
1376 result += "\n the one configured in process command-line 'tmDir') with the name:";
1378 result += "\n 'cycle-<cycle id>.testcase-<test case id>.xml'.";
1380 result += "\n By default, all the states are disabled to avoid IO overload. In most of cases not all the";
1381 result += "\n tests are going to fail and you could enable only such failed dumps, but you can enable all";
1382 result += "\n the types if you want (use reserved word 'all' for this).";
1384 result += "\n test|report-hex[|[yes]|no] Reports could include the diameter messages in hexadecimal format. Disabled by default.";
1387 result += "\nUSING OPERATIONS INTERFACE";
1388 result += "\n--------------------------";
1390 result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
1392 result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
1393 result += "\n to define the http server at the command line with something like: '--httpServer localhost:9000'.";
1394 result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
1395 result += "\n using curl client could be:";
1397 result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
1398 result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000";
1399 result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
1400 result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
1401 result += "\n etc.";
1403 result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
1405 result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
1406 result += "\n signal event:";
1407 result += "\n echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
1408 result += "\n then";
1409 result += "\n kill -12 <pid>";
1411 result += "\n kill -s SIGUSR2 <pid>";
1412 result += "\n and then see the results:";
1413 result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
1415 result += "\n (this file is ended with EOF final line, useful managing huge batch files to ensure the job completion)";
1417 result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
1418 result += "\n case over the output file. Take into account that all the content of the task file will be executed";
1419 result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
1420 result += "\n interface.";
1427 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1428 LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1429 if (operation == "") return; // ignore
1430 LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1432 // Default response:
1433 response_content = "Operation processed with exception (see traces): ";
1434 response_content += operation;
1435 std::string opt_response_content = ""; // aditional response content
1436 anna::DataBlock db_aux(true);
1437 anna::diameter::codec::Message codecMsg; // auxiliary codec message
1440 CommandLine& cl(anna::CommandLine::instantiate());
1441 TestManager &testManager = TestManager::instantiate();
1444 ///////////////////////////////////////////////////////////////////
1445 // Simple operations without arguments:
1448 if(operation == "help") {
1449 response_content = help();
1453 // Reset performance data:
1454 if(operation == "collect") {
1457 response_content = "All process counters & statistic information have been reset";
1461 // Counters dump on demand:
1462 if(operation == "forceCountersRecord") {
1463 forceCountersRecord();
1464 response_content = "Current counters have been dump to disk";
1468 // OAM & statistics:
1469 if(operation == "show-oam") {
1470 anna::xml::Node root("root");
1471 response_content = anna::xml::Compiler().apply(oamAsXML(&root));
1474 if(operation == "show-stats") {
1475 anna::xml::Node root("root");
1476 response_content = anna::xml::Compiler().apply(statsAsXML(&root));
1480 ///////////////////////////////////////////////////////////////////
1481 // Tokenize operation
1483 params.apply(operation, "|", "<null>" /* allow contiguous separators */);
1484 int numParams = params.size() - 1;
1486 // Get the operation type and parameters:
1487 Tokenizer::const_iterator tok_iter = params.begin();
1488 std::string opType = Tokenizer::data(tok_iter);
1489 std::string param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11;
1490 if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1491 if(numParams >= 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1492 if(numParams >= 3) { tok_iter++; param3 = Tokenizer::data(tok_iter); }
1494 if(numParams >= 4) { tok_iter++; param4 = Tokenizer::data(tok_iter); }
1495 if(numParams >= 5) { tok_iter++; param5 = Tokenizer::data(tok_iter); }
1496 if(numParams >= 6) { tok_iter++; param6 = Tokenizer::data(tok_iter); }
1497 if(numParams >= 7) { tok_iter++; param7 = Tokenizer::data(tok_iter); }
1498 if(numParams >= 8) { tok_iter++; param8 = Tokenizer::data(tok_iter); }
1499 if(numParams >= 9) { tok_iter++; param9 = Tokenizer::data(tok_iter); }
1500 if(numParams >= 10) { tok_iter++; param10 = Tokenizer::data(tok_iter); }
1501 if(numParams >= 11) { tok_iter++; param11 = Tokenizer::data(tok_iter); }
1502 // Remove '<null>' artificial token to ease further checkings:
1503 if (param1 == "<null>") param1 = "";
1504 if (param2 == "<null>") param2 = "";
1505 if (param3 == "<null>") param3 = "";
1506 if (param4 == "<null>") param4 = "";
1507 if (param5 == "<null>") param5 = "";
1508 if (param6 == "<null>") param6 = "";
1509 if (param7 == "<null>") param7 = "";
1510 if (param8 == "<null>") param8 = "";
1511 if (param9 == "<null>") param9 = "";
1512 if (param10 == "<null>") param10 = "";
1513 if (param11 == "<null>") param11 = "";
1515 // No operation has more than 2 arguments except 'test' ...
1516 if(opType != "test" && numParams > 2)
1517 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1520 // Check the number of parameters:
1521 bool wrongBody = false;
1523 if((opType == "node") && (numParams > 1)) wrongBody = true;
1524 if((opType == "node_auto") && (numParams > 0)) wrongBody = true;
1526 if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1528 if(((opType == "sendxml2e") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1530 if((opType == "burst") && (numParams < 1)) wrongBody = true;
1532 if((opType == "test") && (numParams < 1)) wrongBody = true;
1534 if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1538 std::string msg = "Wrong body content format on HTTP Request for '";
1540 msg += "' operation (missing parameter/s). Use 'help' management command to see more information.";
1541 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1545 if(opType == "context") {
1546 std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
1547 writeContext(contextFile);
1548 response_content = anna::functions::asString("Context dumped on file '%s'", contextFile.c_str());
1552 if(opType == "services") {
1553 std::string servicesFile = ((numParams == 1) ? param1 : "services.xml");
1555 loadServices(servicesFile, true /* bind entities */);
1557 catch(anna::RuntimeException &ex) {
1559 response_content = anna::functions::asString("Loaded services from file '%s' with errors", servicesFile.c_str());
1562 response_content = anna::functions::asString("Loaded services from file '%s'", servicesFile.c_str());
1567 if(opType == "node") {
1569 if (setWorkingNode(param1)) response_content = anna::functions::asString("Forced node is now '%s'", param1.c_str());
1572 if (a_workingNode) {
1573 response_content = "Working node is forced to be: \n\n";
1574 response_content += a_workingNode->asXMLString();
1577 response_content = "Working node is automatic";
1582 if(opType == "node_auto") {
1583 a_workingNode = NULL;
1584 response_content = "Working node has been set to automatic";
1588 // Operated realm from possible forced-working node:
1589 a_operatedRealm = a_workingNode ? a_workingNode /* priority */: NULL /* auto */;
1591 // If any message is managed: updateOperatedRealmNodeWithMessage(codecMessage)
1592 // To operate, use the exception-protected methods which never will return NULL:
1593 // getOperatedRealm(), getOperatedEntity(), getOperatedServer(), getOperatedEngine()
1596 if(opType == "code") {
1597 codecMsg.loadXML(param1);
1598 std::string hexString = anna::functions::asHexString(codecMsg.code());
1600 std::ofstream outfile(param2.c_str(), std::ifstream::out);
1601 outfile.write(hexString.c_str(), hexString.size());
1603 } else if(opType == "decode") {
1604 // Get DataBlock from file with hex content:
1605 if(!getDataBlockFromHexFile(param1, db_aux))
1606 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1609 try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1611 std::string xmlString = codecMsg.asXMLString();
1613 std::ofstream outfile(param2.c_str(), std::ifstream::out);
1614 outfile.write(xmlString.c_str(), xmlString.size());
1616 } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1620 std::string key = param1;
1624 if(opType == "hide") getOperatedEngine()->findClientSession(key)->hide();
1626 if(opType == "show") getOperatedEngine()->findClientSession(key)->show();
1628 if(opType == "hidden") opt_response_content = getOperatedEngine()->findClientSession(key)->hidden() ? "true" : "false";
1630 if(opType == "shown") opt_response_content = getOperatedEngine()->findClientSession(key)->shown() ? "true" : "false";
1632 std::string address;
1634 anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1636 if(opType == "hide") getOperatedEngine()->findServer(address, port)->hide();
1638 if(opType == "show") getOperatedEngine()->findServer(address, port)->show();
1640 if(opType == "hidden") opt_response_content = getOperatedEngine()->findServer(address, port)->hidden() ? "true" : "false";
1642 if(opType == "shown") opt_response_content = getOperatedEngine()->findServer(address, port)->shown() ? "true" : "false";
1645 if(opType == "hide") getOperatedEntity()->hide();
1647 if(opType == "show") getOperatedEntity()->show();
1649 if(opType == "hidden") opt_response_content = getOperatedEntity()->hidden() ? "true" : "false";
1651 if(opType == "shown") opt_response_content = getOperatedEntity()->shown() ? "true" : "false";
1653 } else if((opType == "sendxml2e") || (opType == "sendhex2e")) {
1654 anna::diameter::comm::Message *msg;
1656 if(opType == "sendxml2e") {
1657 codecMsg.loadXML(param1);
1658 updateOperatedRealmNodeWithMessage(codecMsg);
1659 msg = getOperatedRealm()->createCommMessage();
1661 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)
1662 msg->setBody(codecMsg.code());
1664 // Get DataBlock from file with hex content:
1665 if(!getDataBlockFromHexFile(param1, db_aux))
1666 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1667 msg = getOperatedRealm()->createCommMessage();
1668 msg->setBody(db_aux);
1669 try { if(getOperatedRealm()->logEnabled()) codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1672 bool success = getOperatedEntity()->send(msg, cl.exists("balance"));
1673 getOperatedRealm()->releaseCommMessage(msg);
1676 if(getOperatedRealm()->logEnabled()) {
1677 anna::diameter::comm::Server *usedServer = getOperatedEntity()->getLastUsedResource();
1678 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1679 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
1680 getOperatedRealm()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
1682 } else if((opType == "burst")) {
1685 throw anna::RuntimeException("Burst category operations are only allowed in single realm node configuration. This is only to simplify user experience.", ANNA_FILE_LOCATION);
1687 // burst|clear clears all loaded burst messages.
1688 // burst|load|<source_file> loads the next diameter message into launcher burst.
1689 // burst|start|<initial load> starts the message sending with a certain initial load.
1690 // burst|push|<load amount> sends specific non-aynchronous load.
1691 // burst|stop stops the burst cycle.
1692 // burst|repeat|[[yes]|no] restarts the burst launch when finish.
1693 // burst|send|<amount> send messages from burst list. The main difference with
1694 // start/push operations is that burst won't be awaken.
1695 // Externally we could control sending time (no request
1696 // will be sent for answers).
1697 // burst|goto|<order> Updates current burst pointer position.
1698 // burst|look|<order> Show programmed burst message for order provided, current when missing.
1700 if(param1 == "clear") {
1701 opt_response_content = "removed ";
1702 opt_response_content += anna::functions::asString(getOperatedRealm()->clearBurst());
1703 opt_response_content += " elements";
1704 } else if(param1 == "load") {
1705 if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1707 codecMsg.loadXML(param2);
1708 if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1709 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)
1711 int position = getOperatedRealm()->loadBurstMessage(codecMsg.code());
1712 opt_response_content = "loaded '";
1713 opt_response_content += param2;
1714 opt_response_content += "' file into burst list position ";
1715 opt_response_content += anna::functions::asString(position);
1716 } else if(param1 == "start") {
1717 if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1719 int initialLoad = atoi(param2.c_str());
1720 int processed = getOperatedRealm()->startBurst(initialLoad);
1723 opt_response_content = "initial load completed for ";
1724 opt_response_content += anna::functions::entriesAsString(processed, "message");
1726 } else if(param1 == "push") {
1727 if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1729 int pushed = getOperatedRealm()->pushBurst(atoi(param2.c_str()));
1732 opt_response_content = "pushed ";
1733 opt_response_content += anna::functions::entriesAsString(pushed, "message");
1735 } else if(param1 == "pop") {
1736 if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1738 int releaseLoad = atoi(param2.c_str());
1739 int popped = getOperatedRealm()->popBurst(releaseLoad);
1742 opt_response_content = "burst popped for ";
1743 opt_response_content += anna::functions::entriesAsString(popped, "message");
1745 } else if(param1 == "stop") {
1746 int left = getOperatedRealm()->stopBurst();
1749 opt_response_content += anna::functions::entriesAsString(left, "message");
1750 opt_response_content += " left to the end of the cycle";
1752 } else if(param1 == "repeat") {
1753 if(param2 == "") param2 = "yes";
1755 bool repeat = (param2 == "yes");
1756 getOperatedRealm()->repeatBurst(repeat);
1757 opt_response_content += (repeat ? "repeat enabled" : "repeat disabled");
1758 } else if(param1 == "send") {
1759 if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1761 int sent = getOperatedRealm()->sendBurst(atoi(param2.c_str()));
1764 opt_response_content = "sent ";
1765 opt_response_content += anna::functions::entriesAsString(sent, "message");
1767 } else if(param1 == "goto") {
1768 if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1770 opt_response_content = getOperatedRealm()->gotoBurst(atoi(param2.c_str()));
1771 } else if(param1 == "look") {
1772 int order = ((param2 != "") ? atoi(param2.c_str()) : -1);
1773 opt_response_content = "\n\n";
1774 opt_response_content += getOperatedRealm()->lookBurst(order);
1776 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1779 } else if((opType == "test")) {
1780 // test|<id>|<command>[|parameters] Add a new step to the test case ...
1781 // test|ttps|<amount> Starts/resume the provided number of time ticks per second (ttps). The ADML starts ...
1782 // test|next[|<sync-amount>] Forces the execution of the next test case(s) without waiting for test manager tick ...
1783 // test|ip-limit[|amount] In-progress limit of test cases. No new test cases will be launched over this value ...
1784 // test|repeats|<amount> Restarts the whole programmed test list when finished the amount number of times ...
1785 // test|report|<initialized/in-progress/failed/success/all>[|[yes]|no]
1786 // Enables/disables report generation for a certain test case state: initialized, in-progress ...
1787 // test|report-hex[|[yes]|no] Reports could include the diameter messages in hexadecimal format. Disabled by default.
1788 // test|goto|<id> Updates current test pointer position.
1789 // test|look[|id] Show programmed test case for id provided, current when missing ...
1790 // test|interact|amount|id Makes interactive a specific test case id. The amount is the margin of execution steps ...
1791 // test|reset|<soft/hard>[|id] Reset the test case for id provided, all the tests when missing ...
1792 // test|clear Clears all the programmed test cases.
1793 // test|summary Test manager general report (number of test cases, counts by state ...
1796 if(param1 == "ttps") {
1798 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1800 bool success = ((param2 != "") ? testManager.configureTTPS(atoi(param2.c_str())) : false);
1802 opt_response_content = "assigned new test launch rate to ";
1803 opt_response_content += anna::functions::asString(atoi(param2.c_str()));
1804 opt_response_content += " events per second";
1807 opt_response_content += "unable to configure the test rate provided";
1810 else if (param1 == "next") {
1812 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1814 int sync_amount = ((param2 != "") ? atoi(param2.c_str()) : 1);
1816 if (sync_amount < 1)
1817 throw anna::RuntimeException("The parameter 'sync-amount' must be a positive integer value", ANNA_FILE_LOCATION);
1819 bool success = testManager.execTestCases(sync_amount);
1821 opt_response_content = (success ? "" : "not completely " /* completed cycle and no repeats, rare case */);
1822 opt_response_content += "processed ";
1823 opt_response_content += anna::functions::asString(sync_amount);
1824 opt_response_content += ((sync_amount > 1) ? " test cases synchronously" : " test case");
1826 else if(param1 == "ip-limit") {
1828 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1832 limit = atoi(param2.c_str());
1833 testManager.setInProgressLimit(limit);
1834 opt_response_content = "new in-progress limit: ";
1835 opt_response_content += (limit != UINT_MAX) ? anna::functions::asString(limit) : "<no limit>";
1838 opt_response_content = "in-progress limit amount: ";
1839 limit = testManager.getInProgressLimit();
1840 opt_response_content += (limit != UINT_MAX) ? anna::functions::asString(limit) : "<no limit>";
1841 opt_response_content += "; currently there are ";
1842 opt_response_content += anna::functions::asString(testManager.getInProgressCount());
1843 opt_response_content += " test cases running";
1846 else if(param1 == "repeats") {
1848 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1849 int repeats = atoi(param2.c_str());
1850 if (repeats < 0) repeats = -1;
1851 testManager.setPoolRepeats(repeats);
1852 std::string nolimit = (repeats != -1) ? "":" [no limit]";
1853 opt_response_content += anna::functions::asString("Pool repeats: %d%s (current cycle: %d)", repeats, nolimit.c_str(), testManager.getPoolCycle());
1855 else if(param1 == "report") {
1857 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1859 if(param2 != "initialized" && param2 != "in-progress" && param2 != "failed" && param2 != "success" && param2 != "all")
1860 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1862 if(param3 == "") param3 = "yes";
1863 bool enable = (param3 == "yes");
1865 if(param2 == "initialized")
1866 testManager.setDumpInitializedReports(enable);
1867 else if(param2 == "in-progress")
1868 testManager.setDumpInProgressReports(enable);
1869 else if(param2 == "failed")
1870 testManager.setDumpFailedReports(enable);
1871 else if(param2 == "success")
1872 testManager.setDumpSuccessReports(enable);
1874 testManager.setDumpAllReports(enable);
1876 opt_response_content += (enable ? "report enabled " : "report disabled ");
1877 opt_response_content += "for tests in '";
1878 opt_response_content += param2;
1879 opt_response_content += "' state";
1881 else if(param1 == "report-hex") {
1883 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1885 if(param2 == "") param2 = "yes";
1886 testManager.setDumpHex((param2 == "yes"));
1887 opt_response_content += (testManager.getDumpHex() ? "report includes hexadecimal messages" : "report excludes hexadecimal messages");
1889 else if(param1 == "goto") {
1891 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1893 if(param2 == "") throw anna::RuntimeException("Missing id for test goto operation", ANNA_FILE_LOCATION);
1894 int id = atoi(param2.c_str());
1895 if (testManager.gotoTestCase(id)) {
1896 opt_response_content = "position updated for id provided (";
1899 opt_response_content = "cannot found test id (";
1901 opt_response_content += anna::functions::asString(id);
1902 opt_response_content += ")";
1904 else if(param1 == "look") {
1906 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1908 int id = ((param2 != "") ? atoi(param2.c_str()) : -1);
1909 TestCase *testCase = testManager.findTestCase(id);
1912 response_content = testCase->asXMLString();
1917 opt_response_content = "no current test case detected (testing started ?)";
1920 opt_response_content = "cannot found test id (";
1921 opt_response_content += anna::functions::asString(id);
1922 opt_response_content += ")";
1926 else if (param1 == "interact") {
1928 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1930 int amount = atoi(param2.c_str());
1932 throw anna::RuntimeException("Interactive amount must be -1 (to disable interactive mode) or a positive number.", ANNA_FILE_LOCATION);
1934 int id = atoi(param3.c_str());
1935 TestCase *testCase = testManager.findTestCase(id);
1938 testCase->makeInteractive(false);
1939 opt_response_content = "interactive mode disabled";
1942 testCase->addInteractiveAmount(amount);
1943 opt_response_content = "added interactive amount of ";
1944 opt_response_content += anna::functions::asString(amount);
1945 opt_response_content += " units";
1946 if (amount == 0) opt_response_content += " (0: freezing a non-interactive testcase, no effect on already interactive)";
1948 opt_response_content += " for test case id ";
1949 opt_response_content += anna::functions::asString(id);
1952 opt_response_content = "cannot found test id (";
1953 opt_response_content += anna::functions::asString(id);
1954 opt_response_content += ")";
1957 else if(param1 == "reset") {
1959 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1961 if (param2 != "soft" && param2 != "hard")
1962 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1964 int id = ((param3 != "") ? atoi(param3.c_str()) : -1);
1965 TestCase *testCase = ((id != -1) ? testManager.findTestCase(id) : NULL);
1968 bool done = testCase->reset((param2 == "hard") ? true:false);
1969 opt_response_content = "test ";
1970 opt_response_content += param2;
1971 opt_response_content += " reset for id ";
1972 opt_response_content += anna::functions::asString(id);
1973 opt_response_content += done ? ": done": ": not done";
1977 bool anyReset = testManager.resetPool((param2 == "hard") ? true:false);
1978 opt_response_content = "reset have been sent to all programmed tests: "; opt_response_content += anyReset ? "some/all have been reset" : "nothing was reset";
1981 opt_response_content = "cannot found test id (";
1982 opt_response_content += anna::functions::asString(id);
1983 opt_response_content += ")";
1987 else if(param1 == "clear") {
1989 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1991 if (testManager.clearPool()) {
1992 opt_response_content = "all the programmed test cases have been dropped";
1995 opt_response_content = "there are not programmed test cases to be removed";
1998 else if(param1 == "summary") {
1999 response_content = testManager.asXMLString();
2003 int id = atoi(param1.c_str());
2005 throw anna::RuntimeException("Invalid test case identifier: must be a non-negative number", ANNA_FILE_LOCATION);
2007 // PARAM: 1 2 3 4 5 6 7 8 9 10 11
2008 // test|<id>|<command>
2010 // sendxml2e| <file>[|<step number>]
2011 // sendxml2c| <file>[|<step number>]
2013 // wait<fe/fc>|[code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId]
2014 // wait<fe/fc>-answer|<step number>
2015 // wait<fe/fc>-regexp|<regexp>
2016 if(param2 == "") throw anna::RuntimeException("Missing command for test id operation", ANNA_FILE_LOCATION);
2019 if (param2 == "timeout") {
2021 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2022 if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'timeout' command in test id operation", ANNA_FILE_LOCATION);
2023 anna::Millisecond timeout = checkTimeMeasure("Test case timeout", param3);
2024 testManager.getTestCase(id)->addTimeout(timeout); // creates / reuses
2026 else if ((param2 == "sendxml2e")||(param2 == "sendxml2c")) {
2028 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2029 if(param3 == "") throw anna::RuntimeException(anna::functions::asString("Missing xml file for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
2030 codecMsg.loadXML(param3);
2031 if (codecMsg.isRequest()) {
2033 throw anna::RuntimeException("Step number is provided with answers (to resolve the corresponding 'wait for request' step), but NOT with requests", ANNA_FILE_LOCATION);
2036 if (param4 == "") LOGWARNING(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));
2038 updateOperatedRealmNodeWithMessage(codecMsg);
2039 int stepNumber = ((param4 != "") ? atoi(param4.c_str()):-1);
2041 if (param2 == "sendxml2e")
2042 testManager.getTestCase(id)->addSendxml2e(codecMsg.code(), getOperatedRealm(), stepNumber); // creates / reuses
2044 testManager.getTestCase(id)->addSendxml2c(codecMsg.code(), getOperatedRealm(), stepNumber); // creates / reuses
2046 else if (param2 == "delay") {
2048 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2049 if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'delay' command in test id operation", ANNA_FILE_LOCATION);
2050 anna::Millisecond delay = ((param3 == "0" /* special case */) ? (anna::Millisecond)0 : checkTimeMeasure("Test case delay step", param3));
2051 testManager.getTestCase(id)->addDelay(delay); // creates / reuses
2053 else if ((param2 == "waitfe")||(param2 == "waitfc")) {
2055 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2056 if (param3 != "" || param4 != "" || param5 != "" || param6 != "" || param7 != "" || param8 != "" || param9 != "" || param10 != "" || param11 != "") {
2057 bool fromEntity = (param2.substr(4,2) == "fe");
2058 testManager.getTestCase(id)->addWait(fromEntity, param3, param4, param5, param6, param7, param8, param9, param10, param11);
2061 throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
2064 else if ((param2 == "waitfe-regexp")||(param2 == "waitfc-regexp")) {
2066 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2068 bool fromEntity = (param2.substr(4,2) == "fe");
2069 testManager.getTestCase(id)->addWaitRegexp(fromEntity, param3);
2072 throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
2075 else if (param2 == "sh-command") {
2077 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2078 if(param3 == "") throw anna::RuntimeException("Missing script/executable command-line for 'sh-command' in test id operation", ANNA_FILE_LOCATION);
2079 testManager.getTestCase(id)->addCommand(param3); // creates / reuses
2082 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2086 } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2087 anna::diameter::comm::Message *msg;
2089 if(opType == "sendxml2c") {
2090 codecMsg.loadXML(param1);
2091 updateOperatedRealmNodeWithMessage(codecMsg);
2092 msg = getOperatedRealm()->createCommMessage();
2094 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)
2096 msg->setBody(codecMsg.code());
2098 // Get DataBlock from file with hex content:
2099 if(!getDataBlockFromHexFile(param1, db_aux))
2100 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
2101 msg = getOperatedRealm()->createCommMessage();
2102 msg->setBody(db_aux);
2105 bool success = getOperatedServer()->send(msg);
2106 getOperatedRealm()->releaseCommMessage(msg);
2109 if(getOperatedRealm()->logEnabled()) {
2110 anna::diameter::comm::ServerSession *usedServerSession = getOperatedServer()->getLastUsedResource();
2111 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
2112 getOperatedRealm()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
2114 } else if(opType == "loadxml") {
2115 codecMsg.loadXML(param1);
2116 response_content = codecMsg.asXMLString();
2118 } else if(opType == "diameterServerSessions") {
2119 int diameterServerSessions = atoi(param1.c_str());
2120 getOperatedServer()->setMaxConnections(diameterServerSessions);
2122 } else if(opType == "answerxml2c") {
2123 if(param1 == "") { // programmed answers FIFO's to stdout
2124 response_content = getOperatedServer()->getReactingAnswers()->asString("ANSWERS TO CLIENT");
2126 } else if (param1 == "rotate") {
2127 getOperatedServer()->getReactingAnswers()->rotate(true);
2128 } else if (param1 == "exhaust") {
2129 getOperatedServer()->getReactingAnswers()->rotate(false);
2130 } else if (param1 == "clear") {
2131 getOperatedServer()->getReactingAnswers()->clear();
2132 } else if (param1 == "dump") {
2133 getOperatedServer()->getReactingAnswers()->dump();
2135 codecMsg.loadXML(param1);
2136 updateOperatedRealmNodeWithMessage(codecMsg);
2137 anna::diameter::codec::Message *message = getOperatedRealm()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
2138 LOGDEBUG(anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION));
2140 if(message->isRequest())
2141 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2143 int code = message->getId().first;
2144 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2145 getOperatedServer()->getReactingAnswers()->addMessage(code, message);
2147 } else if(opType == "answerxml2e") {
2149 if(param1 == "") { // programmed answers FIFO's to stdout
2150 response_content = getOperatedEntity()->getReactingAnswers()->asString("ANSWERS TO ENTITY");
2152 } else if (param1 == "rotate") {
2153 getOperatedEntity()->getReactingAnswers()->rotate(true);
2154 } else if (param1 == "exhaust") {
2155 getOperatedEntity()->getReactingAnswers()->rotate(false);
2156 } else if (param1 == "clear") {
2157 getOperatedEntity()->getReactingAnswers()->clear();
2158 } else if (param1 == "dump") {
2159 getOperatedEntity()->getReactingAnswers()->dump();
2161 codecMsg.loadXML(param1);
2162 updateOperatedRealmNodeWithMessage(codecMsg);
2163 anna::diameter::codec::Message *message = getOperatedRealm()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
2164 LOGDEBUG(anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION));
2166 if(message->isRequest())
2167 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2169 int code = message->getId().first;
2170 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2171 getOperatedEntity()->getReactingAnswers()->addMessage(code, message);
2174 throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
2178 response_content = "Operation correctly processed: "; response_content += operation;
2179 if (opt_response_content != "") {
2180 response_content += " => ";
2181 response_content += opt_response_content;
2185 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2187 anna::xml::Node* result = parent->createChild("launcher");
2188 anna::comm::Application::asXML(result);
2190 result->createAttribute("StartTime", a_start_time.asString());
2191 result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2193 for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
2194 it->second->asXML(result);
2197 // OAM & statistics:
2201 // Testing: could be heavy if test case reports are enabled
2202 TestManager::instantiate().asXML(result);
2207 anna::xml::Node* Launcher::oamAsXML(anna::xml::Node* parent) const
2209 anna::xml::Node* result = parent->createChild("Oam");
2212 anna::diameter::comm::OamModule::instantiate().asXML(result);
2213 anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
2214 anna::diameter::codec::OamModule::instantiate().asXML(result);
2219 anna::xml::Node* Launcher::statsAsXML(anna::xml::Node* parent) const
2221 anna::xml::Node* result = parent->createChild("Statistics");
2224 anna::statistics::Engine::instantiate().asXML(result);