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