Remove temporary
[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
13 // Project
14 #include <anna/timex/Engine.hpp>
15 #include <anna/statistics/Engine.hpp>
16 #include <anna/diameter/codec/Engine.hpp>
17 #include <anna/http/Transport.hpp>
18 #include <anna/diameter/stack/Engine.hpp>
19 #include <anna/diameter/helpers/base/functions.hpp>
20 #include <anna/time/functions.hpp>
21 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
22 #include <anna/xml/xml.hpp>
23
24 // Process
25 #include "Launcher.hpp"
26 #include "RealmNode.hpp"
27 #include "MyDiameterEngine.hpp"
28
29
30 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
31 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
32
33
34 const char *ServicesDTD = "\
35 <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
36 <!-- Diameter services DTD -->\n\
37 \n\
38 <!ELEMENT services (stack*, node*)>\n\
39 \n\
40 <!ELEMENT stack EMPTY>\n\
41 <!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>\n\
42 <!--\n\
43    Stack record\n\
44 \n\
45    id:         Normally the id corresponds to the Application-Id for which the dictionary provided is designed.\n\
46                (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
47                for processed messages).\n\
48    dictionary: Path to the dictionary file\n\
49 -->\n\
50 \n\
51 <!ELEMENT node EMPTY>\n\
52 <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>\n\
53 <!--\n\
54    Node record\n\
55 \n\
56    originRealm:                             Node identifier (Origin-Realm name).\n\
57    applicationId:                           The Application-Id provided must exists as a registered 'stack id'.\n\
58    originHost:                              Diameter application host name (system name). If missing, process sets o.s. hostname\n\
59                                             Note that if you have two or more realms, the names must be different.\n\
60    cer:                                     User defined CER path file to be encoded to establish diameter connections.\n\
61                                             If missing, will be harcoded\n\
62    dwr:                                     User defined DWR path file to be encoded for diameter protocol keep alive.\n\
63                                             If missing, will be harcoded\n\
64    allowedInactivityTime:                   Milliseconds for the maximum allowed inactivity time on server sessions born over the\n\
65                                             local server before being reset. If missing, default value of 90000 will be assigned\n\
66    tcpConnectDelay:                         Milliseconds to wait TCP connect to any server. If missing, default value of 200 will\n\
67                                             be assigned\n\
68    answersTimeout:                          Milliseconds to wait pending application answers from diameter peers. If missing,\n\
69                                             default value of 10000 will be assigned\n\
70    ceaTimeout:                              Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'\n\
71                                             will be assigned\n\
72    watchdogPeriod:                          Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default\n\
73                                             value of 30000 will be assigned\n\
74    entity:                                  Target diameter entity (comma-separated '<address>:<port>' format).\n\
75                                             For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled\n\
76    entityServerSessions:                    Diameter entity server sessions (0: diameter entity disabled). Default value of 1\n\
77    diameterServer:                          Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.\n\
78                                             If missing, no local server will be enabled\n\
79    diameterServerSessions:                  Diameter own server available connections (0: diameter server disabled). Default value of 1\n\
80    balance:                                 Balance over entity servers instead of doing standard behaviour (first primary, secondary\n\
81                                             if fails, etc.). Default value 'no'\n\
82    sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part\n\
83                                             will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR\n\
84                                             analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;\n\
85                                             usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart')\n\
86    retries:                                 Expired responses will cause a number of request retransmissions. Disabled by default (0 retries)\n\
87    log:                                     Process log file (operations result, traffic log, etc.). By default '<originRealm>.launcher.log'.\n\
88                                             Empty string or \"null\" name, to disable. Warning: there is no rotation for log files\n\
89                                             (use logrotate or whatever you consider)\n\
90    splitLog:                                Splits log file (appends to log filename, extensions with the type of event: see help on\n\
91                                             startup information-level traces). No log files for code/decode and load operations are created.\n\
92                                             Default value 'no'\n\
93    detailedLog:                             Insert detailed information at log files. Should be disabled on automatic tests. Useful on\n\
94                                             'balance' mode to know messages flow along the sockets. Default value 'no'\n\
95    dumpLog:                                 Write to disk every incoming/outcoming message named as:\n\
96                                                '<originRealm>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'\n\
97                                             Default value 'no'\n\
98    burstLog:                                Burst operations log file. By default '<originRealm>.launcher.burst'. Empty string or \"null\" name, to disable.\n\
99                                             Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each\n\
100                                             burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst\n\
101                                             list size, plus OTA requests when changed\n\
102 \n\
103 -->\n\
104 \n\
105 ";
106
107
108 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
109   a_codecEngine = new anna::diameter::codec::Engine("MyCodecEngine");
110   a_timeEngine = NULL;
111   a_counterRecorder = NULL;
112   a_counterRecorderClock = NULL;
113
114   // a_nodes.clear();
115   a_workingNode = NULL;
116
117   a_httpServerSocket = NULL;
118 }
119
120
121
122
123 void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) {
124   //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
125   const anna::xml::Attribute  *id, *dictionary;
126
127   // <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
128   const anna::xml::Attribute  *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
129                               *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
130                               *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
131                               *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
132
133   // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
134
135   // Stacks
136   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
137   anna::diameter::stack::Dictionary *d;
138   ///////////////////////////////////////////
139   // APPLICATION MESSAGE OAM MODULE SCOPES //
140   ///////////////////////////////////////////
141   // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
142   anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
143   appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
144   static int scope_id = 3;
145
146   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
147     std::string nodeName = (*it)->getName();
148
149     if(nodeName == "stack") {
150       // Input data:
151       id = (*it)->getAttribute("id");
152       dictionary = (*it)->getAttribute("dictionary");
153
154       try {
155         d = stackEngine.createDictionary(id->getIntegerValue(), dictionary->getValue());
156         getCodecEngine()->setDictionary(d);
157
158         // OAM module for counters:
159         appMsgOamModule.createStackCounterScope(scope_id, id->getIntegerValue() /* application-id */);
160         scope_id++;
161
162       } catch(anna::RuntimeException &ex) {
163         //_exit(ex.asString());
164         throw ex;
165       }
166     }
167   }
168
169   // Show loaded stacks:
170   std::cout << "Stacks currently loaded:" << std::endl;
171   std::cout << anna::functions::tab(stackEngine.asString(false /* light */));
172   std::cout << std::endl;
173
174
175   // Codec engine adjustments:
176   // Auto stack selection based on Application-ID:
177   bool multistack = (stackEngine.stack_size() > 1);
178   if (multistack) getCodecEngine()->selectStackWithApplicationId(true);
179
180   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
181     std::string nodeName = (*it)->getName();
182
183     if(nodeName == "node") {
184       // Input data:
185       originRealm = (*it)->getAttribute("originRealm");
186       appId = (*it)->getAttribute("applicationId");
187       originHost = (*it)->getAttribute("originHost", false /* no exception */);
188       cer = (*it)->getAttribute("cer", false /* no exception */);
189       dwr = (*it)->getAttribute("dwr", false /* no exception */);
190       allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */);
191       tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */);
192       answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */);
193       ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */);
194       watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */);
195       entity = (*it)->getAttribute("entity", false /* no exception */);
196       entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */);
197       diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */);
198       diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */);
199       balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no)
200       sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin)
201       retries = (*it)->getAttribute("retries", false /* no exception */);
202       log = (*it)->getAttribute("log", false /* no exception */);
203       splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no)
204       detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no)
205       dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no)
206       burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no)
207
208       // Basic checkings:
209       if (stackEngine.getDictionary(appId->getIntegerValue()) == NULL) {
210         std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
211         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
212       }
213       realm_nodes_it nodeIt = a_nodes.find(originRealm->getValue());
214       if (nodeIt != a_nodes.end()) {
215         std::string msg = "Already registered node name (Origin-Realm): "; msg += originRealm->getValue();
216         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
217       }
218
219       // Engine time measures checking & assignment:
220       anna::Millisecond allowedInactivityTimeMs(90000);
221       anna::Millisecond tcpConnectDelayMs(200);
222       anna::Millisecond answersTimeoutMs(10000);
223       anna::Millisecond ceaTimeoutMs(10000);
224       anna::Millisecond watchdogPeriodMs(30000);
225
226       if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue());
227       if (tcpConnectDelay)       tcpConnectDelayMs =       checkTimeMeasure("tcpConnectDelay",       tcpConnectDelay->getValue());
228       if (answersTimeout)        answersTimeoutMs =        checkTimeMeasure("answersTimeout",        answersTimeout->getValue());
229       if (ceaTimeout)            ceaTimeoutMs =            checkTimeMeasure("ceaTimeout",            ceaTimeout->getValue());
230       if (watchdogPeriod)        watchdogPeriodMs =        checkTimeMeasure("watchdogPeriod",        watchdogPeriod->getValue());
231
232       // Checking command line parameters
233       std::string sessionBasedModelsType;
234       if(sessionBasedModelsClientSocketSelection) {
235         sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue();
236         if((sessionBasedModelsType != "SessionIdHighPart") && (sessionBasedModelsType != "SessionIdOptionalPart") && (sessionBasedModelsType != "RoundRobin")) {
237           throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
238         }
239       }
240
241       int retransmissions = retries ? retries->getIntegerValue() : 0;
242       if(retransmissions < 0) {
243         throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION);
244       }
245
246       // Create new Node instance /////////////////////////////////////////////////////////////////
247       a_workingNode = new RealmNode(originRealm->getValue(), appId->getIntegerValue(), a_codecEngine);
248       MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine();
249       /////////////////////////////////////////////////////////////////////////////////////////////
250
251       // Assignments:
252       commEngine->setMaxConnectionDelay(tcpConnectDelayMs);
253       commEngine->setWatchdogPeriod(watchdogPeriodMs);
254
255       // Realm information:
256       if (originHost) commEngine->setHost(originHost->getValue());
257       commEngine->setRealm(originRealm->getValue());
258
259       // Diameter entity:
260       if(entity) {
261         int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1;
262
263         if(sessions > 0) {
264           // Number of sessions:
265           commEngine->setNumberOfClientSessionsPerServer(sessions);
266
267           // Client CER and DWR
268           std::string cerPathfile = cer ? cer->getValue() : "";
269           std::string dwrPathfile = dwr ? dwr->getValue() : "";
270           commEngine->setClientCERandDWR(cerPathfile, dwrPathfile);
271
272           // Register one entity for this engine:
273           a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs);
274           a_workingNode->setRequestRetransmissions(retransmissions);
275           a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsType);
276           a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings
277           if (eventOperation) a_workingNode->getEntity()->bind();
278         }
279       }
280
281       // Diameter Server:
282       if(diameterServer) {
283         int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1;
284         a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs);
285       }
286
287       // Logs:
288       std::string realm = commEngine->getRealm();
289       std::string s_log = realm + ".launcher.log"; if (log) s_log = log->getValue();
290       bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false);
291       bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false);
292       bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false);
293       std::string s_burstLog = realm + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue();
294       a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog);
295
296
297       // Lazy initialization for comm engine:
298       if (eventOperation) commEngine->lazyInitialize();
299
300       // New Node assignment //////////////////////////////////////////////////////////////////////
301       a_nodes[originRealm->getValue()] = a_workingNode;
302       /////////////////////////////////////////////////////////////////////////////////////////////
303     }
304   }
305
306   // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started,
307   //  but this don't care because application startComponents() -> initialize() -> do_initialize() -> do nothing.
308   // And when stopped, running state is not checked and it will be stopped anyway.
309 }
310
311
312 void Launcher::loadServices(const std::string & xmlPathFile, bool eventOperation) throw(anna::RuntimeException) {
313
314   if (xmlPathFile == "null" || xmlPathFile == "") {
315     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));
316     return;
317   }
318
319   LOGDEBUG(
320     std::string trace = "Loading ADML services file '";
321     trace += xmlPathFile;
322     trace += "'";
323     anna::Logger::debug(trace, ANNA_FILE_LOCATION);
324   );
325   anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
326   anna::xml::DTDMemory xmlDTD;
327   const anna::xml::Node *rootNode;
328   xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
329   xmlDTD.initialize(ServicesDTD);
330   try {
331     rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
332   }
333   catch (anna::RuntimeException &ex) {
334     LOGWARNING(
335       std::string msg = "Services DTD schema:\n\n";
336       msg += ServicesDTD;
337       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
338     );
339     throw ex;
340   }
341
342   LOGDEBUG(
343     std::string trace = "Loaded XML file (";
344     trace += xmlPathFile;
345     trace += "):\n";
346     trace += anna::xml::Compiler().apply(rootNode);
347     anna::Logger::debug(trace, ANNA_FILE_LOCATION);
348   );
349   servicesFromXML(rootNode, eventOperation);
350 }
351
352
353 anna::Millisecond Launcher::checkTimeMeasure(const std::string &parameter, const std::string &value) throw(anna::RuntimeException) {
354
355   if(anna::functions::isLike("^[0-9]+$", value)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
356     int msecs;
357     std::istringstream ( value ) >> msecs;
358
359     if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
360       std::string msg = "Configuration value for '";
361       msg += parameter;
362       msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: ";
363       msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
364       throw RuntimeException(msg, ANNA_FILE_LOCATION);
365     }
366
367     if(msecs > 300000) {
368       std::string msg = "Configuration value for '";
369       msg += parameter;
370       msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes).";
371       LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
372     }
373
374     if(msecs <= a_timeEngine->getResolution()) {
375       std::string msg = "Configuration value for '";
376       msg += parameter;
377       msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: ";
378       msg += anna::functions::asString(a_timeEngine->getResolution());
379       throw RuntimeException(msg, ANNA_FILE_LOCATION);
380     }
381
382     return (anna::Millisecond)msecs; // ok
383   }
384
385   // Non-integer exception:
386   std::string msg = "Configuration error for '";
387   msg += parameter;
388   msg += "' = '";
389   msg += value;
390   msg += "': must be a non-negative integer number";
391   throw RuntimeException(msg, ANNA_FILE_LOCATION);
392 }
393
394 RealmNode *Launcher::getWorkingNode() const throw(anna::RuntimeException) {
395
396   if (!a_workingNode)
397     throw RuntimeException("No services yet loaded. Try 'services' operation (via management interface), or restart process using command-line 'services' parameter", ANNA_FILE_LOCATION);
398
399   return a_workingNode;
400 }
401
402 bool Launcher::setWorkingNode(const std::string &name) throw() {
403   bool result = false;
404
405   realm_nodes_nc_it nodeIt = a_nodes.find(name);
406   if (nodeIt == a_nodes.end()) {
407     LOGWARNING(
408       std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
409       anna::Logger::warning(msg, ANNA_FILE_LOCATION);
410     );
411   }
412   else {
413     a_workingNode = nodeIt->second;
414     result = true;
415   }
416
417   return result;
418 }
419
420 RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw() {
421   realm_nodes_it it = a_nodes.find(realmName);
422   if (it != a_nodes.end()) return it->second;
423
424   return NULL; // this never happens
425 }
426
427 void Launcher::initialize()
428 throw(anna::RuntimeException) {
429   anna::comm::Application::initialize();
430   CommandLine& cl(anna::CommandLine::instantiate());
431   anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
432   a_communicator = new MyCommunicator(workMode);
433
434   //a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, anna::timex::Engine::minResolution);
435   a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, (anna::Millisecond)100); // puedo bajar hasta 10
436
437   // Counters record procedure:
438   const char *varname = "cntRecordPeriod";
439   anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000;
440   if(cntRecordPeriod != 0) {
441     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
442     std::string cntDir = ".";
443     if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
444     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
445   }
446
447   // Tracing:
448   if(cl.exists("trace"))
449     anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
450
451   // Load launcher services:
452   loadServices(cl.getValue("services")); // before run (have components to be created)
453 }
454
455 void Launcher::run()
456 throw(anna::RuntimeException) {
457   LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
458   CommandLine& cl(anna::CommandLine::instantiate());
459   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
460
461   // Start time:
462   a_start_time.setNow();
463   // Statistics:
464   anna::statistics::Engine::instantiate().enable();
465
466   LOGINFORMATION(
467     // Help on startup traces:
468     anna::Logger::information(help(), ANNA_FILE_LOCATION);
469     // Test messages dtd:
470     std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
471     msg += anna::diameter::codec::MessageDTD;
472     anna::Logger::information(msg, ANNA_FILE_LOCATION);
473   );
474
475   // HTTP Server:
476   if(cl.exists("httpServer")) {
477     anna::comm::Network& network = anna::comm::Network::instantiate();
478     std::string address;
479     int port;
480     anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
481     //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
482     const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
483     a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
484   }
485
486   ///////////////////////////////
487   // Diameter library COUNTERS //
488   ///////////////////////////////
489   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
490   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
491   oamDiameterComm.enableCounters();
492   oamDiameterComm.enableAlarms();
493   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
494   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
495   oamDiameterCodec.enableCounters();
496   oamDiameterCodec.enableAlarms();
497   /////////////////
498   // COMM MODULE //
499   /////////////////
500   /* Main events */
501   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
502   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
503   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
504   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
505   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
506   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
507   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
508   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
509   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
510   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
511   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
512   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
513   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
514   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
515   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
516   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
517   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
518   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
519   /* Diameter Base (capabilities exchange & keep alive) */
520   // as client
521   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
522   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
523   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
524   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
525   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
526   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
527   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
528   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
529   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
530   // as server
531   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
532   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
533   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
534   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
535   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
536   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
537   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
538   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
539   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
540   /* server socket operations (enable/disable listening port for any local server) */
541   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
542   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
543   /* Connectivity */
544   // clients
545   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
546   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
547   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
548   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
549   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
550   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
551   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
552   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
553   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
554   // servers
555   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
556   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
557   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
558   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
559   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
560   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
561   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
562   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
563   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
564   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
565   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
566   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 58);
567   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 59);
568   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 60);
569   //////////////////
570   // CODEC MODULE //
571   //////////////////
572   /* Avp decoding */
573   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
574   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
575   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
576   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
577   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
578   /* Message decoding */
579   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
580   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
581   /* Avp validation */
582   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
583   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
584   /* Message validation */
585   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
586   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
587   /* Level validation */
588   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
589   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
590   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
591   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
592   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
593   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
594
595
596   /////////////////////////////////
597   // Counter recorder associated //
598   /////////////////////////////////
599   if(a_counterRecorderClock) {
600     oamDiameterComm.setCounterRecorder(a_counterRecorder);
601     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
602     anna::diameter::comm::ApplicationMessageOamModule::instantiate().setCounterRecorder(a_counterRecorder);
603     a_timeEngine->activate(a_counterRecorderClock); // start clock
604   }
605
606
607   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
608   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
609   if(cl.exists("integrationAndDebugging")) {
610     getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
611     getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
612   }
613
614   // Fix mode
615   if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
616     std::string fixMode = cl.getValue("fixMode");
617     anna::diameter::codec::Engine::FixMode::_v fm;
618     if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
619     else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
620     else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
621     else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
622     else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
623     getCodecEngine()->setFixMode(fm);
624   }
625
626   getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
627
628
629   // Log statistics concepts
630   if(cl.exists("logStatisticSamples")) {
631     std::string list = cl.getValue("logStatisticSamples");
632     anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
633
634     if(list == "all") {
635       if(statEngine.enableSampleLog(/* -1: all concepts */))
636         LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
637     } else {
638       anna::Tokenizer lst;
639       lst.apply(cl.getValue("logStatisticSamples"), ",");
640
641       if(lst.size() >= 1) {
642         anna::Tokenizer::const_iterator tok_min(lst.begin());
643         anna::Tokenizer::const_iterator tok_max(lst.end());
644         anna::Tokenizer::const_iterator tok_iter;
645         int conceptId;
646
647         for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
648           conceptId = atoi(anna::Tokenizer::data(tok_iter));
649
650           if(statEngine.enableSampleLog(conceptId))
651             LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
652         }
653       }
654     }
655   }
656
657
658   // Start client connections //////////////////////////////////////////////////////////////////////////////////
659   MyDiameterEntity *entity;
660   for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
661     entity = it->second->getEntity();
662     if (entity) entity->bind();
663   }
664
665   // Go into communicator poll
666   // Reconnection period (tcp reconnect retry time):
667   const char *varname = "reconnectionPeriod";
668   anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000;
669
670   a_communicator->setRecoveryTime(reconnectionPeriod);
671   if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket);  // HTTP
672   a_communicator->accept();
673 }
674
675 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
676   // Get hex string
677   static char buffer[8192];
678   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
679
680   if(infile.is_open()) {
681     infile >> buffer;
682     std::string hexString(buffer, strlen(buffer));
683     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
684     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
685     LOGDEBUG(
686       std::string msg = "Hex string (remove colons if exists): ";
687       msg += hexString;
688       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
689     );
690     anna::functions::fromHexString(hexString, db);
691     // Close file
692     infile.close();
693     return true;
694   }
695
696   return false;
697 }
698
699 void Launcher::resetStatistics() throw() {
700   getWorkingNode()->getMyDiameterEngine()->resetStatistics();
701 }
702
703 void Launcher::resetCounters() throw() {
704   anna::diameter::comm::OamModule::instantiate().resetCounters();
705   anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
706   anna::diameter::codec::OamModule::instantiate().resetCounters();
707 }
708
709 void Launcher::signalUSR2() throw(anna::RuntimeException) {
710   LOGNOTICE(
711     std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
712     msg += SIGUSR2_TASKS_INPUT_FILENAME;
713     msg += "' (results will be written at '";
714     msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
715     msg += "')";
716     anna::Logger::notice(msg, ANNA_FILE_LOCATION);
717   );
718   // Operation:
719   std::string line;
720   std::string response_content;
721   std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
722   std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
723
724   if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
725
726   if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
727
728   while(getline(in_file, line)) {
729     LOGDEBUG(
730       std::string msg = "Processing line: ";
731       msg += line;
732       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
733     );
734
735     try {
736       eventOperation(line, response_content);
737     } catch(RuntimeException &ex) {
738       ex.trace();
739     }
740
741     out_file << response_content;
742   }
743
744   in_file.close();
745   out_file.close();
746 }
747
748 std::string Launcher::help() const throw() {
749   std::string result = "\n";
750   result += "\n                     ------------- HELP -------------\n";
751   result += "\n";
752   result += "\nOVERVIEW";
753   result += "\n--------";
754   result += "\n";
755   result += "\nThe ADML (ANNA Diameter Multirealm Launcher) process is a multi-realm node with client and server";
756   result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server (i.e. to";
757   result += "\n simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.), and balancer";
758   result += "\n systems to provide failover to external round-robin launchers. Also, auxiliary encoder/decoder/loader";
759   result += "\n function could be deployed to reinterpret certain external flow and send it to another process.";
760   result += "\n ";
761   result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
762   result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
763   result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
764   result += "\n generation, expiration control and many more features.";
765   result += "\n";
766   result += "\nThe ADML process can easily configure a many realm nodes as needed, which will have own endpoints.";
767   result += "\nYou should avoid loop configurations (client and server for that client) because automatic forwarding,";
768   result += "\n is implemented and this would get in a never ending cycle when a request is sent.";
769   result += "\n";
770   result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
771   result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
772   result += "\n";
773   result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
774   result += "\n   kill -10 <pid>";
775   result += "\n    or";
776   result += "\n   kill -s SIGUSR1 <pid>";
777   result += "\n    and then";
778   result += "\n   vi /var/tmp/anna.context.<pid>";
779   result += "\n";
780   result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
781   result += "\n handlers, diameter stacks, etc.), and a powerful log module could dump all the events";
782   result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
783   result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
784   result += "\n measurements.";
785   result += "\n";
786   result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
787   result += "\n";
788   result += "\n";
789   result += "\nCOMMAND LINE";
790   result += "\n------------";
791   result += "\n";
792   result += "\nStart the launcher process without arguments in order to see all the startup configuration";
793   result += "\n posibilities, many of which could be modified on the air through the management interface";
794   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
795   result += "\n";
796   result += "\nAs mandatory, the stacks enabled given through the applicationId and the xml dictionary:";
797   result += "\n   --stacks <appid1,dictionary1#appid2,dictionary2#...#appidN,dictionaryN>";
798   result += "\n";
799   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
800   result += "\n   --diameterServer localhost:3868 --diameterServerSessions 10 --entityServerSessions 0";
801   result += "\n";
802   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
803   result += "\n   --entity 192.168.12.11:3868,192.168.12.21:3868 --entityServerSessions 10 --diameterServerSessions 0";
804   result += "\n";
805   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
806   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
807   result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
808   result += "\n arguments in order to define the balancing behaviour.";
809   result += "\n";
810   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
811   result += "\n customized ones using '--cer <xml message file>' and '--dwr <xml message file>'.";
812   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
813   result += "\n customized ones using operations interface.";
814   result += "\n";
815   result += "\n";
816   result += "\nDYNAMIC OPERATIONS";
817   result += "\n------------------";
818   result += "\n";
819   result += "\nADML supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
820   result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
821   result += "\n separated by pipes. These are the available commands:";
822   result += "\n";
823   result += "\n--------------------------------------------------------------------------------------- General purpose";
824   result += "\n";
825   result += "\nhelp                                 This help. Startup information-level traces also dump this help.";
826   result += "\n";
827   result += "\n---------------------------------------------------------------------------------------- Node selection";
828   result += "\n";
829   result += "\nnode[|<name>]                         Select current working node by mean the registered name.";
830   result += "\n                                      All the subsequent operations will be referred to this node.";
831   result += "\n                                      Without argument, the current node is dumped on stdout.";
832   result += "\n";
833   result += "\n------------------------------------------------------------------------------------ Parsing operations";
834   result += "\n";
835   result += "\ncode|<source_file>|<target_file>     Encodes source file (pathfile) into target file (pathfile).";
836   result += "\ndecode|<source_file>|<target_file>   Decodes source file (pathfile) into target file (pathfile).";
837   result += "\nloadxml|<source_file>                Reinterpret xml source file (pathfile).";
838   result += "\n";
839   result += "\n------------------------------------------------------------------------------------------- Hot changes";
840   result += "\n";
841   result += "\nservices[|source file]               Adds and starts the services specified in the xml file provided.";
842   result += "\n                                      (if missing, the file 'services.xml' will be used).";
843   result += "\n                                     The last loaded realm node will be automatically the new current";
844   result += "\n                                      working node. This is used to load new nodes once the ADML is";
845   result += "\n                                      started, regardless if '--services' command line parameter was";
846   result += "\n                                      used or not. Those services which are not correctly loaded, will";
847   result += "\n                                      be ignored, keeping the process alive.";
848   result += "\n";
849   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
850   result += "\n                                      server socket.";
851   result += "\ncontext[|target file]                Application context could also be written by mean this operation,";
852   result += "\n                                      and not only through SIGUSR1. If optional path file is missing,";
853   result += "\n                                      default '/var/tmp/anna.context.<pid>' will be used.";
854   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
855   result += "\n                                      performance measurement. Context data can be written at";
856   result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
857   result += "\n                                      or sending operation 'context|[target file]'.";
858   result += "\nforceCountersRecord                  Forces dump to file the current counters of the process.";
859   result += "\n";
860   result += "\n<visibility action>[|<address>:<port>][|socket id]";
861   result += "\n";
862   result += "\n       Actions: hide, show (update state) and hidden, shown (query state).";
863   result += "\n       Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
864   result += "\n       If missing server (first parameter) all applications sockets will be affected.";
865   result += "\n       If missing socket (second parameter) for specific server, all its sockets will be affected.";
866   result += "\n";
867   result += "\n       All application client sessions are shown on startup, but standard delivery only use primary";
868   result += "\n        server ones except if fails. Balance configuration use all the allowed sockets. You could also";
869   result += "\n        use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
870   result += "\n        client sessions, but for this, hide/show feature seems easier.";
871   result += "\n";
872   result += "\n--------------------------------------------------------------------------------------- Flow operations";
873   result += "\n";
874   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
875   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
876   result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
877   result += "\nanswerxml2e[|source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
878   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
879   result += "\n                           as many queues as different message codes have been programmed.";
880   result += "\nanswerxml2c[|source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
881   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
882   result += "\n                           as many queues as different message codes have been programmed.";
883   result += "\nanswerxml[|source_file]    Same as 'answerxml2c'.";
884   result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
885   result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
886   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
887   result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
888   result += "\nanswerxml(2e/2c)|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
889   result += "\nanswerxml(2e/2c)|rotate    Enable the corresponding queue rotation, useful in performance tests.";
890   result += "\n                           Rotation consists in add again to the queue, each element retrieved for answering.";
891   result += "\n";
892   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
893   result += "\nspecial scenarios (protocol errors):";
894   result += "\n";
895   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
896   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
897   result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
898   result += "\n";
899   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
900   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
901   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
902   result += "\n";
903   result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
904   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
905   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
906   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
907   result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
908   result += "\n";
909   result += "\nIn the most complete situation (process with both client and server side) there are internally";
910   result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
911   result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
912   result += "\n each one we could program different answers corresponding to different request codes received.";
913   result += "\n";
914   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
915   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
916   result += "\n    use sendxml/sendhex operations better than programming.";
917   result += "\n";
918   result += "\nBalance ('--balance' command line parameter) could be used to forward server socket receptions through";
919   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
920   result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
921   result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
922   result += "\n";
923   result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
924   result += "\n";
925   result += "\nUsed as log file extensions (when '--splitLog' is provided on command line) and context preffixes on log";
926   result += "\n details when unique log file is dumped:";
927   result += "\n";
928   result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
929   result += "\n   [sent2c/send2cError]   Send to client (success/error)";
930   result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
931   result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
932   result += "\n   [recvfc]               Reception from client";
933   result += "\n   [recvfe]               Reception from entity";
934   result += "\n   [req2c-expired]        A request sent to client has been expired";
935   result += "\n   [req2e-expired]        A request sent to entity has been expired";
936   result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
937   result += "\n                           has been logged)";
938   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
939   result += "\n                           has been logged)";
940   result += "\n   [retry]                Request retransmission";
941   result += "\n";
942   result += "\n-------------------------------------------------------------------------------------------- Load tests";
943   result += "\n";
944   result += "\nburst|<action>[|parameter]     Used for performance testing, we first program diameter requests";
945   result += "\n                                messages in order to launch them from client side to the configured";
946   result += "\n                                diameter entity. We could start the burst with an initial load";
947   result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
948   result += "\n                                per answer received or expired context. There are 10 actions: clear,";
949   result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
950   result += "\n";
951   result += "\n   burst|clear                 Clears all loaded burst messages.";
952   result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
953   result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
954   result += "\n                                a certain initial load.";
955   result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
956   result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
957   result += "\n                               Popping all OTA requests implies burst stop because no more answer";
958   result += "\n                                will arrive to the process. Burst output file (--burstLog command";
959   result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
960   result += "\n                                represents one received answer for which no new request is sent.";
961   result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
962   result += "\n   burst|repeat[|[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
963   result += "\n                                amount is greater than burst list size, they will be limited when";
964   result += "\n                                the list is processed except when repeat mode is enabled.";
965   result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
966   result += "\n                                operations is that burst won't be awaken. Externally we could control";
967   result += "\n                                sending time (no request will be sent for answers).";
968   result += "\n   burst|goto|<order>          Updates current burst pointer position.";
969   result += "\n   burst|look|<order>          Show programmed burst message for order provided.";
970   result += "\n";
971   result += "\n";
972   result += "\nUSING OPERATIONS INTERFACE";
973   result += "\n--------------------------";
974   result += "\n";
975   result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
976   result += "\n";
977   result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
978   result += "\n to define the http server at the command line with something like: '--httpServer localhost:9000'.";
979   result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
980   result += "\n using curl client could be:";
981   result += "\n";
982   result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
983   result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
984   result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
985   result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
986   result += "\n   etc.";
987   result += "\n";
988   result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
989   result += "\n";
990   result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
991   result += "\n signal event:";
992   result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
993   result += "\n    then";
994   result += "\n   kill -12 <pid>";
995   result += "\n    or";
996   result += "\n   kill -s SIGUSR2 <pid>";
997   result += "\n    and then see the results:";
998   result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
999   result += "\n";
1000   result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
1001   result += "\n case over the output file. Take into account that all the content of the task file will be executed";
1002   result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
1003   result += "\n interface.";
1004   result += "\n";
1005   result += "\n";
1006   return result;
1007 }
1008
1009 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1010   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1011   CommandLine& cl(anna::CommandLine::instantiate());
1012   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1013   response_content = "Operation processed with exception. See traces\n"; // supposed
1014   std::string result = "";
1015   anna::DataBlock db_aux(true);
1016
1017   ///////////////////////////////////////////////////////////////////
1018   // Simple operations without arguments:
1019
1020   // Help:
1021   if(operation == "help") {
1022     std::string s_help = help();
1023     std::cout << s_help << std::endl;
1024     LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1025     response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n";
1026     return;
1027   }
1028
1029   // Reset performance data:
1030   if(operation == "collect") {
1031     resetCounters();
1032     resetStatistics();
1033     response_content = "All process counters & statistic information have been reset\n";
1034     return;
1035   }
1036
1037   // Counters dump on demand:
1038   if(operation == "forceCountersRecord") {
1039     forceCountersRecord();
1040     response_content = "Current counters have been dump to disk\n";
1041     return;
1042   }
1043
1044   ///////////////////////////////////////////////////////////////////
1045   // Tokenize operation
1046   Tokenizer params;
1047   params.apply(operation, "|");
1048   int numParams = params.size() - 1;
1049
1050   // No operation has more than 2 arguments ...
1051   if(numParams > 2) {
1052     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1053     throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1054   }
1055
1056   // Get the operation type:
1057   Tokenizer::const_iterator tok_iter = params.begin();
1058   std::string opType = Tokenizer::data(tok_iter);
1059   // Check the number of parameters:
1060   bool wrongBody = false;
1061
1062   if((opType == "node") && (numParams > 1)) wrongBody = true;
1063
1064   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1065
1066   if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1067
1068   if((opType == "burst") && (numParams < 1)) wrongBody = true;
1069
1070   if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1071
1072   if(wrongBody) {
1073     // Launch exception
1074     std::string msg = "Wrong body content format on HTTP Request for '";
1075     msg += opType;
1076     msg += "' operation (missing parameter/s)";
1077     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1078   }
1079
1080   // All seems ok:
1081   std::string param1, param2;
1082
1083   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1084
1085   if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1086
1087   // Operations:
1088   if(opType == "context") {
1089     std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
1090     writeContext(contextFile);
1091     response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
1092     return;
1093   }
1094
1095   if(opType == "services") {
1096     std::string servicesFile = ((numParams == 1) ? param1 : "services.xml");
1097     try {
1098       loadServices(servicesFile, true /* bind entities */);
1099     }
1100     catch(anna::RuntimeException &ex) {
1101       ex.trace();
1102       response_content = anna::functions::asString("Loaded services from file '%s' with some problems (ignored ones)\n", servicesFile.c_str());
1103       return;
1104     }
1105     response_content = anna::functions::asString("Loaded services from file '%s'\n", servicesFile.c_str());
1106     return;
1107   }
1108
1109   // Realm switch:
1110   if(opType == "node") {
1111     if (param1 != "") {
1112       if (setWorkingNode(param1)) response_content = anna::functions::asString("Current node is now '%s'\n", param1.c_str());
1113     }
1114     else {
1115       std::cout << getWorkingNode()->asXMLString() << std::endl;
1116     }
1117     return;
1118   }
1119
1120   // Diameter endpoints:
1121   MyDiameterEntity *entity = getWorkingNode()->getEntity();
1122   MyDiameterEngine *commEngine = getWorkingNode()->getMyDiameterEngine();
1123   MyLocalServer *localServer = getWorkingNode()->getDiameterServer();
1124   anna::diameter::codec::Message codecMsg(getCodecEngine());
1125
1126
1127   if(opType == "code") {
1128     codecMsg.loadXML(param1);
1129     std::string hexString = anna::functions::asHexString(codecMsg.code());
1130     // write to outfile
1131     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1132     outfile.write(hexString.c_str(), hexString.size());
1133     outfile.close();
1134   } else if(opType == "decode") {
1135     // Get DataBlock from file with hex content:
1136     if(!getDataBlockFromHexFile(param1, db_aux))
1137       throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1138
1139     // Decode
1140     try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1141
1142     std::string xmlString = codecMsg.asXMLString();
1143     // write to outfile
1144     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1145     outfile.write(xmlString.c_str(), xmlString.size());
1146     outfile.close();
1147   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1148     if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1149
1150     if(param1 != "") {
1151       if(param2 != "") {
1152         std::string key = param1;
1153         key += "|";
1154         key += param2;
1155
1156         if(opType == "hide") commEngine->findClientSession(key)->hide();
1157
1158         if(opType == "show") commEngine->findClientSession(key)->show();
1159
1160         if(opType == "hidden") result = commEngine->findClientSession(key)->hidden() ? "true" : "false";
1161
1162         if(opType == "shown") result = commEngine->findClientSession(key)->shown() ? "true" : "false";
1163       } else {
1164         std::string address;
1165         int port;
1166         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1167
1168         if(opType == "hide") commEngine->findServer(address, port)->hide();
1169
1170         if(opType == "show") commEngine->findServer(address, port)->show();
1171
1172         if(opType == "hidden") result = commEngine->findServer(address, port)->hidden() ? "true" : "false";
1173
1174         if(opType == "shown") result = commEngine->findServer(address, port)->shown() ? "true" : "false";
1175       }
1176     } else {
1177       if(opType == "hide") entity->hide();
1178
1179       if(opType == "show") entity->show();
1180
1181       if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1182
1183       if(opType == "shown") result = entity->shown() ? "true" : "false";
1184     }
1185   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1186     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1187     anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
1188
1189     if((opType == "sendxml") || (opType == "sendxml2e")) {
1190       codecMsg.loadXML(param1);
1191       msg->clearBody();
1192       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)
1193
1194       msg->setBody(codecMsg.code());
1195     } else {
1196       // Get DataBlock from file with hex content:
1197       if(!getDataBlockFromHexFile(param1, db_aux))
1198         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1199
1200       msg->setBody(db_aux);
1201     }
1202
1203     bool success = entity->send(msg, cl.exists("balance"));
1204     getWorkingNode()->releaseCommMessage(msg);
1205
1206     // Detailed log:
1207     if(getWorkingNode()->logEnabled()) {
1208       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1209       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1210       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1211       getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
1212     }
1213   } else if((opType == "burst")) {
1214     if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1215
1216     // burst|clear                     clears all loaded burst messages.
1217     // burst|load|<source_file>        loads the next diameter message into launcher burst.
1218     // burst|start|<initial load>      starts the message sending with a certain initial load.
1219     // burst|push|<load amount>        sends specific non-aynchronous load.
1220     // burst|stop                      stops the burst cycle.
1221     // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1222     // burst|send|<amount>             send messages from burst list. The main difference with
1223     //                                 start/push operations is that burst won't be awaken.
1224     //                                 Externally we could control sending time (no request
1225     //                                 will be sent for answers).
1226     // burst|goto|<order>              Updates current burst pointer position.
1227     // burst|look|<order>              Show programmed burst message for order provided.
1228
1229     if(param1 == "clear") {
1230       result = "Removed ";
1231       result += anna::functions::asString(getWorkingNode()->clearBurst());
1232       result += " elements.";
1233     } else if(param1 == "load") {
1234       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1235
1236       codecMsg.loadXML(param2);
1237
1238       if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1239       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)
1240
1241       int position = getWorkingNode()->loadBurstMessage(codecMsg.code());
1242       result = "Loaded '";
1243       result += param2;
1244       result += "' file into burst list position ";
1245       result += anna::functions::asString(position);
1246     } else if(param1 == "start") {
1247       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1248
1249       int initialLoad = atoi(param2.c_str());
1250       int processed = getWorkingNode()->startBurst(initialLoad);
1251
1252       if(processed > 0) {
1253         result = "Initial load completed for ";
1254         result += anna::functions::entriesAsString(processed, "message");
1255         result += ".";
1256       }
1257     } else if(param1 == "push") {
1258       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1259
1260       int pushed = getWorkingNode()->pushBurst(atoi(param2.c_str()));
1261
1262       if(pushed > 0) {
1263         result = "Pushed ";
1264         result += anna::functions::entriesAsString(pushed, "message");
1265         result += ".";
1266       }
1267     } else if(param1 == "pop") {
1268       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1269
1270       int releaseLoad = atoi(param2.c_str());
1271       int popped = getWorkingNode()->popBurst(releaseLoad);
1272
1273       if(popped > 0) {
1274         result = "Burst popped for ";
1275         result += anna::functions::entriesAsString(popped, "message");
1276         result += ".";
1277       }
1278     } else if(param1 == "stop") {
1279       int left = getWorkingNode()->stopBurst();
1280
1281       if(left != -1) {
1282         result += anna::functions::entriesAsString(left, "message");
1283         result += " left to the end of the cycle.";
1284       }
1285     } else if(param1 == "repeat") {
1286       if(param2 == "") param2 = "yes";
1287
1288       bool repeat = (param2 == "yes");
1289       getWorkingNode()->repeatBurst(repeat);
1290       result += (repeat ? "Mode on." : "Mode off.");
1291     } else if(param1 == "send") {
1292       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1293
1294       int sent = getWorkingNode()->sendBurst(atoi(param2.c_str()));
1295
1296       if(sent > 0) {
1297         result = "Sent ";
1298         result += anna::functions::entriesAsString(sent, "message");
1299         result += ".";
1300       }
1301     } else if(param1 == "goto") {
1302       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1303
1304       result = getWorkingNode()->gotoBurst(atoi(param2.c_str()));
1305       result += ".";
1306     } else if(param1 == "look") {
1307       if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1308
1309       result = "\n\n";
1310       result += getWorkingNode()->lookBurst(atoi(param2.c_str()));
1311       result += "\n\n";
1312     } else {
1313       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1314     }
1315   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1316     if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1317     anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
1318
1319     if(opType == "sendxml2c") {
1320       codecMsg.loadXML(param1);
1321       msg->clearBody();
1322       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)
1323
1324       msg->setBody(codecMsg.code());
1325     } else {
1326       // Get DataBlock from file with hex content:
1327       if(!getDataBlockFromHexFile(param1, db_aux))
1328         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1329
1330       msg->setBody(db_aux);
1331     }
1332
1333     bool success = localServer->send(msg);
1334     getWorkingNode()->releaseCommMessage(msg);
1335
1336     // Detailed log:
1337     if(getWorkingNode()->logEnabled()) {
1338       anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1339       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1340       getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
1341     }
1342   } else if(opType == "loadxml") {
1343     codecMsg.loadXML(param1);
1344     std::string xmlString = codecMsg.asXMLString();
1345     std::cout << xmlString << std::endl;
1346   } else if(opType == "diameterServerSessions") {
1347     int diameterServerSessions = atoi(param1.c_str());
1348
1349     if(localServer)
1350       localServer->setMaxConnections(diameterServerSessions);
1351     else
1352       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));
1353
1354   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1355     if(!localServer)
1356       throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1357
1358     if(param1 == "") { // programmed answers FIFO's to stdout
1359       std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl;
1360       response_content = "Programmed answers dumped on stdout\n";
1361       return;
1362     } else if (param1 == "rotate") {
1363       localServer->getReactingAnswers()->rotate(true);
1364     } else if (param1 == "exhaust") {
1365       localServer->getReactingAnswers()->rotate(false);
1366     } else if (param1 == "clear") {
1367       localServer->getReactingAnswers()->clear();
1368     } else if (param1 == "dump") {
1369       localServer->getReactingAnswers()->dump();
1370     } else {
1371       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1372       LOGDEBUG
1373       (
1374         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1375       );
1376
1377       if(message->isRequest())
1378         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1379
1380       int code = message->getId().first;
1381       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1382       localServer->getReactingAnswers()->addMessage(code, message);
1383     }
1384   } else if(opType == "answerxml2e") {
1385     if(!entity)
1386       throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1387
1388     if(param1 == "") { // programmed answers FIFO's to stdout
1389       std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl;
1390       response_content = "Programmed answers dumped on stdout\n";
1391       return;
1392     } else if (param1 == "rotate") {
1393       entity->getReactingAnswers()->rotate(true);
1394     } else if (param1 == "exhaust") {
1395       entity->getReactingAnswers()->rotate(false);
1396     } else if (param1 == "clear") {
1397       entity->getReactingAnswers()->clear();
1398     } else if (param1 == "dump") {
1399       entity->getReactingAnswers()->dump();
1400     } else {
1401       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1402       LOGDEBUG
1403       (
1404         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1405       );
1406
1407       if(message->isRequest())
1408         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1409
1410       int code = message->getId().first;
1411       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1412       entity->getReactingAnswers()->addMessage(code, message);
1413     }
1414   } else {
1415     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1416     throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
1417   }
1418
1419   // HTTP response
1420   response_content = "Operation processed; ";
1421
1422   if((opType == "decode") || (opType == "code")) {
1423     response_content += "File '";
1424     response_content += param2;
1425     response_content += "' created.";
1426     response_content += "\n";
1427   } else if((opType == "hide") || (opType == "show")) {
1428     response_content += "Resource '";
1429     response_content += ((param1 != "") ? param1 : "Entity");
1430
1431     if(param2 != "") {
1432       response_content += "|";
1433       response_content += param2;
1434     }
1435
1436     response_content += "' ";
1437
1438     if(opType == "hide") response_content += "has been hidden.";
1439
1440     if(opType == "show") response_content += "has been shown.";
1441
1442     response_content += "\n";
1443   } else if((opType == "hidden") || (opType == "shown")) {
1444     response_content += "Result: ";
1445     response_content += result;
1446     response_content += "\n";
1447   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1448     response_content += "Message '";
1449     response_content += param1;
1450     response_content += "' sent to entity.";
1451     response_content += "\n";
1452   } else if(opType == "burst") {
1453     response_content += "Burst '";
1454     response_content += param1;
1455     response_content += "' executed. ";
1456     response_content += result;
1457     response_content += "\n";
1458   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1459     response_content += "Message '";
1460     response_content += param1;
1461     response_content += "' sent to client.";
1462     response_content += "\n";
1463   } else if(opType == "loadxml") {
1464     response_content += "Message '";
1465     response_content += param1;
1466     response_content += "' loaded.";
1467     response_content += "\n";
1468   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1469     response_content += "'";
1470     response_content += param1;
1471     response_content += "' applied on server FIFO queue";
1472     response_content += "\n";
1473   } else if(opType == "answerxml2e") {
1474     response_content += "'";
1475     response_content += param1;
1476     response_content += "' applied on client FIFO queue";
1477     response_content += "\n";
1478   } else if(opType == "diameterServerSessions") {
1479     response_content += "Maximum server socket connections updated to '";
1480     response_content += param1;
1481     response_content += "'.";
1482     response_content += "\n";
1483   }
1484 }
1485
1486 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
1487 throw() {
1488   anna::xml::Node* result = parent->createChild("launcher");
1489   anna::comm::Application::asXML(result);
1490   // Timming:
1491   result->createAttribute("StartTime", a_start_time.asString());
1492   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
1493   // Diameter:
1494   getCodecEngine()->asXML(result);
1495   for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
1496     it->second->asXML(result);
1497   }
1498
1499   // OAM:
1500   anna::diameter::comm::OamModule::instantiate().asXML(result);
1501   anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
1502   anna::diameter::codec::OamModule::instantiate().asXML(result);
1503   // Statistics:
1504   anna::statistics::Engine::instantiate().asXML(result);
1505   return result;
1506 }