System test feature
[anna.git] / example / diameter / launcher / Launcher.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
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 //
7
8
9 // Standard
10 #include <sstream>      // std::istringstream
11 #include <iostream>     // std::cout
12 #include <math.h> // ceil
13 #include <climits>
14
15 // Project
16 #include <anna/timex/Engine.hpp>
17 #include <anna/statistics/Engine.hpp>
18 #include <anna/diameter/codec/Engine.hpp>
19 #include <anna/http/Transport.hpp>
20 #include <anna/diameter/stack/Engine.hpp>
21 #include <anna/diameter/helpers/base/functions.hpp>
22 #include <anna/time/functions.hpp>
23 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
24 #include <anna/xml/xml.hpp>
25
26 // Process
27 #include <Launcher.hpp>
28 #include <RealmNode.hpp>
29 #include <MyDiameterEngine.hpp>
30 #include <TestManager.hpp>
31 #include <TestCase.hpp>
32
33
34 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
35 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
36
37
38
39 const char *ServicesDTD = "\
40 <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
41 <!-- Diameter services DTD -->\n\
42 \n\
43 <!ELEMENT services (stack*, node*)>\n\
44 \n\
45 <!ELEMENT stack EMPTY>\n\
46 <!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>\n\
47 <!--\n\
48    Stack record\n\
49 \n\
50    id:         Normally the id corresponds to the Application-Id for which the dictionary provided is designed.\n\
51                (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
52                for processed messages).\n\
53    dictionary: Path to the dictionary file\n\
54 -->\n\
55 \n\
56 <!ELEMENT node EMPTY>\n\
57 <!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\
58 <!--\n\
59    Node record\n\
60 \n\
61    originRealm:                             Node identifier (Origin-Realm name).\n\
62    applicationId:                           The Application-Id provided must exists as a registered 'stack id'.\n\
63    originHost:                              Diameter application host name (system name). If missing, process sets o.s. hostname\n\
64                                             Note that if you have two or more realms, the names must be different.\n\
65    cer:                                     User defined CER path file to be encoded to establish diameter connections.\n\
66                                             If missing, will be harcoded\n\
67    dwr:                                     User defined DWR path file to be encoded for diameter protocol keep alive.\n\
68                                             If missing, will be harcoded\n\
69    allowedInactivityTime:                   Milliseconds for the maximum allowed inactivity time on server sessions born over the\n\
70                                             local server before being reset. If missing, default value of 90000 will be assigned\n\
71    tcpConnectDelay:                         Milliseconds to wait TCP connect to any server. If missing, default value of 200 will\n\
72                                             be assigned\n\
73    answersTimeout:                          Milliseconds to wait pending application answers from diameter peers. If missing,\n\
74                                             default value of 10000 will be assigned\n\
75    ceaTimeout:                              Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'\n\
76                                             will be assigned\n\
77    watchdogPeriod:                          Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default\n\
78                                             value of 30000 will be assigned\n\
79    entity:                                  Target diameter entity (comma-separated '<address>:<port>' format).\n\
80                                             For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled\n\
81    entityServerSessions:                    Diameter entity server sessions (0: diameter entity disabled). Default value of 1\n\
82    diameterServer:                          Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.\n\
83                                             If missing, no local server will be enabled\n\
84    diameterServerSessions:                  Diameter own server available connections (0: diameter server disabled). Default value of 1\n\
85    balance:                                 Balance over entity servers instead of doing standard behaviour (first primary, secondary\n\
86                                             if fails, etc.). Default value 'no'\n\
87    sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part\n\
88                                             will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR\n\
89                                             analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;\n\
90                                             usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart')\n\
91    retries:                                 Expired responses will cause a number of request retransmissions. Disabled by default (0 retries)\n\
92    log:                                     Process log file (operations result, traffic log, etc.). By default '<originRealm>.launcher.log'.\n\
93                                             Empty string or \"null\" name, to disable. Warning: there is no rotation for log files\n\
94                                             (use logrotate or whatever you consider)\n\
95    splitLog:                                Splits log file (appends to log filename, extensions with the type of event: see help on\n\
96                                             startup information-level traces). No log files for code/decode and load operations are created.\n\
97                                             Default value 'no'\n\
98    detailedLog:                             Insert detailed information at log files. Should be disabled on automatic tests. Useful on\n\
99                                             'balance' mode to know messages flow along the sockets. Default value 'no'\n\
100    dumpLog:                                 Write to disk every incoming/outcoming message named as:\n\
101                                                '<originRealm>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'\n\
102                                             Default value 'no'\n\
103    burstLog:                                Burst operations log file. By default '<originRealm>.launcher.burst'. Empty string or \"null\" name, to disable.\n\
104                                             Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each\n\
105                                             burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst\n\
106                                             list size, plus OTA requests when changed\n\
107 \n\
108 -->\n\
109 \n\
110 ";
111
112
113 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
114   a_codecEngine = new anna::diameter::codec::Engine("MyCodecEngine");
115   a_timeEngine = NULL;
116   a_counterRecorder = NULL;
117   a_admlMinResolution = 2 * anna::timex::Engine::minResolution; // 2*10 = 20 ms; 1000/20 = 50 ticks per second;
118   //a_admlMinResolution = (anna::Millisecond)100;
119   a_counterRecorderClock = NULL;
120
121   // a_nodes.clear();
122   a_workingNode = NULL;
123
124   a_httpServerSocket = NULL;
125 }
126
127
128
129
130 void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) {
131   //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
132   const anna::xml::Attribute  *id, *dictionary;
133
134   // <!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>
135   const anna::xml::Attribute  *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
136                               *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
137                               *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
138                               *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
139
140   // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
141
142   // Stacks
143   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
144   anna::diameter::stack::Dictionary *d;
145   ///////////////////////////////////////////
146   // APPLICATION MESSAGE OAM MODULE SCOPES //
147   ///////////////////////////////////////////
148   // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
149   anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
150   appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
151   static int scope_id = 3;
152
153   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
154     std::string nodeName = (*it)->getName();
155
156     if(nodeName == "stack") {
157       // Input data:
158       id = (*it)->getAttribute("id");
159       dictionary = (*it)->getAttribute("dictionary");
160
161       try {
162         d = stackEngine.createDictionary(id->getIntegerValue(), dictionary->getValue());
163         getCodecEngine()->setDictionary(d);
164
165         // OAM module for counters:
166         appMsgOamModule.createStackCounterScope(scope_id, id->getIntegerValue() /* application-id */);
167         scope_id++;
168
169       } catch(anna::RuntimeException &ex) {
170         //_exit(ex.asString());
171         throw ex;
172       }
173     }
174   }
175
176   // Show loaded stacks:
177   std::cout << "Stacks currently loaded:" << std::endl;
178   std::cout << anna::functions::tab(stackEngine.asString(false /* light */));
179   std::cout << std::endl;
180
181
182   // Codec engine adjustments:
183   // Auto stack selection based on Application-ID:
184   bool multistack = (stackEngine.stack_size() > 1);
185   if (multistack) getCodecEngine()->selectStackWithApplicationId(true);
186
187   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
188     std::string nodeName = (*it)->getName();
189
190     if(nodeName == "node") {
191       // Input data:
192       originRealm = (*it)->getAttribute("originRealm");
193       appId = (*it)->getAttribute("applicationId");
194       originHost = (*it)->getAttribute("originHost", false /* no exception */);
195       cer = (*it)->getAttribute("cer", false /* no exception */);
196       dwr = (*it)->getAttribute("dwr", false /* no exception */);
197       allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */);
198       tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */);
199       answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */);
200       ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */);
201       watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */);
202       entity = (*it)->getAttribute("entity", false /* no exception */);
203       entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */);
204       diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */);
205       diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */);
206       balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no)
207       sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin)
208       retries = (*it)->getAttribute("retries", false /* no exception */);
209       log = (*it)->getAttribute("log", false /* no exception */);
210       splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no)
211       detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no)
212       dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no)
213       burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no)
214
215       // Basic checkings:
216       if (stackEngine.getDictionary(appId->getIntegerValue()) == NULL) {
217         std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
218         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
219       }
220       realm_nodes_it nodeIt = a_nodes.find(originRealm->getValue());
221       if (nodeIt != a_nodes.end()) {
222         std::string msg = "Already registered node name (Origin-Realm): "; msg += originRealm->getValue();
223         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
224       }
225
226       // Engine time measures checking & assignment:
227       anna::Millisecond allowedInactivityTimeMs(90000);
228       anna::Millisecond tcpConnectDelayMs(200);
229       anna::Millisecond answersTimeoutMs(10000);
230       anna::Millisecond ceaTimeoutMs(10000);
231       anna::Millisecond watchdogPeriodMs(30000);
232
233       if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue());
234       if (tcpConnectDelay)       tcpConnectDelayMs =       checkTimeMeasure("tcpConnectDelay",       tcpConnectDelay->getValue());
235       if (answersTimeout)        answersTimeoutMs =        checkTimeMeasure("answersTimeout",        answersTimeout->getValue());
236       if (ceaTimeout)            ceaTimeoutMs =            checkTimeMeasure("ceaTimeout",            ceaTimeout->getValue());
237       if (watchdogPeriod)        watchdogPeriodMs =        checkTimeMeasure("watchdogPeriod",        watchdogPeriod->getValue());
238
239       // Checking command line parameters
240       std::string sessionBasedModelsType;
241       if(sessionBasedModelsClientSocketSelection) {
242         sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue();
243         if((sessionBasedModelsType != "SessionIdHighPart") && (sessionBasedModelsType != "SessionIdOptionalPart") && (sessionBasedModelsType != "RoundRobin")) {
244           throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
245         }
246       }
247
248       int retransmissions = retries ? retries->getIntegerValue() : 0;
249       if(retransmissions < 0) {
250         throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION);
251       }
252
253       // Create new Node instance /////////////////////////////////////////////////////////////////
254       a_workingNode = new RealmNode(originRealm->getValue(), appId->getIntegerValue(), a_codecEngine);
255       MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine();
256       /////////////////////////////////////////////////////////////////////////////////////////////
257
258       // Assignments:
259       commEngine->setMaxConnectionDelay(tcpConnectDelayMs);
260       commEngine->setWatchdogPeriod(watchdogPeriodMs);
261
262       // Realm information:
263       if (originHost) commEngine->setHost(originHost->getValue());
264       commEngine->setRealm(originRealm->getValue());
265
266       // Diameter entity:
267       if(entity) {
268         int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1;
269
270         if(sessions > 0) {
271           // Number of sessions:
272           commEngine->setNumberOfClientSessionsPerServer(sessions);
273
274           // Client CER and DWR
275           std::string cerPathfile = cer ? cer->getValue() : "";
276           std::string dwrPathfile = dwr ? dwr->getValue() : "";
277           commEngine->setClientCERandDWR(cerPathfile, dwrPathfile);
278
279           // Register one entity for this engine:
280           a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs);
281           a_workingNode->setRequestRetransmissions(retransmissions);
282           a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsType);
283           a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings
284           if (eventOperation) a_workingNode->getEntity()->bind();
285         }
286       }
287
288       // Diameter Server:
289       if(diameterServer) {
290         int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1;
291         a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs);
292       }
293
294       // Logs:
295       std::string realm = commEngine->getRealm();
296       std::string s_log = realm + ".launcher.log"; if (log) s_log = log->getValue();
297       bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false);
298       bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false);
299       bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false);
300       std::string s_burstLog = realm + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue();
301       a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog);
302
303
304       // Lazy initialization for comm engine:
305       if (eventOperation) commEngine->lazyInitialize();
306
307       // New Node assignment //////////////////////////////////////////////////////////////////////
308       a_nodes[originRealm->getValue()] = a_workingNode;
309       /////////////////////////////////////////////////////////////////////////////////////////////
310     }
311   }
312
313   // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started,
314   //  but this don't care because application startComponents() -> initialize() -> do_initialize() -> do nothing.
315   // And when stopped, running state is not checked and it will be stopped anyway.
316 }
317
318
319 void Launcher::loadServices(const std::string & xmlPathFile, bool eventOperation) throw(anna::RuntimeException) {
320
321   if (xmlPathFile == "null" || xmlPathFile == "") {
322     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));
323     return;
324   }
325
326   LOGDEBUG(
327     std::string trace = "Loading ADML services file '";
328     trace += xmlPathFile;
329     trace += "'";
330     anna::Logger::debug(trace, ANNA_FILE_LOCATION);
331   );
332   anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
333   anna::xml::DTDMemory xmlDTD;
334   const anna::xml::Node *rootNode;
335   xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
336   xmlDTD.initialize(ServicesDTD);
337   try {
338     rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
339   }
340   catch (anna::RuntimeException &ex) {
341     LOGWARNING(
342       std::string msg = "Services DTD schema:\n\n";
343       msg += ServicesDTD;
344       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
345     );
346     throw ex;
347   }
348
349   LOGDEBUG(
350     std::string trace = "Loaded XML file (";
351     trace += xmlPathFile;
352     trace += "):\n";
353     trace += anna::xml::Compiler().apply(rootNode);
354     anna::Logger::debug(trace, ANNA_FILE_LOCATION);
355   );
356   servicesFromXML(rootNode, eventOperation);
357 }
358
359
360 anna::Millisecond Launcher::checkTimeMeasure(const std::string &parameter, const std::string &value) throw(anna::RuntimeException) {
361
362   if(anna::functions::isLike("^[0-9]+$", value)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
363     int msecs;
364     std::istringstream ( value ) >> msecs;
365
366     if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
367       std::string msg = "Configuration value for '";
368       msg += parameter;
369       msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: ";
370       msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
371       throw RuntimeException(msg, ANNA_FILE_LOCATION);
372     }
373
374     if(msecs > 300000) {
375       std::string msg = "Configuration value for '";
376       msg += parameter;
377       msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes).";
378       LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
379     }
380
381     if(msecs <= a_timeEngine->getResolution()) {
382       std::string msg = "Configuration value for '";
383       msg += parameter;
384       msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: ";
385       msg += anna::functions::asString(a_timeEngine->getResolution());
386       throw RuntimeException(msg, ANNA_FILE_LOCATION);
387     }
388
389     return (anna::Millisecond)msecs; // ok
390   }
391
392   // Non-integer exception:
393   std::string msg = "Configuration error for '";
394   msg += parameter;
395   msg += "' = '";
396   msg += value;
397   msg += "': must be a non-negative integer number";
398   throw RuntimeException(msg, ANNA_FILE_LOCATION);
399 }
400
401 RealmNode *Launcher::getWorkingNode() const throw(anna::RuntimeException) {
402
403   if (!a_workingNode)
404     throw RuntimeException("No services yet loaded. Try 'services' operation (via management interface), or restart process using command-line 'services' parameter", ANNA_FILE_LOCATION);
405
406   return a_workingNode;
407 }
408
409 bool Launcher::setWorkingNode(const std::string &name) throw() {
410   bool result = false;
411
412   realm_nodes_nc_it nodeIt = a_nodes.find(name);
413   if (nodeIt == a_nodes.end()) {
414     LOGWARNING(
415       std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
416       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
417     );
418   }
419   else {
420     a_workingNode = nodeIt->second;
421     result = true;
422   }
423
424   return result;
425 }
426
427 RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw() {
428   realm_nodes_it it = a_nodes.find(realmName);
429   if (it != a_nodes.end()) return it->second;
430
431   return NULL; // this never happens
432 }
433
434 void Launcher::initialize()
435 throw(anna::RuntimeException) {
436   anna::comm::Application::initialize();
437   CommandLine& cl(anna::CommandLine::instantiate());
438   anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
439   a_communicator = new MyCommunicator(workMode);
440   a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, a_admlMinResolution);
441   TestManager::instantiate().setTimerController(a_timeEngine);
442
443   // Counters record procedure:
444   const char *varname = "cntRecordPeriod";
445   anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000;
446   if(cntRecordPeriod != 0) {
447     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
448     std::string cntDir = ".";
449     if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
450     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
451   }
452
453   // Testing framework:
454   std::string tmDir = ".";
455   if(cl.exists("tmDir")) tmDir = cl.getValue("tmDir");
456   TestManager::instantiate().setReportsDirectory(tmDir);
457
458   // Tracing:
459   if(cl.exists("trace"))
460     anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
461
462   // Load launcher services:
463   loadServices(cl.getValue("services")); // before run (have components to be created)
464 }
465
466 void Launcher::run()
467 throw(anna::RuntimeException) {
468   LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
469   CommandLine& cl(anna::CommandLine::instantiate());
470   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
471
472   // Start time:
473   a_start_time.setNow();
474   // Statistics:
475   anna::statistics::Engine::instantiate().enable();
476
477   LOGINFORMATION(
478     // Help on startup traces:
479     anna::Logger::information(help(), ANNA_FILE_LOCATION);
480     // Test messages dtd:
481     std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
482     msg += anna::diameter::codec::MessageDTD;
483     anna::Logger::information(msg, ANNA_FILE_LOCATION);
484   );
485
486   // HTTP Server:
487   if(cl.exists("httpServer")) {
488     anna::comm::Network& network = anna::comm::Network::instantiate();
489     std::string address;
490     int port;
491     anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
492     //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
493     const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
494     a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
495   }
496
497   ///////////////////////////////
498   // Diameter library COUNTERS //
499   ///////////////////////////////
500   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
501   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
502   oamDiameterComm.enableCounters();
503   oamDiameterComm.enableAlarms();
504   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
505   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
506   oamDiameterCodec.enableCounters();
507   oamDiameterCodec.enableAlarms();
508   /////////////////
509   // COMM MODULE //
510   /////////////////
511   /* Main events */
512   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
513   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
514   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
515   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
516   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
517   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
518   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
519   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
520   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
521   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
522   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
523   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
524   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
525   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
526   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
527   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
528   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
529   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
530   /* Diameter Base (capabilities exchange & keep alive) */
531   // as client
532   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
533   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
534   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
535   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
536   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
537   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
538   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
539   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
540   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
541   // as server
542   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
543   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
544   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
545   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
546   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
547   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
548   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
549   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
550   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
551   /* server socket operations (enable/disable listening port for any local server) */
552   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
553   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
554   /* Connectivity */
555   // clients
556   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
557   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
558   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
559   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
560   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
561   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
562   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
563   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
564   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
565   // servers
566   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
567   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
568   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
569   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
570   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
571   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
572   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
573   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
574   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
575   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
576   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
577   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmitted,  "", 58);
578   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnClientSession,  "", 59);
579   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestRetransmittedOnServerSession,  "", 60);
580   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 61);
581   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 62);
582   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 63);
583   //////////////////
584   // CODEC MODULE //
585   //////////////////
586   /* Avp decoding */
587   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
588   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
589   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
590   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
591   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
592   /* Message decoding */
593   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
594   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
595   /* Avp validation */
596   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
597   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
598   /* Message validation */
599   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
600   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
601   /* Level validation */
602   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
603   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
604   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
605   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
606   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
607   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
608
609
610   /////////////////////////////////
611   // Counter recorder associated //
612   /////////////////////////////////
613   if(a_counterRecorderClock) {
614     oamDiameterComm.setCounterRecorder(a_counterRecorder);
615     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
616     anna::diameter::comm::ApplicationMessageOamModule::instantiate().setCounterRecorder(a_counterRecorder);
617     a_timeEngine->activate(a_counterRecorderClock); // start clock
618   }
619
620
621   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
622   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
623   if(cl.exists("integrationAndDebugging")) {
624     getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
625     getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
626   }
627
628   // Fix mode
629   if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
630     std::string fixMode = cl.getValue("fixMode");
631     anna::diameter::codec::Engine::FixMode::_v fm;
632     if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
633     else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
634     else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
635     else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
636     else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
637     getCodecEngine()->setFixMode(fm);
638   }
639
640   getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
641
642
643   // Log statistics concepts
644   if(cl.exists("logStatisticSamples")) {
645     std::string list = cl.getValue("logStatisticSamples");
646     anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
647
648     if(list == "all") {
649       if(statEngine.enableSampleLog(/* -1: all concepts */))
650         LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
651     } else {
652       anna::Tokenizer lst;
653       lst.apply(cl.getValue("logStatisticSamples"), ",");
654
655       if(lst.size() >= 1) {
656         anna::Tokenizer::const_iterator tok_min(lst.begin());
657         anna::Tokenizer::const_iterator tok_max(lst.end());
658         anna::Tokenizer::const_iterator tok_iter;
659         int conceptId;
660
661         for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
662           conceptId = atoi(anna::Tokenizer::data(tok_iter));
663
664           if(statEngine.enableSampleLog(conceptId))
665             LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
666         }
667       }
668     }
669   }
670
671
672   // Start client connections //////////////////////////////////////////////////////////////////////////////////
673   MyDiameterEntity *entity;
674   for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
675     entity = it->second->getEntity();
676     if (entity) entity->bind();
677   }
678
679   // Go into communicator poll
680   // Reconnection period (tcp reconnect retry time):
681   const char *varname = "reconnectionPeriod";
682   anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000;
683
684   a_communicator->setRecoveryTime(reconnectionPeriod);
685   if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket);  // HTTP
686   a_communicator->accept();
687 }
688
689
690 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
691   // Get hex string
692   static char buffer[8192];
693   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
694
695   if(infile.is_open()) {
696     infile >> buffer;
697     std::string hexString(buffer, strlen(buffer));
698     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
699     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
700     LOGDEBUG(
701       std::string msg = "Hex string (remove colons if exists): ";
702       msg += hexString;
703       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
704     );
705     anna::functions::fromHexString(hexString, db);
706     // Close file
707     infile.close();
708     return true;
709   }
710
711   return false;
712 }
713
714 void Launcher::resetStatistics() throw() {
715   getWorkingNode()->getMyDiameterEngine()->resetStatistics();
716 }
717
718 void Launcher::resetCounters() throw() {
719   anna::diameter::comm::OamModule::instantiate().resetCounters();
720   anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
721   anna::diameter::codec::OamModule::instantiate().resetCounters();
722 }
723
724 void Launcher::signalUSR2() throw(anna::RuntimeException) {
725   LOGNOTICE(
726     std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
727     msg += SIGUSR2_TASKS_INPUT_FILENAME;
728     msg += "' (results will be written at '";
729     msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
730     msg += "')";
731     anna::Logger::notice(msg, ANNA_FILE_LOCATION);
732   );
733   // Operation:
734   std::string line;
735   std::string response_content;
736   std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
737   std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
738
739   if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
740
741   if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
742
743   while(getline(in_file, line)) {
744     LOGDEBUG(
745       std::string msg = "Processing line: ";
746       msg += line;
747       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
748     );
749
750     try {
751       eventOperation(line, response_content);
752     } catch(RuntimeException &ex) {
753       ex.trace();
754     }
755
756     out_file << response_content;
757   }
758
759   in_file.close();
760   out_file.close();
761 }
762
763 std::string Launcher::help() const throw() {
764   std::string result = "\n";
765   result += "\n                     ------------- HELP -------------\n";
766   result += "\n";
767   result += "\nOVERVIEW";
768   result += "\n--------";
769   result += "\n";
770   result += "\nThe ADML (ANNA Diameter Multirealm Launcher) process is a multi-realm node with client and server";
771   result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server (i.e. to";
772   result += "\n simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.), and balancer";
773   result += "\n systems to provide failover to external round-robin launchers. Also, auxiliary encoder/decoder/loader";
774   result += "\n function could be deployed to reinterpret certain external flow and send it to another process.";
775   result += "\n ";
776   result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
777   result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
778   result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
779   result += "\n generation, expiration control and many more features.";
780   result += "\n";
781   result += "\nThe ADML process can easily configure a many realm nodes as needed, which will have own endpoints.";
782   result += "\nYou should avoid loop configurations (client and server for that client) because automatic forwarding,";
783   result += "\n is implemented and this would get in a never ending cycle when a request is sent.";
784   result += "\n";
785   result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
786   result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
787   result += "\n";
788   result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
789   result += "\n   kill -10 <pid>";
790   result += "\n    or";
791   result += "\n   kill -s SIGUSR1 <pid>";
792   result += "\n    and then";
793   result += "\n   vi /var/tmp/anna.context.<pid>";
794   result += "\n";
795   result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
796   result += "\n handlers, diameter stacks, etc.), and a powerful log module could dump all the events";
797   result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
798   result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
799   result += "\n measurements.";
800   result += "\n";
801   result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
802   result += "\n";
803   result += "\n";
804   result += "\nCOMMAND LINE";
805   result += "\n------------";
806   result += "\n";
807   result += "\nStart the launcher process without arguments in order to see all the startup configuration";
808   result += "\n posibilities, many of which could be modified on the air through the management interface";
809   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
810   result += "\n";
811   result += "\nAs mandatory, the stacks enabled given through the applicationId and the xml dictionary:";
812   result += "\n   --stacks <appid1,dictionary1#appid2,dictionary2#...#appidN,dictionaryN>";
813   result += "\n";
814   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
815   result += "\n   --diameterServer localhost:3868 --diameterServerSessions 10 --entityServerSessions 0";
816   result += "\n";
817   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
818   result += "\n   --entity 192.168.12.11:3868,192.168.12.21:3868 --entityServerSessions 10 --diameterServerSessions 0";
819   result += "\n";
820   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
821   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
822   result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
823   result += "\n arguments in order to define the balancing behaviour.";
824   result += "\n";
825   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
826   result += "\n customized ones using '--cer <xml message file>' and '--dwr <xml message file>'.";
827   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
828   result += "\n customized ones using operations interface.";
829   result += "\n";
830   result += "\n";
831   result += "\nDYNAMIC OPERATIONS";
832   result += "\n------------------";
833   result += "\n";
834   result += "\nADML supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
835   result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
836   result += "\n separated by pipes. These are the available commands:";
837   result += "\n";
838   result += "\n--------------------------------------------------------------------------------------- General purpose";
839   result += "\n";
840   result += "\nhelp                                 This help. Startup information-level traces also dump this help.";
841   result += "\n";
842   result += "\n---------------------------------------------------------------------------------------- Node selection";
843   result += "\n";
844   result += "\nnode[|<name>]                         Select current working node by mean the registered name.";
845   result += "\n                                      All the subsequent operations will be referred to this node.";
846   result += "\n                                      Without argument, the current node is dumped on stdout.";
847   result += "\n";
848   result += "\n------------------------------------------------------------------------------------ Parsing operations";
849   result += "\n";
850   result += "\ncode|<source_file>|<target_file>     Encodes source file (pathfile) into target file (pathfile).";
851   result += "\ndecode|<source_file>|<target_file>   Decodes source file (pathfile) into target file (pathfile).";
852   result += "\nloadxml|<source_file>                Reinterpret xml source file (pathfile).";
853   result += "\n";
854   result += "\n------------------------------------------------------------------------------------------- Hot changes";
855   result += "\n";
856   result += "\nservices[|source file]               Adds and starts the services specified in the xml file provided.";
857   result += "\n                                      (if missing, the file 'services.xml' will be used).";
858   result += "\n                                     The last loaded realm node will be automatically the new current";
859   result += "\n                                      working node. This is used to load new nodes once the ADML is";
860   result += "\n                                      started, regardless if '--services' command line parameter was";
861   result += "\n                                      used or not. Those services which are not correctly loaded, will";
862   result += "\n                                      be ignored, keeping the process alive.";
863   result += "\n";
864   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
865   result += "\n                                      server socket.";
866   result += "\ncontext[|target file]                Application context could also be written by mean this operation,";
867   result += "\n                                      and not only through SIGUSR1. If optional path file is missing,";
868   result += "\n                                      default '/var/tmp/anna.context.<pid>' will be used.";
869   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
870   result += "\n                                      performance measurement. Context data can be written at";
871   result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
872   result += "\n                                      or sending operation 'context|[target file]'.";
873   result += "\nforceCountersRecord                  Forces dump to file the current counters of the process.";
874   result += "\n";
875   result += "\n<visibility action>[|<address>:<port>][|socket id]";
876   result += "\n";
877   result += "\n       Actions: hide, show (update state) and hidden, shown (query state).";
878   result += "\n       Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
879   result += "\n       If missing server (first parameter) all applications sockets will be affected.";
880   result += "\n       If missing socket (second parameter) for specific server, all its sockets will be affected.";
881   result += "\n";
882   result += "\n       All application client sessions are shown on startup, but standard delivery only use primary";
883   result += "\n        server ones except if fails. Balance configuration use all the allowed sockets. You could also";
884   result += "\n        use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
885   result += "\n        client sessions, but for this, hide/show feature seems easier.";
886   result += "\n";
887   result += "\n--------------------------------------------------------------------------------------- Flow operations";
888   result += "\n";
889   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
890   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
891   result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
892   result += "\nanswerxml2e[|source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
893   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
894   result += "\n                           as many queues as different message codes have been programmed.";
895   result += "\nanswerxml2c[|source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
896   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
897   result += "\n                           as many queues as different message codes have been programmed.";
898   result += "\nanswerxml[|source_file]    Same as 'answerxml2c'.";
899   result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
900   result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
901   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
902   result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
903   result += "\nanswerxml(2e/2c)|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
904   result += "\nanswerxml(2e/2c)|rotate    Enable the corresponding queue rotation, useful in performance tests.";
905   result += "\n                           Rotation consists in add again to the queue, each element retrieved for answering.";
906   result += "\n";
907   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
908   result += "\nspecial scenarios (protocol errors):";
909   result += "\n";
910   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
911   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
912   result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
913   result += "\n";
914   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
915   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
916   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
917   result += "\n";
918   result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
919   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
920   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
921   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
922   result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
923   result += "\n";
924   result += "\nIn the most complete situation (process with both client and server side) there are internally";
925   result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
926   result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
927   result += "\n each one we could program different answers corresponding to different request codes received.";
928   result += "\n";
929   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
930   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
931   result += "\n    use sendxml/sendhex operations better than programming.";
932   result += "\n";
933   result += "\nBalance ('--balance' command line parameter) could be used to forward server socket receptions through";
934   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
935   result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
936   result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
937   result += "\n";
938   result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
939   result += "\n";
940   result += "\nUsed as log file extensions (when '--splitLog' is provided on command line) and context preffixes on log";
941   result += "\n details when unique log file is dumped:";
942   result += "\n";
943   result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
944   result += "\n   [sent2c/send2cError]   Send to client (success/error)";
945   result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
946   result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
947   result += "\n   [recvfc]               Reception from client";
948   result += "\n   [recvfe]               Reception from entity";
949   result += "\n   [req2c-expired]        A request sent to client has been expired";
950   result += "\n   [req2e-expired]        A request sent to entity has been expired";
951   result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
952   result += "\n                           has been logged)";
953   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
954   result += "\n                           has been logged)";
955   result += "\n   [retry]                Request retransmission";
956   result += "\n";
957   result += "\n------------------------------------------------------------------------------------------- Burst tests";
958   result += "\n";
959   result += "\nburst|<action>[|parameter]     Used for performance testing, we first program diameter requests";
960   result += "\n                                messages in order to launch them from client side to the configured";
961   result += "\n                                diameter entity. We could start the burst with an initial load";
962   result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
963   result += "\n                                per answer received or expired context. There are 10 actions: clear,";
964   result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
965   result += "\n";
966   result += "\n   burst|clear                 Clears all loaded burst messages.";
967   result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
968   result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
969   result += "\n                                a certain initial load.";
970   result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
971   result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
972   result += "\n                               Popping all OTA requests implies burst stop because no more answer";
973   result += "\n                                will arrive to the process. Burst output file (--burstLog command";
974   result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
975   result += "\n                                represents one received answer for which no new request is sent.";
976   result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
977   result += "\n   burst|repeat[|[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
978   result += "\n                                amount is greater than burst list size, they will be limited when";
979   result += "\n                                the list is processed except when repeat mode is enabled.";
980   result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
981   result += "\n                                operations is that burst won't be awaken. Externally we could control";
982   result += "\n                                sending time (no request will be sent for answers).";
983   result += "\n   burst|goto|<order>          Updates current burst pointer position.";
984   result += "\n   burst|look[|order]          Show programmed burst message for order provided, current when missing.";
985   result += "\n";
986   result += "\n-------------------------------------------------------------------------------------- Advanced testing";
987   result += "\n";
988   result += "\n                           Burst mode only allows single interface interaction. For multiple interface";
989   result += "\n                            (realm) coordination, you could use the advanced test cases programming:";
990   result += "\n";
991   result += "\n";
992   result += "\n   test|<id>|<command>[|parameters]";
993   result += "\n";
994   result += "\n                           Adds a new step to the test case with provided identifier. If provided identifier";
995   result += "\n                            is not registered yet, a new test case will be created with that value and the";
996   result += "\n                            step will be added as the first. For a specific 'id', the steps are stored in";
997   result += "\n                            order as they are programmed";
998   result += "\n";
999   result += "\n                           <id>: integer number, normally monotonically increased for each test case. Some external";
1000   result += "\n                                 script/procedure shall clone a test case template in order to build a collection";
1001   result += "\n                                 of independent and coherent test cases (normally same type) with different context";
1002   result += "\n                                 values (Session-Id, Subscriber-Id, etc.).";
1003   result += "\n";
1004   result += "\n                           <command>: commands to be executed for the test id provided. Each command programmed";
1005   result += "\n                                      constitutes a test case 'step', numbered from 1 to N.";
1006   result += "\n";
1007   result += "\n                              timeout|<msecs>            Sets an asynchronous timer to restrict the maximum timeout";
1008   result += "\n                                                          until last test step. Normally, this command is invoked";
1009   result += "\n                                                          in the first step, anyway it measures the time from the";
1010   result += "\n                                                          execution point whatever it is. The expiration will abort";
1011   result += "\n                                                          the test if still running. One or more timeouts could be";
1012   result += "\n                                                          programmed (not usual), but the more restrict will apply.";
1013   result += "\n                                                         It is highly recommended to program a initial timeout step,";
1014   result += "\n                                                          or the test case could be eternally in-progress.";
1015   result += "\n";
1016   result += "\n                              sendxml2e|<source_file>[|<step number>]";
1017   result += "\n                                                         Sends xml source file (pathfile) to entity (it would be a";
1018   result += "\n                                                          'forward' event if it came through local server endpoint).";
1019   result += "\n                                                         The step number should be provided for answers to indicate";
1020   result += "\n                                                          the 'wait for request' corresponding step. If you miss this";
1021   result += "\n                                                          reference, the sequence information (hop-by-hop, end-to-end)";
1022   result += "\n                                                          will be sent as they are in the answer xml message (realize";
1023   result += "\n                                                          the difficulty of predicting these information). Be sure to";
1024   result += "\n                                                          refer to a 'wait for request' step. Conditions like 'regexp'";
1025   result += "\n                                                          (as we will see later) are not verified.";
1026   result += "\n";
1027   result += "\n                              sendxml2c|<source_file>[|<step number>]";
1028   result += "\n                                                         Sends xml source file (pathfile) to client (it would be a";
1029   result += "\n                                                          'forward' event if it came through remote server endpoint).";
1030   result += "\n                                                         Same commented for 'sendxml2e' regarding the step number.";
1031   result += "\n";
1032   result += "\n                              delay|<msecs>              Blocking step until the time lapse expires. Useful to give ";
1033   result += "\n                                                          some cadence control and time schedule for a specific case.";
1034   result += "\n                              wait<fe/fc>|<condition>    Blocking step until condition is fulfilled. The message could";
1035   result += "\n                                                          received from entity (waitfe) or from client (waitfc).";
1036   result += "\n";
1037   result += "\n                              wait<fe/fc>-regexp|<regexp>";
1038   result += "\n                                                          Wait condition, from entity (waitfe-regexp) or client (waitfc-regexp)";
1039   result += "\n                                                          to match the serialized xml content for received messages. CPU cost";
1040   result += "\n                                                          is bigger than the former ones because the whole message must be";
1041   result += "\n                                                          decoded and converted to xml instead of doing a direct hexadecimal";
1042   result += "\n                                                          buffer search. The main advantage is the great flexibility to identify";
1043   result += "\n                                                          any content with a regular expression.";
1044   result += "\n";
1045   result += "\n                           <condition>: Optional parameters which must be fulfilled to continue through the next step.";
1046   result += "\n                                        Any received message over diameter interfaces will be evaluated against the";
1047   result += "\n                                         corresponding test case starting from the current step until the first one";
1048   result += "\n                                         whose condition is fulfilled. If no condition is fulfilled the event will be";
1049   result += "\n                                         classified as 'uncovered' (normally a test case bad configuration, or perhaps";
1050   result += "\n                                         a real unexpected message).";
1051
1052   // TODO(***)
1053 //  result += "\n                                        The way to identify the test case, is through registered Session-Id values for";
1054 //  result += "\n                                         programmed requests. But this depends on the type of node. Acting as clients,";
1055 //  result += "\n                                         requests received have Session-Id values which are already registered with";
1056 //  result += "\n                                         one test case, causing an error if not found. Acting as servers, requests are";
1057 //  result += "\n                                         received over a diameter local server from a client which are generating that";
1058 //  result += "\n                                         Session-Id values. Then we know nothing about such values. The procedure in";
1059 //  result += "\n                                         this case is find out a test case not-started containing a condition which";
1060 //  result += "\n                                         comply with the incoming message, and reactivates it.";
1061   // The other solution: register Session-Id values for answers send to client from a local diameter server.
1062
1063   result += "\n                                        How to answer: a wait condition for a request will store the incoming message";
1064   result += "\n                                         which fulfills that condition. This message is useful together with the peer";
1065   result += "\n                                         connection source in a further send step configured with the corresponding";
1066   result += "\n                                         response. You could also insert a delay between wait and send steps to be";
1067   result += "\n                                         more realistic (processing time simulation in a specific ADML realm node).";
1068   result += "\n                                         Always, a response send step will get the needed information from the most";
1069   result += "\n                                         recent wait step finding in reverse order (note that some race conditions";
1070   result += "\n                                         could happen if your condition is not specific enough).";
1071
1072   result += "\n";
1073   result += "\n                                        Condition format:";
1074   result += "\n";
1075   result += "\n                                           [code]|[bitR]|[ResultCode]|[sessionId]|[hopByHop]|[msisdn]|[imsi]|[serviceContextId]";
1076   result += "\n";
1077   result += "\n                                             code: integer number";
1078   result += "\n                                             bitR: 1 (request), 0 (answer)";
1079   result += "\n                                             ResultCode: integer number";
1080   result += "\n                                             sessionId: string";
1081   result += "\n                                             hopByHop: integer number or request send step reference: #<step number>";
1082   result += "\n";
1083   result += "\n                                                       Using the hash reference, you would indicate a specific wait condition";
1084   result += "\n                                                        for answers. The step number provided must correspond to any of the";
1085   result += "\n                                                        previous send commands (sendxml2e/sendxml2c) configured for a request.";
1086   result += "\n                                                       This 'hop-by-hop' variant eases the wait condition for answers in the";
1087   result += "\n                                                        safest way.";
1088   result += "\n";
1089   result += "\n                                             msisdn: string";
1090   result += "\n                                             imsi: string";
1091   result += "\n                                             serviceContextId: string";
1092   result += "\n";
1093   result += "\n                                        Take into account these rules, useful in general:";
1094   result += "\n";
1095   result += "\n                                           - Be as much specific as possible defining conditions to avoid ambiguity sending";
1096   result += "\n                                             messages out of context due to race conditions. Although you could program several";
1097   result += "\n                                             times similar conditions, some risky practices will throw a warning trace (if you";
1098   result += "\n                                             repeat the same condition within the same test case).";
1099   result += "\n                                           - Adding a ResultCode and/or HopByHop to the condition are only valid waiting answers.";
1100   result += "\n                                           - Requests hop-by-hop values must be different for all the test case requests.";
1101   result += "\n                                             RFC says that a hop by hop must be unique for a specific connection, something that";
1102   result += "\n                                             could be difficult to manage if we have multiple available connections from client";
1103   result += "\n                                             side endpoint (entity or local server), even if we would have only one connection but";
1104   result += "\n                                             several realm interfaces. It is enough to configure different hop-by-hop values within";
1105   result += "\n                                             each test case, because on reception, the Session-Id is used to identify that test case.";
1106   result += "\n";
1107   result += "\n";
1108   result += "\n";
1109   result += "\n";
1110   result += "\n                           Programming example:";
1111   result += "\n";
1112   result += "\n                              Basic Rx/Gx scenary: PCEF (Gx) - PCRF - AF (Rx)";
1113   result += "\n";
1114   result += "\n                              test|1|timeout|5000                  (step 1: whole time requirement is 5 seconds)";
1115   result += "\n                              test|1|sendxml2e|CCR-I.xml           (step 2: imagine this xml uses the Session-Id 'SGx')";
1116   result += "\n                              test|1|waitfe|272|0|2001|SGx         (step 3: waits the CCA for the CCR-I with Result-Code = DIAMETER_SUCCESS)";
1117   result += "\n                              test|1|sendxml2e|AAR-flows.xml       (step 4: imagine this xml uses the Session-Id 'SRx')";
1118   result += "\n                              test|1|waitfe|265|0|2001|SRx         (step 5: waits the AAA for the AAR-flows with Result-Code = DIAMETER_SUCCESS)";
1119   result += "\n                              test|1|waitfe|258|1||SGx             (step 6: waits the RAR (install policies) from the PCRF server)";
1120   result += "\n                              test|1|sendxml2e|RAA-install.xml|6   (step 7: sends the response for the RAR)";
1121   result += "\n                              test|1|sendxml2e|CCR-T.xml           (step 8: termination of the Gx session, imagine this xml puts hop-by-hop 'H1')";
1122   result += "\n                              test|1|waitfe|272|0|2001|SGx|H1      (step 9: waits the CCA for the CCR-T with Result-Code = DIAMETER_SUCCESS and hop-by-hop 'H1')";
1123   result += "\n                              test|1|waitfe|258|1||SGx             (step 10: waits the RAR (remove policies) from the PCRF server)";
1124   result += "\n                              test|1|sendxml2e|RAA-remove.xml|10   (step 11: sends the response for the RAR)";
1125   result += "\n";
1126   result += "\n                              Notes: We added an additional condition in step 9: the hop-by-hop. When we program the corresponding";
1127   result += "\n                                      source request (CCR-T), we configured the value 'H1' for the hop-by-hop. This is an 'application";
1128   result += "\n                                      value' because the real hop-by-hop transported through the client connection is managed by the";
1129   result += "\n                                      diameter stack. But when returned, the transaction pool resolve the original value. This feature";
1130   result += "\n                                      is necessary to ease the implementation of certain diameter agents (proxies for example). In our";
1131   result += "\n                                      case, we could format the hop-by-hop values within the request templates with total freedom to";
1132   result += "\n                                      improve the programmed conditions.";
1133   result += "\n";
1134   result += "\n                                     In the case of 'waiting for requests' is not such easy. Indeed, steps 6 and 10 will write a warning";
1135   result += "\n                                      because they are the same condition. We know that we are not going to have any problem because";
1136   result += "\n                                      such events are blocking-protected regarding logic-dependent messages (CCR-T), and race condition";
1137   result += "\n                                      is absolutely strange in this case.";
1138   result += "\n";
1139   result += "\n                                     You could speed up the test case moving forward steps like 3 & 5, understood as non-strict requirements";
1140   result += "\n                                      to continue testing. Anyway, remember that test cases should be as real as possible, and that there";
1141   result += "\n                                      are many ways to increase the load rate as we will see in next section (test cases execution).";
1142   result += "\n";
1143   result += "\n                                     Other simplifications: the steps 3, 5 and 9 can be replaced by";
1144   result += "\n";
1145   result += "\n                                        test|1|waitfe||0|||#2";
1146   result += "\n                                        test|1|waitfe||0|||#4";
1147   result += "\n                                        test|1|waitfe||0|||#8";
1148   result += "\n";
1149   result += "\n                                        which means that hop-by-hop must be retrieved from steps 2, 4 and 8 respectively,";
1150   result += "\n                                        and the expected message shall be an answer. Normally you will add other conditions,";
1151   result += "\n                                        for example a DIAMETER_SUCCESS result (adding 2001 as Result-Code).";
1152   result += "\n";
1153   result += "\nTest cases execution:";
1154   result += "\n";
1155   result += "\n";
1156   result += "\n   test|ttps|<amount>            Starts/resume the provided number of test ticks per second (ttps). The ADML starts";
1157   result += "\n                                 with the event trigger system suspended, and this operation is neccessary to begin";
1158   result += "\n                                 those cases which need this time event (internal triggering). Some other test cases";
1159   result += "\n                                 could be started through external events (first test case event could be programmed";
1160   result += "\n                                 to wait specific message), but is not usual this external mode and neither usual to";
1161   result += "\n                                 mix triggering types. Normally, you will pause/stop new test launchs providing 0 as";
1162   result += "\n                                 ttps value, and also you could dynamically modify the load rate updating that value.";
1163   result += "\n                                 If a test case has N messages then 'ttps * N' will be the virtual number of messages";
1164   result += "\n                                 managed per second when no bottleneck exists.";
1165   result += "\n";
1166   result += "\n                                 Provide 0 in order to stop the timer triggering.";
1167   result += "\n";
1168   result += "\n                                 There timer manager resolution currently harcoded allows a maximum  of ";
1169   result += anna::functions::asString(1000/a_admlMinResolution); result += " events";
1170   result += "\n                                 per second. To reach greater rates ADML will join synchronously the needed number of";
1171   result += "\n                                 new time-triggered test cases per a single event, writting a warning-level trace to";
1172   result += "\n                                 advice about the risk of burst sendings and recommend launching multiple instances";
1173   result += "\n                                 to achieve such load with a lower rate per instance.";
1174   result += "\n";
1175   result += "\n   test|ip-limit[|amount]        In-progress limit of test cases. No new test cases will be launched over this value";
1176   result += "\n                                 (test Manager tick work will be ignored). Zero-value is equivalent to stop the clock.";
1177   result += "\n                                 tick, -1 is used to specify 'no limit' which is the default. If missing amount, the";
1178   result += "\n                                 limit and current amount of in-progress test cases will be shown.";
1179   result += "\n";
1180   result += "\n   test|goto|<id>                Updates current test pointer position.";
1181   result += "\n";
1182   result += "\n   test|look[|id]                Show programmed test case for id provided, current when missing. Test cases programmed";
1183   result += "\n                                 are not dumped on process context (too many information in general). When the test case";
1184   result += "\n                                 has been completed or initiated, it will contain context information acting as a report.";
1185   result += "\n";
1186   result += "\n   test|report[|[yes]|no]        Every time a test case is finished, its xml representation will be dump on a file under";
1187   result += "\n                                 the execution directory (or the one configured in process command-line 'tmDir') with";
1188   result += "\n                                 the name 'testcase.<id>.xml'. If repeat mode is active, new test case executions will";
1189   result += "\n                                 append its reports into the same file. This option is disabled by default to improve";
1190   result += "\n                                 performance (reducing IO). ADML process context will show test manager whole information";
1191   result += "\n                                 and test case reports will be written depending on this report option. Anyway, you could";
1192   result += "\n                                  use the 'look' operation to see the report.";
1193   result += "\n";
1194   result += "\n   test|reset|<soft/hard>[|id]   Reset the test case for id provided, all the tests when missing. It could be hard/soft:";
1195   result += "\n                                 - hard: you probably may need to stop the load rate before. This operation initializes";
1196   result += "\n                                         all test cases regardless their states.";
1197   result += "\n                                 - soft: only for finished cases (those with 'Success' or 'Failed' states). It does not";
1198   result += "\n                                         affect to test cases with 'InProgress' state.";
1199   result += "\n";
1200   result += "\n   test|repeat[|[yes]|no]        Restarts the whole programmed test list when finished, disabled by default (testing";
1201   result += "\n                                 time trigger system will enter suspended state until new ttps operation is received).";
1202   result += "\n                                 Test cases state & data will be reset (when achieved again), but general statistics";
1203   result += "\n                                 and counters will continue measuring until reset with 'collect' operation.";
1204   result += "\n                                 When the test cases pool has been processed (and this repeat option is disabled), you";
1205   result += "\n                                 could reactivate the testing by mean 'test|reset|soft' and then 'test|ttps|<value>'.";
1206   result += "\n";
1207   result += "\n   test|clear                    Clears all the programmed test cases and stop testing (if in progress).";
1208   result += "\n";
1209   result += "\n";
1210   result += "\nUSING OPERATIONS INTERFACE";
1211   result += "\n--------------------------";
1212   result += "\n";
1213   result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
1214   result += "\n";
1215   result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
1216   result += "\n to define the http server at the command line with something like: '--httpServer localhost:9000'.";
1217   result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
1218   result += "\n using curl client could be:";
1219   result += "\n";
1220   result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
1221   result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
1222   result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
1223   result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
1224   result += "\n   etc.";
1225   result += "\n";
1226   result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
1227   result += "\n";
1228   result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
1229   result += "\n signal event:";
1230   result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
1231   result += "\n    then";
1232   result += "\n   kill -12 <pid>";
1233   result += "\n    or";
1234   result += "\n   kill -s SIGUSR2 <pid>";
1235   result += "\n    and then see the results:";
1236   result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
1237   result += "\n";
1238   result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
1239   result += "\n case over the output file. Take into account that all the content of the task file will be executed";
1240   result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
1241   result += "\n interface.";
1242   result += "\n";
1243   result += "\n";
1244   return result;
1245 }
1246
1247 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1248   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1249   CommandLine& cl(anna::CommandLine::instantiate());
1250   TestManager &testManager = TestManager::instantiate();
1251   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1252
1253   // Default response:
1254   response_content = "Operation processed with exception (see traces): ";
1255   response_content += operation;
1256   response_content += "\n";
1257
1258   std::string result_msg = "";
1259   anna::DataBlock db_aux(true);
1260
1261
1262   ///////////////////////////////////////////////////////////////////
1263   // Simple operations without arguments:
1264
1265   // Help:
1266   if(operation == "help") {
1267     std::string s_help = help();
1268     std::cout << s_help << std::endl;
1269     LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1270     response_content = "Help dumped on stdout and information-level traces\n";
1271     return;
1272   }
1273
1274   // Reset performance data:
1275   if(operation == "collect") {
1276     resetCounters();
1277     resetStatistics();
1278     response_content = "All process counters & statistic information have been reset\n";
1279     return;
1280   }
1281
1282   // Counters dump on demand:
1283   if(operation == "forceCountersRecord") {
1284     forceCountersRecord();
1285     response_content = "Current counters have been dump to disk\n";
1286     return;
1287   }
1288
1289   ///////////////////////////////////////////////////////////////////
1290   // Tokenize operation
1291   Tokenizer params;
1292   params.apply(operation, "|", "<null>" /* allow contiguous separators */);
1293   int numParams = params.size() - 1;
1294
1295   // Get the operation type and parameters:
1296   Tokenizer::const_iterator tok_iter = params.begin();
1297   std::string opType = Tokenizer::data(tok_iter);
1298   std::string param1, param2, param3, param4, param5, param6, param7, param8, param9, param10;
1299   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1300   if(numParams >= 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1301   if(numParams >= 3) { tok_iter++; param3 = Tokenizer::data(tok_iter); }
1302   // Tests conditions
1303   if(numParams >= 4) { tok_iter++; param4 = Tokenizer::data(tok_iter); }
1304   if(numParams >= 5) { tok_iter++; param5 = Tokenizer::data(tok_iter); }
1305   if(numParams >= 6) { tok_iter++; param6 = Tokenizer::data(tok_iter); }
1306   if(numParams >= 7) { tok_iter++; param7 = Tokenizer::data(tok_iter); }
1307   if(numParams >= 8) { tok_iter++; param8 = Tokenizer::data(tok_iter); }
1308   if(numParams >= 9) { tok_iter++; param9 = Tokenizer::data(tok_iter); }
1309   if(numParams >= 10) { tok_iter++; param10 = Tokenizer::data(tok_iter); }
1310   // Remove '<null>' artificial token to ease further checkings:
1311   if (param1 == "<null>") param1 = "";
1312   if (param2 == "<null>") param2 = "";
1313   if (param3 == "<null>") param3 = "";
1314   if (param4 == "<null>") param4 = "";
1315   if (param5 == "<null>") param5 = "";
1316   if (param6 == "<null>") param6 = "";
1317   if (param7 == "<null>") param7 = "";
1318   if (param8 == "<null>") param8 = "";
1319   if (param9 == "<null>") param9 = "";
1320   if (param10 == "<null>") param10 = "";
1321
1322   // No operation has more than 2 arguments except 'test' ...
1323   if(opType != "test" && numParams > 2)
1324     throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1325
1326
1327   // Check the number of parameters:
1328   bool wrongBody = false;
1329
1330   if((opType == "node") && (numParams > 1)) wrongBody = true;
1331
1332   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1333
1334   if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1335
1336   if((opType == "burst") && (numParams < 1)) wrongBody = true;
1337
1338   if((opType == "test") && (numParams < 1)) wrongBody = true;
1339
1340   if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1341
1342   if(wrongBody) {
1343     // Launch exception
1344     std::string msg = "Wrong body content format on HTTP Request for '";
1345     msg += opType;
1346     msg += "' operation (missing parameter/s). Use 'help' management command to see more information.";
1347     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1348   }
1349
1350   // Operations:
1351   if(opType == "context") {
1352     std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
1353     writeContext(contextFile);
1354     response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
1355     return;
1356   }
1357
1358   if(opType == "services") {
1359     std::string servicesFile = ((numParams == 1) ? param1 : "services.xml");
1360     try {
1361       loadServices(servicesFile, true /* bind entities */);
1362     }
1363     catch(anna::RuntimeException &ex) {
1364       ex.trace();
1365       response_content = anna::functions::asString("Loaded services from file '%s' with some problems (ignored ones)\n", servicesFile.c_str());
1366       return;
1367     }
1368     response_content = anna::functions::asString("Loaded services from file '%s'\n", servicesFile.c_str());
1369     return;
1370   }
1371
1372   // Realm switch:
1373   if(opType == "node") {
1374     if (param1 != "") {
1375       if (setWorkingNode(param1)) response_content = anna::functions::asString("Current node is now '%s'\n", param1.c_str());
1376     }
1377     else {
1378       std::cout << getWorkingNode()->asXMLString() << std::endl;
1379     }
1380     return;
1381   }
1382
1383   // Diameter endpoints:
1384   MyDiameterEntity *entity = getWorkingNode()->getEntity();
1385   MyDiameterEngine *commEngine = getWorkingNode()->getMyDiameterEngine();
1386   MyLocalServer *localServer = getWorkingNode()->getDiameterServer();
1387   anna::diameter::codec::Message codecMsg(getCodecEngine());
1388
1389
1390   if(opType == "code") {
1391     codecMsg.loadXML(param1);
1392     std::string hexString = anna::functions::asHexString(codecMsg.code());
1393     // write to outfile
1394     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1395     outfile.write(hexString.c_str(), hexString.size());
1396     outfile.close();
1397   } else if(opType == "decode") {
1398     // Get DataBlock from file with hex content:
1399     if(!getDataBlockFromHexFile(param1, db_aux))
1400       throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1401
1402     // Decode
1403     try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1404
1405     std::string xmlString = codecMsg.asXMLString();
1406     // write to outfile
1407     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1408     outfile.write(xmlString.c_str(), xmlString.size());
1409     outfile.close();
1410   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1411     if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1412
1413     if(param1 != "") {
1414       if(param2 != "") {
1415         std::string key = param1;
1416         key += "|";
1417         key += param2;
1418
1419         if(opType == "hide") commEngine->findClientSession(key)->hide();
1420
1421         if(opType == "show") commEngine->findClientSession(key)->show();
1422
1423         if(opType == "hidden") result_msg = commEngine->findClientSession(key)->hidden() ? "true" : "false";
1424
1425         if(opType == "shown") result_msg = commEngine->findClientSession(key)->shown() ? "true" : "false";
1426       } else {
1427         std::string address;
1428         int port;
1429         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1430
1431         if(opType == "hide") commEngine->findServer(address, port)->hide();
1432
1433         if(opType == "show") commEngine->findServer(address, port)->show();
1434
1435         if(opType == "hidden") result_msg = commEngine->findServer(address, port)->hidden() ? "true" : "false";
1436
1437         if(opType == "shown") result_msg = commEngine->findServer(address, port)->shown() ? "true" : "false";
1438       }
1439     } else {
1440       if(opType == "hide") entity->hide();
1441
1442       if(opType == "show") entity->show();
1443
1444       if(opType == "hidden") result_msg = entity->hidden() ? "true" : "false";
1445
1446       if(opType == "shown") result_msg = entity->shown() ? "true" : "false";
1447     }
1448   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1449     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1450     anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
1451
1452     if((opType == "sendxml") || (opType == "sendxml2e")) {
1453       codecMsg.loadXML(param1);
1454       msg->clearBody();
1455       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)
1456
1457       msg->setBody(codecMsg.code());
1458     } else {
1459       // Get DataBlock from file with hex content:
1460       if(!getDataBlockFromHexFile(param1, db_aux))
1461         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1462
1463       msg->setBody(db_aux);
1464     }
1465
1466     bool success = entity->send(msg, cl.exists("balance"));
1467     getWorkingNode()->releaseCommMessage(msg);
1468
1469     // Detailed log:
1470     if(getWorkingNode()->logEnabled()) {
1471       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1472       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1473       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1474       getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
1475     }
1476   } else if((opType == "burst")) {
1477     if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1478
1479     // burst|clear                     clears all loaded burst messages.
1480     // burst|load|<source_file>        loads the next diameter message into launcher burst.
1481     // burst|start|<initial load>      starts the message sending with a certain initial load.
1482     // burst|push|<load amount>        sends specific non-aynchronous load.
1483     // burst|stop                      stops the burst cycle.
1484     // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1485     // burst|send|<amount>             send messages from burst list. The main difference with
1486     //                                 start/push operations is that burst won't be awaken.
1487     //                                 Externally we could control sending time (no request
1488     //                                 will be sent for answers).
1489     // burst|goto|<order>              Updates current burst pointer position.
1490     // burst|look|<order>              Show programmed burst message for order provided, current when missing.
1491
1492     if(param1 == "clear") {
1493       result_msg = "removed ";
1494       result_msg += anna::functions::asString(getWorkingNode()->clearBurst());
1495       result_msg += " elements";
1496     } else if(param1 == "load") {
1497       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1498
1499       codecMsg.loadXML(param2);
1500
1501       if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1502       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)
1503
1504       int position = getWorkingNode()->loadBurstMessage(codecMsg.code());
1505       result_msg = "loaded '";
1506       result_msg += param2;
1507       result_msg += "' file into burst list position ";
1508       result_msg += anna::functions::asString(position);
1509     } else if(param1 == "start") {
1510       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1511
1512       int initialLoad = atoi(param2.c_str());
1513       int processed = getWorkingNode()->startBurst(initialLoad);
1514
1515       if(processed > 0) {
1516         result_msg = "initial load completed for ";
1517         result_msg += anna::functions::entriesAsString(processed, "message");
1518       }
1519     } else if(param1 == "push") {
1520       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1521
1522       int pushed = getWorkingNode()->pushBurst(atoi(param2.c_str()));
1523
1524       if(pushed > 0) {
1525         result_msg = "pushed ";
1526         result_msg += anna::functions::entriesAsString(pushed, "message");
1527       }
1528     } else if(param1 == "pop") {
1529       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1530
1531       int releaseLoad = atoi(param2.c_str());
1532       int popped = getWorkingNode()->popBurst(releaseLoad);
1533
1534       if(popped > 0) {
1535         result_msg = "burst popped for ";
1536         result_msg += anna::functions::entriesAsString(popped, "message");
1537       }
1538     } else if(param1 == "stop") {
1539       int left = getWorkingNode()->stopBurst();
1540
1541       if(left != -1) {
1542         result_msg += anna::functions::entriesAsString(left, "message");
1543         result_msg += " left to the end of the cycle";
1544       }
1545     } else if(param1 == "repeat") {
1546       if(param2 == "") param2 = "yes";
1547
1548       bool repeat = (param2 == "yes");
1549       getWorkingNode()->repeatBurst(repeat);
1550       result_msg += (repeat ? "repeat enabled" : "repeat disabled");
1551     } else if(param1 == "send") {
1552       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1553
1554       int sent = getWorkingNode()->sendBurst(atoi(param2.c_str()));
1555
1556       if(sent > 0) {
1557         result_msg = "sent ";
1558         result_msg += anna::functions::entriesAsString(sent, "message");
1559       }
1560     } else if(param1 == "goto") {
1561       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1562
1563       result_msg = getWorkingNode()->gotoBurst(atoi(param2.c_str()));
1564     } else if(param1 == "look") {
1565       int order = ((param2 != "") ? atoi(param2.c_str()) : -1);
1566       result_msg = "\n\n";
1567       result_msg += getWorkingNode()->lookBurst(order);
1568     } else {
1569       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1570     }
1571
1572   } else if((opType == "test")) {
1573     // test|<id>|<command>[|parameters]   Add a new step to the test case ...
1574     // test|ttps|<amount>                 Starts/resume the provided number of time ticks per second (ttps). The ADML starts ...
1575     // test|ip-limit[|amount]             In-progress limit of test cases. No new test cases will be launched over this value ...
1576     // test|repeat[|[yes]|no]             Restarts the programmed test cases when finished. Disabled by default: the testing ...
1577     // test|report[|[yes]|no]             Every time a test case is finished a report file in xml format will be created under ...
1578     // test|goto|<id>                     Updates current test pointer position.
1579     // test|look[|id]                     Show programmed test case for id provided, current when missing ...
1580     // test|reset|<soft/hard>[|id]        Reset the test case for id provided, all the tests when missing ...
1581     // test|clear                         Clears all the programmed test cases.
1582
1583     if(param1 == "ttps") {
1584       if (numParams > 2)
1585         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1586
1587       bool success = ((param2 != "") ? testManager.configureTTPS(atoi(param2.c_str())) : false);
1588       if (success) {
1589         result_msg = "assigned new test launch rate to ";
1590         result_msg += anna::functions::asString(atoi(param2.c_str()));
1591         result_msg += " events per second";
1592       }
1593       else {
1594         result_msg += "unable to configure the test rate provided";
1595       }
1596     }
1597     else if(param1 == "ip-limit") {
1598       if (numParams > 2)
1599         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1600
1601       unsigned int limit;
1602       if (param2 != "") {
1603         limit = atoi(param2.c_str());
1604         testManager.setInProgressLimit(limit);
1605         result_msg = "new in-progress limit: ";
1606         result_msg += (limit != UINT_MAX) ? anna::functions::asString(limit) : "<no limit>";
1607       }
1608       else {
1609         result_msg = "in-progress limit amount: ";
1610         limit = testManager.getInProgressLimit();
1611         result_msg += (limit != UINT_MAX) ? anna::functions::asString(limit) : "<no limit>";
1612         result_msg += "; currently there are ";
1613         result_msg += anna::functions::asString(testManager.getInProgressCount());
1614         result_msg += " test cases running";
1615       }
1616     }
1617     else if(param1 == "repeat") {
1618       if (numParams > 2)
1619         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1620
1621       if(param2 == "") param2 = "yes";
1622       testManager.setPoolRepeat((param2 == "yes"));
1623       result_msg += (testManager.getPoolRepeat() ? "repeat enabled" : "repeat disabled");
1624     }
1625     else if(param1 == "report") {
1626       if (numParams > 2)
1627         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1628
1629       if(param2 == "") param2 = "yes";
1630       testManager.setDumpReports((param2 == "yes"));
1631       result_msg += (testManager.getDumpReports() ? "report enabled" : "report disabled");
1632     }
1633     else if(param1 == "goto") {
1634       if (numParams > 2)
1635         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1636
1637       if(param2 == "") throw anna::RuntimeException("Missing id for test goto operation", ANNA_FILE_LOCATION);
1638       int id = atoi(param2.c_str());
1639       if (testManager.gotoTestCase(id)) {
1640         result_msg = "position updated for id provided (";
1641       }
1642       else {
1643         result_msg = "cannot found test id (";
1644       }
1645       result_msg += anna::functions::asString(id);
1646       result_msg += ")";
1647     }
1648     else if(param1 == "look") {
1649       if (numParams > 2)
1650         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1651
1652       int id = ((param2 != "") ? atoi(param2.c_str()) : -1);
1653       TestCase *testCase = testManager.findTestCase(id);
1654
1655       if (testCase) {
1656         result_msg = "\n\n";
1657         result_msg += testCase->asXMLString();
1658       }
1659       else {
1660         if (id == -1) {
1661           result_msg = "no current test case detected (testing started ?)";
1662         }
1663         else {
1664           result_msg = "cannot found test id (";
1665           result_msg += anna::functions::asString(id);
1666           result_msg += ")";
1667         }
1668       }
1669     }
1670     else if(param1 == "reset") {
1671       if (numParams > 3)
1672         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1673
1674       if (param2 != "soft" && param2 != "hard")
1675         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1676
1677       int id = ((param3 != "") ? atoi(param3.c_str()) : -1);
1678       TestCase *testCase = ((id != -1) ? testManager.findTestCase(id) : NULL);
1679
1680       if (testCase) {
1681         bool done = testCase->reset((param2 == "hard") ? true:false);
1682         result_msg = "test ";
1683         result_msg += param2;
1684         result_msg += " reset for id ";
1685         result_msg += anna::functions::asString(id);
1686         result_msg += done ? ": done": ": not done";
1687       }
1688       else {
1689         if (id == -1) {
1690           bool anyReset = testManager.resetPool((param2 == "hard") ? true:false);
1691           result_msg = "reset have been sent to all programmed tests: "; result_msg += anyReset ? "some/all was actually reset" : "nothing was reset";
1692         }
1693         else {
1694           result_msg = "cannot found test id (";
1695           result_msg += anna::functions::asString(id);
1696           result_msg += ")";
1697         }
1698       }
1699     }
1700     else if(param1 == "clear") {
1701       if (numParams > 1)
1702         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1703
1704       if (testManager.clearPool()) {
1705         result_msg = "all the programmed test cases have been dropped";
1706       }
1707       else {
1708         result_msg = "there are not programmed test cases to be removed";
1709       }
1710     }
1711     else {
1712       int id = atoi(param1.c_str());
1713       if(id < 0)
1714         throw anna::RuntimeException("Invalid test case identifier: must be a non-negative number", ANNA_FILE_LOCATION);
1715
1716       // PARAM: 1     2            3      4          5           6          7         8       9           10
1717       // test|<id>|<command>
1718       //             timeout|    <msecs>
1719       //             sendxml2e|  <file>[|<step number>]
1720       //             sendxml2c|  <file>[|<step number>]
1721       //             delay|      [msecs]
1722       //             wait<fe/fc>|[code]|[bitR]|[ResultCode]|[sessionId]|[hopByHop]|[msisdn]|[imsi]|[serviceContextId]
1723       //      wait<fe/fc>-answer|<step number>
1724       //      wait<fe/fc>-regexp|<regexp>
1725       if(param2 == "") throw anna::RuntimeException("Missing command for test id operation", ANNA_FILE_LOCATION);
1726
1727       // Commands:
1728       if (param2 == "timeout") {
1729         if (numParams > 3)
1730           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1731         if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'timeout' command in test id operation", ANNA_FILE_LOCATION);
1732         anna::Millisecond timeout = checkTimeMeasure("Test case timeout", param3);
1733         testManager.getTestCase(id)->addTimeout(timeout); // creates / reuses
1734       }
1735       else if ((param2 == "sendxml2e")||(param2 == "sendxml2c")) {
1736         if (numParams > 4)
1737           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1738         if(param3 == "") throw anna::RuntimeException(anna::functions::asString("Missing xml file for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
1739         codecMsg.loadXML(param3);
1740         if (codecMsg.isRequest()) {
1741           if (param4 != "")
1742             throw anna::RuntimeException("Step number is provided with answers (to resolve the corresponding 'wait for request' step), but NOT with requests", ANNA_FILE_LOCATION);
1743         }
1744         else {
1745           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));
1746         }
1747         int stepNumber = ((param4 != "") ? atoi(param4.c_str()):-1);
1748         std::string originRealm = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
1749         RealmNode *realm = getRealmNode(originRealm);
1750         if (!realm)
1751           throw anna::RuntimeException("Cannot identify the realm node for the manager message. Check the Origin-Realm avp value (use the realm node name)", ANNA_FILE_LOCATION);
1752
1753         if (param2 == "sendxml2e")
1754           testManager.getTestCase(id)->addSendxml2e(codecMsg.code(), realm, stepNumber); // creates / reuses
1755         else
1756           testManager.getTestCase(id)->addSendxml2c(codecMsg.code(), realm, stepNumber); // creates / reuses
1757       }
1758       else if (param2 == "delay") {
1759         if (numParams > 3)
1760           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1761         if(param3 == "") throw anna::RuntimeException("Missing milliseconds for 'delay' command in test id operation", ANNA_FILE_LOCATION);
1762         anna::Millisecond delay = checkTimeMeasure("Test case delay step", param3);
1763         testManager.getTestCase(id)->addDelay(delay); // creates / reuses
1764       }
1765       else if ((param2 == "waitfe")||(param2 == "waitfc")) {
1766         if (numParams > 10)
1767           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1768         if (param3 != "" || param4 != "" || param5 != "" || param6 != "" || param7 != "" || param8 != "" || param9 != "" || param10 != "") {
1769           bool fromEntity = (param2.substr(4,2) == "fe");
1770           testManager.getTestCase(id)->addWait(fromEntity, param3, param4, param5, param6, param7, param8, param9, param10);
1771         }
1772         else {
1773           throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
1774         }
1775       }
1776       else if ((param2 == "waitfe-regexp")||(param2 == "waitfc-regexp")) {
1777         if (numParams > 3)
1778           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1779         if (param3 != "") {
1780           bool fromEntity = (param2.substr(4,2) == "fe");
1781           testManager.getTestCase(id)->addWaitRegexp(fromEntity, param3);
1782         }
1783         else {
1784           throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
1785         }
1786       }
1787       else {
1788         throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1789       }
1790
1791       result_msg = "new step added to test id ";
1792       result_msg += anna::functions::asString(id);
1793     }
1794
1795   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1796     if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1797     anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
1798
1799     if(opType == "sendxml2c") {
1800       codecMsg.loadXML(param1);
1801       msg->clearBody();
1802       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)
1803
1804       msg->setBody(codecMsg.code());
1805     } else {
1806       // Get DataBlock from file with hex content:
1807       if(!getDataBlockFromHexFile(param1, db_aux))
1808         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1809
1810       msg->setBody(db_aux);
1811     }
1812
1813     bool success = localServer->send(msg);
1814     getWorkingNode()->releaseCommMessage(msg);
1815
1816     // Detailed log:
1817     if(getWorkingNode()->logEnabled()) {
1818       anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1819       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1820       getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
1821     }
1822   } else if(opType == "loadxml") {
1823     codecMsg.loadXML(param1);
1824     std::string xmlString = codecMsg.asXMLString();
1825     std::cout << xmlString << std::endl;
1826   } else if(opType == "diameterServerSessions") {
1827     int diameterServerSessions = atoi(param1.c_str());
1828
1829     if(localServer)
1830       localServer->setMaxConnections(diameterServerSessions);
1831     else
1832       LOGWARNING(anna::Logger::warning("To update the number of sessions, you must configure the process diameter local server: you could also launch it with no sessions (disabled)", ANNA_FILE_LOCATION));
1833
1834   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1835     if(!localServer)
1836       throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1837
1838     if(param1 == "") { // programmed answers FIFO's to stdout
1839       std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl;
1840       response_content = "Programmed answers dumped on stdout\n";
1841       return;
1842     } else if (param1 == "rotate") {
1843       localServer->getReactingAnswers()->rotate(true);
1844     } else if (param1 == "exhaust") {
1845       localServer->getReactingAnswers()->rotate(false);
1846     } else if (param1 == "clear") {
1847       localServer->getReactingAnswers()->clear();
1848     } else if (param1 == "dump") {
1849       localServer->getReactingAnswers()->dump();
1850     } else {
1851       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1852       LOGDEBUG
1853       (
1854         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1855       );
1856
1857       if(message->isRequest())
1858         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1859
1860       int code = message->getId().first;
1861       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1862       localServer->getReactingAnswers()->addMessage(code, message);
1863     }
1864   } else if(opType == "answerxml2e") {
1865     if(!entity)
1866       throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1867
1868     if(param1 == "") { // programmed answers FIFO's to stdout
1869       std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl;
1870       response_content = "Programmed answers dumped on stdout\n";
1871       return;
1872     } else if (param1 == "rotate") {
1873       entity->getReactingAnswers()->rotate(true);
1874     } else if (param1 == "exhaust") {
1875       entity->getReactingAnswers()->rotate(false);
1876     } else if (param1 == "clear") {
1877       entity->getReactingAnswers()->clear();
1878     } else if (param1 == "dump") {
1879       entity->getReactingAnswers()->dump();
1880     } else {
1881       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1882       LOGDEBUG
1883       (
1884         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1885       );
1886
1887       if(message->isRequest())
1888         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1889
1890       int code = message->getId().first;
1891       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1892       entity->getReactingAnswers()->addMessage(code, message);
1893     }
1894   } else {
1895     throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
1896   }
1897
1898   // HTTP response
1899   response_content = "Operation correctly processed: "; response_content += operation; response_content += " => ";
1900   response_content += result_msg;
1901 }
1902
1903 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
1904 throw() {
1905   anna::xml::Node* result = parent->createChild("launcher");
1906   anna::comm::Application::asXML(result);
1907   // Timming:
1908   result->createAttribute("StartTime", a_start_time.asString());
1909   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
1910   // Diameter:
1911   getCodecEngine()->asXML(result);
1912   for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
1913     it->second->asXML(result);
1914   }
1915
1916   // OAM:
1917   anna::diameter::comm::OamModule::instantiate().asXML(result);
1918   anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
1919   anna::diameter::codec::OamModule::instantiate().asXML(result);
1920   // Statistics:
1921   anna::statistics::Engine::instantiate().asXML(result);
1922
1923   // Testing: could be heavy if test case reports are enabled
1924   TestManager::instantiate().asXML(result);
1925
1926   return result;
1927 }