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