New feature to allow to register components with different names for same class:...
[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 // Project
10 #include <anna/statistics/Engine.hpp>
11 #include <anna/diameter/codec/Engine.hpp>
12 #include <anna/http/Transport.hpp>
13 #include <anna/diameter/stack/Engine.hpp>
14 #include <anna/diameter/helpers/base/functions.hpp>
15 #include <anna/diameter/helpers/dcca/functions.hpp>
16 #include <anna/time/functions.hpp>
17 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
18
19 // Process
20 #include "Launcher.hpp"
21
22
23 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
24 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
25 #define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine"
26
27 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
28   a_myDiameterEngine = new MyDiameterEngine();
29   a_myDiameterEngine->setRealm("ADL.ericsson.com");
30   a_myDiameterEngine->setAutoBind(false);  // allow to create client-sessions without binding them, in order to set timeouts.
31   a_logFile = "launcher.log";
32   a_burstLogFile = "launcher.burst";
33   a_splitLog = false;
34   a_detailedLog = false;
35   a_dumpLog = false;
36   a_timeEngine = NULL;
37   a_counterRecorder = NULL;
38   a_counterRecorderClock = NULL;
39   a_entity = NULL;
40   a_diameterLocalServer = NULL;
41   a_cerPathfile = "cer.xml";
42   a_dwrPathfile = "dwr.xml";
43   // Burst
44   a_burstCycle = 1;
45   a_burstRepeat = false;
46   a_burstActive = false;
47   a_burstLoadIndx = 0;
48   a_burstDeliveryIt = a_burstMessages.begin();
49   a_otaRequest = 0;
50   a_burstPopCounter = 0;
51 }
52
53 anna::diameter::comm::Message *Launcher::createCommMessage() throw(anna::RuntimeException) {
54   return a_commMessages.create();
55 }
56
57 void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
58   a_commMessages.release(msg);
59 }
60
61 anna::diameter::codec::Message *Launcher::createCodecMessage() throw(anna::RuntimeException) {
62   return a_codecMessages.create();
63 }
64
65 void Launcher::releaseCodecMessage(anna::diameter::codec::Message *msg) throw() {
66   a_codecMessages.release(msg);
67 }
68
69
70 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
71   // Build CER
72   //   <CER> ::= < Diameter Header: 257, REQ >
73   //             { Origin-Host } 264 diameterIdentity
74   //             { Origin-Realm } 296 idem
75   //          1* { Host-IP-Address } 257, address
76   //             { Vendor-Id } 266 Unsigned32
77   //             { Product-Name } 269 UTF8String
78   //             [Origin-State-Id] 278 Unsigned32
79   //           * [ Supported-Vendor-Id ]  265 Unsigned32
80   //           * [ Auth-Application-Id ] 258 Unsigned32
81   //           * [Acct-Application-Id]  259 Unsigned32
82   anna::diameter::codec::Message diameterCER;
83   int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
84   std::string OH = a_myDiameterEngine->getHost();
85   std::string OR = a_myDiameterEngine->getRealm();
86   std::string hostIP = anna::functions::getHostnameIP(); // Address
87   int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
88   std::string productName = "ANNA Diameter Launcher"; // UTF8String
89   bool loadingError = false;
90
91   try {
92     diameterCER.loadXML(a_cerPathfile);
93   } catch(anna::RuntimeException &ex) {
94     //ex.trace();
95     loadingError = true;
96   }
97
98   if(loadingError) {
99     LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
100     diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
101     diameterCER.setApplicationId(applicationId);
102     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
103     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
104     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
105     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
106     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
107     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
108   }
109
110   // Build DWR
111   //   <DWR>  ::= < Diameter Header: 280, REQ >
112   //              { Origin-Host }
113   //              { Origin-Realm }
114   anna::diameter::codec::Message diameterDWR;
115   loadingError = false;
116
117   try {
118     diameterDWR.loadXML(a_dwrPathfile);
119   } catch(anna::RuntimeException &ex) {
120     //ex.trace();
121     loadingError = true;
122   }
123
124   if(loadingError) {
125     LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
126     diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
127     diameterDWR.setApplicationId(applicationId);
128     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
129     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
130   }
131
132 //////////////////////////
133 // IDEM FOR CEA AND DWA //
134 //////////////////////////
135 //            // Build CER
136 //            //   <CER> ::= < Diameter Header: 257, REQ >
137 //            //             { Origin-Host } 264 diameterIdentity
138 //            //             { Origin-Realm } 296 idem
139 //            //          1* { Host-IP-Address } 257, address
140 //            //             { Vendor-Id } 266 Unsigned32
141 //            //             { Product-Name } 269 UTF8String
142 //            //             [Origin-State-Id] 278 Unsigned32
143 //            //           * [ Supported-Vendor-Id ]  265 Unsigned32
144 //            //           * [ Auth-Application-Id ] 258 Unsigned32
145 //            //           * [Acct-Application-Id]  259 Unsigned32
146 //            anna::diameter::codec::Message diameterCER;
147 //            int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
148 //            std::string OH = a_myDiameterEngine->getHost();
149 //            std::string OR = a_myDiameterEngine->getRealm();
150 //            std::string hostIP = anna::functions::getHostnameIP(); // Address
151 //            int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
152 //            std::string productName = "ANNA Diameter Launcher"; // UTF8String
153 //            bool loadingError = false;
154 //
155 //            try {
156 //               diameterCER.loadXML("cer.xml");
157 //            } catch (anna::RuntimeException &ex) {
158 //               ex.trace();
159 //               loadingError = true;
160 //            }
161 //
162 //            if (loadingError) {
163 //               LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
164 //               diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
165 //               diameterCER.setApplicationId(applicationId);
166 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
167 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
168 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
169 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
170 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
171 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
172 //            }
173 //
174 //            // Build DWR
175 //            //   <DWR>  ::= < Diameter Header: 280, REQ >
176 //            //              { Origin-Host }
177 //            //              { Origin-Realm }
178 //            anna::diameter::codec::Message diameterDWR;
179 //            loadingError = false;
180 //
181 //            try {
182 //               diameterDWR.loadXML("dwr.xml");
183 //            } catch (anna::RuntimeException &ex) {
184 //               ex.trace();
185 //               loadingError = true;
186 //            }
187 //
188 //            if (loadingError) {
189 //               LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
190 //               diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
191 //               diameterDWR.setApplicationId(applicationId);
192 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
193 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
194 //            }
195   // Assignment for CER/DWR and CEA/DWA:
196   a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
197   //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
198 }
199
200 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
201 //   if (!logEnabled()) return;
202   anna::diameter::codec::Message codecMsg;
203   try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
204   writeLogFile(codecMsg, logExtension, detail);
205
206 }
207
208 // Si ya lo tengo decodificado:
209 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
210 //   if (!logEnabled()) return;
211   // Open target file:
212   std::string targetFile = a_logFile;
213
214   if(a_splitLog) {
215     targetFile += ".";
216     targetFile += logExtension;
217   }
218
219   std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app);
220   // Set text to dump:
221   std::string title = "[";
222   title += logExtension;
223   title += "]";
224   // Build complete log:
225   std::string log = "\n";
226   std::string xml = decodedMessage.asXMLString();
227
228
229   if(a_detailedLog) {
230     anna::time::Date now;
231     now.setNow();
232     title += " ";
233     title += now.asString();
234     log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
235     log += xml;
236     log += "\n";
237     log += anna::functions::highlight("Used resource");
238     log += detail;
239     log += "\n";
240   } else {
241     log += title;
242     log += "\n";
243     log += xml;
244     log += "\n";
245   }
246
247   if(a_dumpLog) {
248     std::string name = anna::functions::asString(decodedMessage.getHopByHop());
249     name += ".";
250     name += anna::functions::asString(decodedMessage.getEndToEnd());
251     name += ".";
252     name += anna::functions::asString(decodedMessage.getId().first);
253     name += ".";
254     name += ((decodedMessage.getId().second) ? "request.":"answer.");
255     name += logExtension;
256     name += ".xml";
257     std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app);
258     outMsg.write(xml.c_str(), xml.size());
259     outMsg.close();
260   }
261
262   // Write and close
263   out.write(log.c_str(), log.size());
264   out.close();
265 }
266
267 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
268   std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app);
269   out.write(buffer.c_str(), buffer.size());
270   out.close();    // close() will be called when the object is destructed (i.e., when it goes out of scope).
271   // you'd call close() only if you indeed for some reason wanted to close the filestream
272   // earlier than it goes out of scope.
273 }
274
275 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
276   CommandLine& cl(anna::CommandLine::instantiate());
277
278   if(!cl.exists(commandLineParameter) && optional) return;  // start error if mandatory
279
280   std::string parameter = cl.getValue(commandLineParameter);
281
282   if(anna::functions::isLike("^[0-9]+$", parameter)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
283     int msecs = cl.getIntegerValue(commandLineParameter);
284
285     if(msecs > a_timeEngine->getMaxTimeout()) {
286       std::string msg = "Commandline parameter '";
287       msg += commandLineParameter;
288       msg += "' is greater than allowed max timeout for timming engine: ";
289       msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
290       throw RuntimeException(msg, ANNA_FILE_LOCATION);
291     }
292
293     if(msecs <= a_timeEngine->getResolution()) {
294       std::string msg = "Commandline parameter '";
295       msg += commandLineParameter;
296       msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
297       msg += anna::functions::asString(a_timeEngine->getResolution());
298       throw RuntimeException(msg, ANNA_FILE_LOCATION);
299     }
300
301     return; // ok
302   }
303
304   // Excepcion (por no ser entero):
305   std::string msg = "Error at commandline parameter '";
306   msg += commandLineParameter;
307   msg += "' = '";
308   msg += parameter;
309   msg += "': must be a non-negative integer number";
310   throw RuntimeException(msg, ANNA_FILE_LOCATION);
311 }
312
313 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
314   if(diameterServerSessions <= 0) return;
315
316   std::string address;
317   int port;
318   CommandLine& cl(anna::CommandLine::instantiate());
319   anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
320   //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
321   a_diameterLocalServer = (MyLocalServer*)(a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions));
322   a_diameterLocalServer->setDescription("Launcher diameter local server");
323   a_diameterLocalServer->setProgrammedAnswersCodecEngine(getCodecEngine());
324   int allowedInactivityTime = 90000; // ms
325
326   if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
327
328   a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
329 }
330
331 void Launcher::initialize()
332 throw(anna::RuntimeException) {
333   anna::comm::Application::initialize();
334   CommandLine& cl(anna::CommandLine::instantiate());
335   anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
336 //   if (cl.exists ("clone"))
337 //      workMode = anna::comm::Communicator::WorkMode::Clone;
338   a_communicator = new MyCommunicator(workMode);
339   a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
340   // Counters record procedure:
341   anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
342
343   if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
344
345   if(cntRecordPeriod != 0) {
346     checkTimeMeasure("cntRecordPeriod");
347     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
348     std::string cntDir = ".";
349
350     if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
351
352     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
353   }
354 }
355
356 void Launcher::run()
357 throw(anna::RuntimeException) {
358   LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
359   CommandLine& cl(anna::CommandLine::instantiate());
360   // Start time:
361   a_start_time.setNow();
362   // Statistics:
363   anna::statistics::Engine::instantiate().enable();
364
365   // Checking command line parameters
366   if(cl.exists("sessionBasedModelsClientSocketSelection")) {
367     std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
368
369     if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
370       throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
371     }
372   }
373
374   // Tracing:
375   if(cl.exists("trace"))
376     anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
377
378   LOGINFORMATION(
379     // Help on startup traces:
380     anna::Logger::information(help(), ANNA_FILE_LOCATION);
381     // Test messages dtd:
382     std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
383     msg += anna::diameter::codec::MessageDTD;
384     anna::Logger::information(msg, ANNA_FILE_LOCATION);
385   );
386
387   // HTTP Server:
388   if(cl.exists("httpServer")) {
389     anna::comm::Network& network = anna::comm::Network::instantiate();
390     std::string address;
391     int port;
392     anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
393     //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
394     const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
395     a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
396   }
397
398   // Stack:
399   a_codecEngine = new anna::diameter::codec::Engine(DIAMETER_CODEC_ENGINE_NAME_PREFIX);
400   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
401   anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
402   // Analyze comma-separated list:
403   anna::Tokenizer lst;
404   std::string dictionaryParameter = cl.getValue("dictionary");
405   lst.apply(dictionaryParameter, ",");
406
407   if(lst.size() >= 1) {  // always true (at least one, because -dictionary is mandatory)
408     anna::Tokenizer::const_iterator tok_min(lst.begin());
409     anna::Tokenizer::const_iterator tok_max(lst.end());
410     anna::Tokenizer::const_iterator tok_iter;
411     std::string pathFile;
412     d->allowUpdates();
413
414     for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
415       pathFile = anna::Tokenizer::data(tok_iter);
416       d->load(pathFile);
417     }
418   }
419
420   getCodecEngine()->setDictionary(d);
421   LOGDEBUG(anna::Logger::debug(getCodecEngine()->asString(), ANNA_FILE_LOCATION));
422
423   if(lst.size() > 1) {
424     std::string all_in_one = "./dictionary-all-in-one.xml";
425     std::ofstream out(all_in_one.c_str(), std::ifstream::out);
426     std::string buffer = d->asXMLString();
427     out.write(buffer.c_str(), buffer.size());
428     out.close();
429     std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
430   }
431
432   ///////////////////////////////
433   // Diameter library COUNTERS //
434   ///////////////////////////////
435   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
436   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
437   oamDiameterComm.enableCounters();
438   oamDiameterComm.enableAlarms();
439   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
440   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
441   oamDiameterCodec.enableCounters();
442   oamDiameterCodec.enableAlarms();
443   /////////////////
444   // COMM MODULE //
445   /////////////////
446   /* Main events */
447   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
448   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
449   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
450   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
451   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
452   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
453   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
454   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
455   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
456   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
457   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
458   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
459   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
460   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
461   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
462   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
463   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
464   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
465   /* Diameter Base (capabilities exchange & keep alive) */
466   // as client
467   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
468   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
469   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
470   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
471   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
472   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
473   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
474   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
475   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
476   // as server
477   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
478   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
479   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
480   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
481   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
482   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
483   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
484   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
485   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
486   /* server socket operations (enable/disable listening port for any local server) */
487   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
488   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
489   /* Connectivity */
490   // clients
491   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
492   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
493   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
494   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
495   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
496   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
497   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
498   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
499   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
500   // servers
501   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
502   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
503   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
504   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
505   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
506   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
507   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
508   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
509   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
510   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
511   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
512   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 58);
513   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 59);
514   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 60);
515   //////////////////
516   // CODEC MODULE //
517   //////////////////
518   /* Avp decoding */
519   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
520   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
521   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
522   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
523   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
524   /* Message decoding */
525   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
526   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
527   /* Avp validation */
528   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
529   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
530   /* Message validation */
531   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
532   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
533   /* Level validation */
534   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
535   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
536   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
537   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
538   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
539   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
540   ///////////////////////////////////////////
541   // APPLICATION MESSAGE OAM MODULE SCOPES //
542   ///////////////////////////////////////////
543   // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
544   anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
545   int scope_id = 3;
546   for (anna::diameter::stack::Engine::const_stack_iterator it = stackEngine.stack_begin(); it != stackEngine.stack_end(); it++) {
547     appMsgOamModule.createStackCounterScope(scope_id, it->first);
548     scope_id++;
549   }
550   appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
551
552
553   /////////////////////////////////
554   // Counter recorder associated //
555   /////////////////////////////////
556   if(a_counterRecorderClock) {
557     oamDiameterComm.setCounterRecorder(a_counterRecorder);
558     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
559     appMsgOamModule.setCounterRecorder(a_counterRecorder);
560     a_timeEngine->activate(a_counterRecorderClock); // start clock
561   }
562
563
564   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
565   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
566   if(cl.exists("integrationAndDebugging")) {
567     getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
568     getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
569   }
570
571   // Fix mode
572   if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
573     std::string fixMode = cl.getValue("fixMode");
574     anna::diameter::codec::Engine::FixMode::_v fm;
575     if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
576     else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
577     else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
578     else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
579     else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
580     getCodecEngine()->setFixMode(fm);
581   }
582
583   getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
584
585   // Diameter Server:
586   if(cl.exists("diameterServer"))
587     startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
588
589   // Optional command line parameters ////////////////////////////////////////////////////////
590   checkTimeMeasure("allowedInactivityTime");
591   checkTimeMeasure("tcpConnectDelay");
592   checkTimeMeasure("answersTimeout");
593   checkTimeMeasure("ceaTimeout");
594   checkTimeMeasure("watchdogPeriod");
595   checkTimeMeasure("reconnectionPeriod");
596   int tcpConnectDelay = 200; // ms
597   anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
598   anna::Millisecond ceaTimeout;
599   anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
600   int reconnectionPeriod = 10000; // ms
601
602   if(cl.exists("tcpConnectDelay"))         tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
603
604   if(cl.exists("answersTimeout"))          answersTimeout = cl.getIntegerValue("answersTimeout");
605
606   if(cl.exists("ceaTimeout"))              ceaTimeout = cl.getIntegerValue("ceaTimeout");
607   else                                      ceaTimeout = answersTimeout;
608
609   if(cl.exists("watchdogPeriod"))          watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
610
611   if(cl.exists("reconnectionPeriod"))      reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
612
613   a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
614   a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
615   std::string originHost = "";
616   std::string originRealm = "";
617
618   if(cl.exists("cer"))                  a_cerPathfile = cl.getValue("cer");
619
620   if(cl.exists("dwr"))                  a_dwrPathfile = cl.getValue("dwr");
621
622   if(cl.exists("originHost"))           originHost = cl.getValue("originHost");
623
624   if(cl.exists("originRealm"))          originRealm = cl.getValue("originRealm");
625
626   a_myDiameterEngine->setHost(originHost);
627   a_myDiameterEngine->setRealm(originRealm);
628
629   // Diameter entity:
630   if(cl.exists("entity")) {
631     int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
632
633     if(entityServerSessions > 0) {
634       baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
635       anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
636       a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
637       a_entity = (MyDiameterEntity*)(a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"));
638       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
639       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
640       a_entity->setProgrammedAnswersCodecEngine(getCodecEngine());
641       a_entity->bind();
642     }
643   }
644
645   // Logs
646   if(cl.exists("log")) a_logFile = cl.getValue("log");
647
648   if(cl.exists("splitLog")) a_splitLog = true;
649
650   if(cl.exists("detailedLog")) a_detailedLog = true;
651
652   if(cl.exists("dumpLog")) a_dumpLog = true;
653
654   if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
655
656   // Log statistics concepts
657   if(cl.exists("logStatisticSamples")) {
658     std::string list = cl.getValue("logStatisticSamples");
659     anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
660
661     if(list == "all") {
662       if(statEngine.enableSampleLog(/* -1: all concepts */))
663         LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
664     } else {
665       anna::Tokenizer lst;
666       lst.apply(cl.getValue("logStatisticSamples"), ",");
667
668       if(lst.size() >= 1) {
669         anna::Tokenizer::const_iterator tok_min(lst.begin());
670         anna::Tokenizer::const_iterator tok_max(lst.end());
671         anna::Tokenizer::const_iterator tok_iter;
672         int conceptId;
673
674         for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
675           conceptId = atoi(anna::Tokenizer::data(tok_iter));
676
677           if(statEngine.enableSampleLog(conceptId))
678             LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
679         }
680       }
681     }
682   }
683
684   a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
685
686   if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket);  // HTTP
687
688   a_communicator->accept();
689 }
690
691 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
692   // Get hex string
693   static char buffer[8192];
694   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
695
696   if(infile.is_open()) {
697     infile >> buffer;
698     std::string hexString(buffer, strlen(buffer));
699     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
700     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
701     LOGDEBUG(
702       std::string msg = "Hex string (remove colons if exists): ";
703       msg += hexString;
704       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
705     );
706     anna::functions::fromHexString(hexString, db);
707     // Close file
708     infile.close();
709     return true;
710   }
711
712   return false;
713 }
714
715 int Launcher::clearBurst() throw() {
716   int size = a_burstMessages.size();
717
718   if(size) {
719     std::map<int, anna::diameter::comm::Message*>::const_iterator it;
720     std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
721     std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
722
723     for(it = it_min; it != it_max; it++) releaseCommMessage((*it).second);
724
725     a_burstMessages.clear();
726   } else {
727     std::string msg = "Burst list already empty. Nothing done";
728     std::cout << msg << std::endl;
729     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
730   }
731
732   a_burstActive = false;
733   a_burstLoadIndx = 0;
734   a_burstDeliveryIt = a_burstMessages.begin();
735   return size;
736 }
737
738 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
739   anna::diameter::comm::Message *msg = createCommMessage();
740   msg->setBody(db);
741   a_burstMessages[a_burstLoadIndx++] = msg;
742   return (a_burstLoadIndx - 1);
743 }
744
745 int Launcher::stopBurst() throw() {
746   if(!a_burstActive) {
747     std::string msg = "Burst launch is already stopped. Nothing done";
748     std::cout << msg << std::endl;
749     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
750     return -1;
751   }
752
753   a_burstActive = false;
754   // Remaining on cycle:
755   return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
756 }
757
758 int Launcher::popBurst(int releaseAmount) throw() {
759   if(!a_burstActive) {
760     std::string msg = "Burst launch is stopped. Nothing done";
761     std::cout << msg << std::endl;
762     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
763     return -1;
764   }
765
766   if(releaseAmount < 1) {
767     std::string msg = "No valid release amount is specified. Ignoring burst pop";
768     std::cout << msg << std::endl;
769     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
770     return -2;
771   }
772
773   int currentOTArequests = a_entity->getOTARequests();
774   a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
775   return a_burstPopCounter;
776 }
777
778 int Launcher::pushBurst(int loadAmount) throw() {
779   if(a_burstMessages.size() == 0) {
780     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
781     std::cout << msg << std::endl;
782     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
783     return -1;
784   }
785
786   if(loadAmount < 1) {
787     std::string msg = "No valid load amount is specified. Ignoring burst push";
788     std::cout << msg << std::endl;
789     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
790     return -2;
791   }
792
793   a_burstActive = true;
794   int count;
795
796   for(count = 0; count < loadAmount; count++)
797     if(!sendBurstMessage()) break;
798
799   return count;
800 }
801
802 int Launcher::sendBurst(int loadAmount) throw() {
803   if(a_burstMessages.size() == 0) {
804     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
805     std::cout << msg << std::endl;
806     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
807     return -1;
808   }
809
810   if(loadAmount < 1) {
811     std::string msg = "No valid load amount is specified. Ignoring burst send";
812     std::cout << msg << std::endl;
813     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
814     return -2;
815   }
816
817   int count;
818
819   for(count = 0; count < loadAmount; count++)
820     if(!sendBurstMessage(true /* anyway */)) break;
821
822   return count;
823 }
824
825 int Launcher::startBurst(int initialLoad) throw() {
826   if(initialLoad < 1) {
827     std::string msg = "No initial load is specified. Ignoring burst start";
828     std::cout << msg << std::endl;
829     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
830     return -2;
831   }
832
833   a_burstActive = true;
834   a_burstCycle = 1;
835   a_burstDeliveryIt = a_burstMessages.begin();
836   return (pushBurst(initialLoad));
837 }
838
839 bool Launcher::sendBurstMessage(bool anyway) throw() {
840   if(!anyway && !burstActive()) return false;
841
842   if(a_burstPopCounter > 0) {
843     if(burstLogEnabled()) writeBurstLogFile("x");
844
845     a_burstPopCounter--;
846     return false;
847   }
848
849   if(a_burstDeliveryIt == a_burstMessages.end()) {
850     a_burstDeliveryIt = a_burstMessages.begin();
851
852     if(!anyway) {
853       if(a_burstRepeat) {
854         a_burstCycle++;
855
856         if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
857       } else {
858         if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
859
860         stopBurst();
861         return false;
862       }
863     }
864   }
865
866   anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
867   int order = (*a_burstDeliveryIt).first + 1;
868   a_burstDeliveryIt++;
869   bool dot = true;
870   // sending
871   bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
872
873   if(burstLogEnabled()) {
874     if(a_burstMessages.size() >= 100)
875       dot = (order  % (a_burstMessages.size() / 100));
876
877     if(dot) {
878       writeBurstLogFile(".");
879     } else {
880       writeBurstLogFile(anna::functions::asString(" %d", order));
881       int otaReqs  = a_entity->getOTARequests();
882
883       if(result && (otaReqs != a_otaRequest)) {
884         // false if was a sending after an answer received (no OTA change in this case)
885         // true after push and pop operations
886         a_otaRequest = otaReqs;
887         writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
888       }
889     }
890   }
891
892   // Detailed log:
893   if(logEnabled()) {
894     anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
895     anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
896     std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
897     writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
898   }
899
900   return result;
901 }
902
903 std::string Launcher::lookBurst(int order) const throw() {
904   std::string result = "No message found for order provided (";
905   result += anna::functions::asString(order);
906   result += ")";
907   std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
908
909   if(it != a_burstMessages.end()) {
910     // Decode
911     anna::diameter::codec::Message codecMsg;
912     try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
913     result = codecMsg.asXMLString();
914   }
915
916   return result;
917 }
918
919 std::string Launcher::gotoBurst(int order) throw() {
920   std::string result = "Position not found for order provided (";
921   std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
922
923   if(it != a_burstMessages.end()) {
924     a_burstDeliveryIt = it;
925     result = "Position updated for order provided (";
926   }
927
928   result += anna::functions::asString(order);
929   result += ")";
930   return result;
931 }
932
933 void Launcher::resetCounters() throw() {
934   anna::diameter::comm::OamModule::instantiate().resetCounters();
935   anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
936   anna::diameter::codec::OamModule::instantiate().resetCounters();
937 }
938
939 void Launcher::signalUSR2() throw(anna::RuntimeException) {
940   LOGNOTICE(
941     std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
942     msg += SIGUSR2_TASKS_INPUT_FILENAME;
943     msg += "' (results will be written at '";
944     msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
945     msg += "')";
946     anna::Logger::notice(msg, ANNA_FILE_LOCATION);
947   );
948   // Operation:
949   std::string line;
950   std::string response_content;
951   std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
952   std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
953
954   if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
955
956   if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
957
958   while(getline(in_file, line)) {
959     LOGDEBUG(
960       std::string msg = "Processing line: ";
961       msg += line;
962       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
963     );
964
965     try {
966       eventOperation(line, response_content);
967     } catch(RuntimeException &ex) {
968       ex.trace();
969     }
970
971     out_file << response_content;
972   }
973
974   in_file.close();
975   out_file.close();
976 }
977
978 std::string Launcher::help() const throw() {
979   std::string result = "\n";
980   result += "\n                     ------------- HELP -------------\n";
981   result += "\n";
982   result += "\nOVERVIEW";
983   result += "\n--------";
984   result += "\n";
985   result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
986   result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
987   result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
988   result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
989   result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
990   result += "\n send it to another process.";
991   result += "\n";
992   result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
993   result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
994   result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
995   result += "\n generation, expiration control and many more features.";
996   result += "\n";
997   result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
998   result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
999   result += "\n";
1000   result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
1001   result += "\n   kill -10 <pid>";
1002   result += "\n    or";
1003   result += "\n   kill -s SIGUSR1 <pid>";
1004   result += "\n    and then";
1005   result += "\n   vi /var/tmp/anna.context.<pid>";
1006   result += "\n";
1007   result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
1008   result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
1009   result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
1010   result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
1011   result += "\n measurements.";
1012   result += "\n";
1013   result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
1014   result += "\n";
1015   result += "\n";
1016   result += "\nCOMMAND LINE";
1017   result += "\n------------";
1018   result += "\n";
1019   result += "\nStart the launcher process without arguments in order to see all the startup configuration";
1020   result += "\n posibilities, many of which could be modified on the air through the management interface";
1021   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
1022   result += "\n";
1023   result += "\nAs mandatory, the stack definition given through the xml dictionary:";
1024   result += "\n   --dictionary <path to dictionary file>";
1025   result += "\n";
1026   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
1027   result += "\n   --diameterServer localhost:3868 --diameterServerSessions 10 --entityServerSessions 0";
1028   result += "\n";
1029   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
1030   result += "\n   --entity 192.168.12.11:3868,192.168.12.21:3868 --entityServerSessions 10 --diameterServerSessions 0";
1031   result += "\n";
1032   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
1033   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
1034   result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
1035   result += "\n arguments in order to define the balancing behaviour.";
1036   result += "\n";
1037   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
1038   result += "\n customized ones using '--cer <xml message file>' and '--dwr <xml message file>'.";
1039   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
1040   result += "\n customized ones using operations interface.";
1041   result += "\n";
1042   result += "\n";
1043   result += "\nDYNAMIC OPERATIONS";
1044   result += "\n------------------";
1045   result += "\n";
1046   result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
1047   result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
1048   result += "\n separated by pipes. These are the available commands:";
1049   result += "\n";
1050   result += "\n--------------------------------------------------------------------------------------- General purpose";
1051   result += "\n";
1052   result += "\nhelp                                 This help. Startup information-level traces also dump this help.";
1053   result += "\n";
1054   result += "\n------------------------------------------------------------------------------------ Parsing operations";
1055   result += "\n";
1056   result += "\ncode|<source_file>|<target_file>     Encodes source file (pathfile) into target file (pathfile).";
1057   result += "\ndecode|<source_file>|<target_file>   Decodes source file (pathfile) into target file (pathfile).";
1058   result += "\nloadxml|<source_file>                Reinterpret xml source file (pathfile).";
1059   result += "\n";
1060   result += "\n------------------------------------------------------------------------------------------- Hot changes";
1061   result += "\n";
1062   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
1063   result += "\n                                      server socket.";
1064   result += "\ncontext|[target file]                Application context could also be written by mean this operation,";
1065   result += "\n                                      and not only through SIGUSR1. If optional path file is missing,";
1066   result += "\n                                      default '/var/tmp/anna.context.<pid>' will be used.";
1067   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
1068   result += "\n                                      performance measurement. Context data can be written at";
1069   result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
1070   result += "\n                                      or sending operation 'context|[target file]'.";
1071   result += "\nforceCountersRecord                  Forces dump to file the current counters of the process.";
1072   result += "\n";
1073   result += "\n<visibility action>|[<address>:<port>]|[socket id]";
1074   result += "\n";
1075   result += "\n       Actions: hide, show (update state) and hidden, shown (query state).";
1076   result += "\n       Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
1077   result += "\n       If missing server (first parameter) all applications sockets will be affected.";
1078   result += "\n       If missing socket (second parameter) for specific server, all its sockets will be affected.";
1079   result += "\n";
1080   result += "\n       All application client sessions are shown on startup, but standard delivery only use primary";
1081   result += "\n        server ones except if fails. Balance configuration use all the allowed sockets. You could also";
1082   result += "\n        use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
1083   result += "\n        client sessions, but for this, hide/show feature seems easier.";
1084   result += "\n";
1085   result += "\n--------------------------------------------------------------------------------------- Flow operations";
1086   result += "\n";
1087   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
1088   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
1089   result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
1090   result += "\nanswerxml2e|[source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
1091   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
1092   result += "\n                           as many queues as different message codes have been programmed.";
1093   result += "\nanswerxml2c|[source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
1094   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
1095   result += "\n                           as many queues as different message codes have been programmed.";
1096   result += "\nanswerxml|[source_file]    Same as 'answerxml2c'.";
1097   result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
1098   result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
1099   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
1100   result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
1101   result += "\nanswerxml(2e/2c)|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
1102   result += "\nanswerxml(2e/2c)|rotate    Enable the corresponding queue rotation, useful in performance tests.";
1103   result += "\n                           Rotation consists in add again to the queue, each element retrieved for answering.";
1104   result += "\n";
1105   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
1106   result += "\nspecial scenarios (protocol errors):";
1107   result += "\n";
1108   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
1109   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
1110   result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
1111   result += "\n";
1112   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
1113   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
1114   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
1115   result += "\n";
1116   result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
1117   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
1118   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
1119   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
1120   result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
1121   result += "\n";
1122   result += "\nIn the most complete situation (process with both client and server side) there are internally";
1123   result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
1124   result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
1125   result += "\n each one we could program different answers corresponding to different request codes received.";
1126   result += "\n";
1127   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
1128   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
1129   result += "\n    use sendxml/sendhex operations better than programming.";
1130   result += "\n";
1131   result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
1132   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
1133   result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
1134   result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
1135   result += "\n";
1136   result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
1137   result += "\n";
1138   result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
1139   result += "\n details when unique log file is dumped:";
1140   result += "\n";
1141   result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
1142   result += "\n   [sent2c/send2cError]   Send to client (success/error)";
1143   result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
1144   result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
1145   result += "\n   [recvfc]               Reception from client";
1146   result += "\n   [recvfe]               Reception from entity";
1147   result += "\n   [req2c-expired]        A request sent to client has been expired";
1148   result += "\n   [req2e-expired]        A request sent to entity has been expired";
1149   result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
1150   result += "\n                           has been logged)";
1151   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
1152   result += "\n                           has been logged)";
1153   result += "\n";
1154   result += "\n-------------------------------------------------------------------------------------------- Load tests";
1155   result += "\n";
1156   result += "\nburst|<action>|[parameter]     Used for performance testing, we first program diameter requests";
1157   result += "\n                                messages in order to launch them from client side to the configured";
1158   result += "\n                                diameter entity. We could start the burst with an initial load";
1159   result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
1160   result += "\n                                per answer received or expired context. There are 10 actions: clear,";
1161   result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
1162   result += "\n";
1163   result += "\n   burst|clear                 Clears all loaded burst messages.";
1164   result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
1165   result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
1166   result += "\n                                a certain initial load.";
1167   result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
1168   result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
1169   result += "\n                               Popping all OTA requests implies burst stop because no more answer";
1170   result += "\n                                will arrive to the process. Burst output file (-burstLog command";
1171   result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
1172   result += "\n                                represents one received answer for which no new request is sent.";
1173   result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
1174   result += "\n   burst|repeat|[[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
1175   result += "\n                                amount is greater than burst list size, they will be limited when";
1176   result += "\n                                the list is processed except when repeat mode is enabled.";
1177   result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
1178   result += "\n                                operations is that burst won't be awaken. Externally we could control";
1179   result += "\n                                sending time (no request will be sent for answers).";
1180   result += "\n   burst|goto|<order>          Updates current burst pointer position.";
1181   result += "\n   burst|look|<order>          Show programmed burst message for order provided.";
1182   result += "\n";
1183   result += "\n";
1184   result += "\nUSING OPERATIONS INTERFACE";
1185   result += "\n--------------------------";
1186   result += "\n";
1187   result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
1188   result += "\n";
1189   result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
1190   result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
1191   result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
1192   result += "\n using curl client could be:";
1193   result += "\n";
1194   result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
1195   result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
1196   result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
1197   result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
1198   result += "\n   etc.";
1199   result += "\n";
1200   result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
1201   result += "\n";
1202   result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
1203   result += "\n signal event:";
1204   result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
1205   result += "\n    then";
1206   result += "\n   kill -12 <pid>";
1207   result += "\n    or";
1208   result += "\n   kill -s SIGUSR2 <pid>";
1209   result += "\n    and then see the results:";
1210   result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
1211   result += "\n";
1212   result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
1213   result += "\n case over the output file. Take into account that all the content of the task file will be executed";
1214   result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
1215   result += "\n interface.";
1216   result += "\n";
1217   result += "\n";
1218   return result;
1219 }
1220
1221 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1222   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1223   CommandLine& cl(anna::CommandLine::instantiate());
1224   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1225   response_content = "Operation processed with exception. See traces\n"; // supposed
1226   std::string result = "";
1227   anna::DataBlock db_aux(true);
1228   anna::diameter::codec::Message codecMsg;
1229
1230   ///////////////////////////////////////////////////////////////////
1231   // Simple operations without arguments:
1232
1233   // Help:
1234   if(operation == "help") {
1235     std::string s_help = help();
1236     std::cout << s_help << std::endl;
1237     LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1238     response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n";
1239     return;
1240   }
1241
1242   // Reset performance data:
1243   if(operation == "collect") {
1244     resetCounters();
1245     resetStatistics();
1246     response_content = "All process counters & statistic information have been reset\n";
1247     return;
1248   }
1249
1250   // Counters dump on demand:
1251   if(operation == "forceCountersRecord") {
1252     forceCountersRecord();
1253     response_content = "Current counters have been dump to disk\n";
1254     return;
1255   }
1256
1257   ///////////////////////////////////////////////////////////////////
1258   // Tokenize operation
1259   Tokenizer params;
1260   params.apply(operation, "|");
1261   int numParams = params.size() - 1;
1262
1263   // No operation has more than 2 arguments ...
1264   if(numParams > 2) {
1265     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1266     throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1267   }
1268
1269   // Get the operation type:
1270   Tokenizer::const_iterator tok_iter = params.begin();
1271   std::string opType = Tokenizer::data(tok_iter);
1272   // Check the number of parameters:
1273   bool wrongBody = false;
1274
1275   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1276
1277   if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1278
1279   if((opType == "burst") && (numParams < 1)) wrongBody = true;
1280
1281   if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1282
1283   if(wrongBody) {
1284     // Launch exception
1285     std::string msg = "Wrong body content format on HTTP Request for '";
1286     msg += opType;
1287     msg += "' operation (missing parameter/s)";
1288     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1289   }
1290
1291   // All seems ok:
1292   std::string param1, param2;
1293
1294   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1295
1296   if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1297
1298   // Operations:
1299   if(opType == "context") {
1300     std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
1301     writeContext(contextFile);
1302     response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
1303     return;
1304   }
1305
1306   if(opType == "code") {
1307     codecMsg.loadXML(param1);
1308     std::string hexString = anna::functions::asHexString(codecMsg.code());
1309     // write to outfile
1310     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1311     outfile.write(hexString.c_str(), hexString.size());
1312     outfile.close();
1313   } else if(opType == "decode") {
1314     // Get DataBlock from file with hex content:
1315     if(!getDataBlockFromHexFile(param1, db_aux))
1316       throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1317
1318     // Decode
1319     try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1320
1321     std::string xmlString = codecMsg.asXMLString();
1322     // write to outfile
1323     std::ofstream outfile(param2.c_str(), std::ifstream::out);
1324     outfile.write(xmlString.c_str(), xmlString.size());
1325     outfile.close();
1326   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1327     MyDiameterEntity *entity = getEntity();
1328
1329     if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1330
1331     if(param1 != "") {
1332       if(param2 != "") {
1333         std::string key = param1;
1334         key += "|";
1335         key += param2;
1336
1337         if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1338
1339         if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1340
1341         if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1342
1343         if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1344       } else {
1345         std::string address;
1346         int port;
1347         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1348
1349         if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1350
1351         if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1352
1353         if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1354
1355         if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1356       }
1357     } else {
1358       if(opType == "hide") entity->hide();
1359
1360       if(opType == "show") entity->show();
1361
1362       if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1363
1364       if(opType == "shown") result = entity->shown() ? "true" : "false";
1365     }
1366   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1367     MyDiameterEntity *entity = getEntity();
1368
1369     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1370     anna::diameter::comm::Message *msg = createCommMessage();
1371
1372     if((opType == "sendxml") || (opType == "sendxml2e")) {
1373       codecMsg.loadXML(param1);
1374       msg->clearBody();
1375       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)
1376
1377       msg->setBody(codecMsg.code());
1378     } else {
1379       // Get DataBlock from file with hex content:
1380       if(!getDataBlockFromHexFile(param1, db_aux))
1381         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1382
1383       msg->setBody(db_aux);
1384     }
1385
1386     bool success = entity->send(msg, cl.exists("balance"));
1387     releaseCommMessage(msg);
1388
1389     // Detailed log:
1390     if(logEnabled()) {
1391       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1392       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1393       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1394       writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
1395     }
1396   } else if((opType == "burst")) {
1397     anna::diameter::comm::Entity *entity = getEntity();
1398
1399     if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1400
1401     // burst|clear                     clears all loaded burst messages.
1402     // burst|load|<source_file>        loads the next diameter message into launcher burst.
1403     // burst|start|<initial load>      starts the message sending with a certain initial load.
1404     // burst|push|<load amount>        sends specific non-aynchronous load.
1405     // burst|stop                      stops the burst cycle.
1406     // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1407     // burst|send|<amount>             send messages from burst list. The main difference with
1408     //                                 start/push operations is that burst won't be awaken.
1409     //                                 Externally we could control sending time (no request
1410     //                                 will be sent for answers).
1411     // burst|goto|<order>              Updates current burst pointer position.
1412     // burst|look|<order>              Show programmed burst message for order provided.
1413
1414     if(param1 == "clear") {
1415       result = "Removed ";
1416       result += anna::functions::asString(clearBurst());
1417       result += " elements.";
1418     } else if(param1 == "load") {
1419       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1420
1421       codecMsg.loadXML(param2);
1422
1423       if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1424       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)
1425
1426       int position = loadBurstMessage(codecMsg.code());
1427       result = "Loaded '";
1428       result += param2;
1429       result += "' file into burst list position ";
1430       result += anna::functions::asString(position);
1431     } else if(param1 == "start") {
1432       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1433
1434       int initialLoad = atoi(param2.c_str());
1435       int processed = startBurst(initialLoad);
1436
1437       if(processed > 0) {
1438         result = "Initial load completed for ";
1439         result += anna::functions::entriesAsString(processed, "message");
1440         result += ".";
1441       }
1442     } else if(param1 == "push") {
1443       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1444
1445       int pushed = pushBurst(atoi(param2.c_str()));
1446
1447       if(pushed > 0) {
1448         result = "Pushed ";
1449         result += anna::functions::entriesAsString(pushed, "message");
1450         result += ".";
1451       }
1452     } else if(param1 == "pop") {
1453       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1454
1455       int releaseLoad = atoi(param2.c_str());
1456       int popped = popBurst(releaseLoad);
1457
1458       if(popped > 0) {
1459         result = "Burst popped for ";
1460         result += anna::functions::entriesAsString(popped, "message");
1461         result += ".";
1462       }
1463     } else if(param1 == "stop") {
1464       int left = stopBurst();
1465
1466       if(left != -1) {
1467         result += anna::functions::entriesAsString(left, "message");
1468         result += " left to the end of the cycle.";
1469       }
1470     } else if(param1 == "repeat") {
1471       if(param2 == "") param2 = "yes";
1472
1473       bool repeat = (param2 == "yes");
1474       repeatBurst(repeat);
1475       result += (repeat ? "Mode on." : "Mode off.");
1476     } else if(param1 == "send") {
1477       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1478
1479       int sent = sendBurst(atoi(param2.c_str()));
1480
1481       if(sent > 0) {
1482         result = "Sent ";
1483         result += anna::functions::entriesAsString(sent, "message");
1484         result += ".";
1485       }
1486     } else if(param1 == "goto") {
1487       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1488
1489       result = gotoBurst(atoi(param2.c_str()));
1490       result += ".";
1491     } else if(param1 == "look") {
1492       if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1493
1494       result = "\n\n";
1495       result += lookBurst(atoi(param2.c_str()));
1496       result += "\n\n";
1497     } else {
1498       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1499     }
1500   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1501     MyLocalServer *localServer = getDiameterLocalServer();
1502
1503     if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1504     anna::diameter::comm::Message *msg = createCommMessage();
1505
1506     if(opType == "sendxml2c") {
1507       codecMsg.loadXML(param1);
1508       msg->clearBody();
1509       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)
1510
1511       msg->setBody(codecMsg.code());
1512     } else {
1513       // Get DataBlock from file with hex content:
1514       if(!getDataBlockFromHexFile(param1, db_aux))
1515         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1516
1517       msg->setBody(db_aux);
1518     }
1519
1520     bool success = localServer->send(msg);
1521     releaseCommMessage(msg);
1522
1523     // Detailed log:
1524     if(logEnabled()) {
1525       anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1526       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1527       writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
1528     }
1529   } else if(opType == "loadxml") {
1530     codecMsg.loadXML(param1);
1531     std::string xmlString = codecMsg.asXMLString();
1532     std::cout << xmlString << std::endl;
1533   } else if(opType == "diameterServerSessions") {
1534     int diameterServerSessions = atoi(param1.c_str());
1535
1536     if(!getDiameterLocalServer())
1537       startDiameterServer(diameterServerSessions);
1538     else
1539       getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
1540   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1541     MyLocalServer *localServer = getDiameterLocalServer();
1542
1543     if(!localServer)
1544       throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1545
1546     if(param1 == "") { // programmed answers FIFO's to stdout
1547       std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl;
1548       response_content = "Programmed answers dumped on stdout\n";
1549       return;
1550     } else if (param1 == "rotate") {
1551       localServer->getReactingAnswers()->rotate(true);
1552     } else if (param1 == "exhaust") {
1553       localServer->getReactingAnswers()->rotate(false);
1554     } else if (param1 == "clear") {
1555       localServer->getReactingAnswers()->clear();
1556     } else if (param1 == "dump") {
1557       localServer->getReactingAnswers()->dump();
1558     } else {
1559       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1560       LOGDEBUG
1561       (
1562         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1563       );
1564
1565       if(message->isRequest())
1566         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1567
1568       int code = message->getId().first;
1569       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1570       localServer->getReactingAnswers()->addMessage(code, message);
1571     }
1572   } else if(opType == "answerxml2e") {
1573     MyDiameterEntity *entity = getEntity();
1574
1575     if(!entity)
1576       throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1577
1578     if(param1 == "") { // programmed answers FIFO's to stdout
1579       std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl;
1580       response_content = "Programmed answers dumped on stdout\n";
1581       return;
1582     } else if (param1 == "rotate") {
1583       entity->getReactingAnswers()->rotate(true);
1584     } else if (param1 == "exhaust") {
1585       entity->getReactingAnswers()->rotate(false);
1586     } else if (param1 == "clear") {
1587       entity->getReactingAnswers()->clear();
1588     } else if (param1 == "dump") {
1589       entity->getReactingAnswers()->dump();
1590     } else {
1591       anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1592       LOGDEBUG
1593       (
1594         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1595       );
1596
1597       if(message->isRequest())
1598         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1599
1600       int code = message->getId().first;
1601       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1602       entity->getReactingAnswers()->addMessage(code, message);
1603     }
1604   } else {
1605     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1606     throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
1607   }
1608
1609   // HTTP response
1610   response_content = "Operation processed; ";
1611
1612   if((opType == "decode") || (opType == "code")) {
1613     response_content += "File '";
1614     response_content += param2;
1615     response_content += "' created.";
1616     response_content += "\n";
1617   } else if((opType == "hide") || (opType == "show")) {
1618     response_content += "Resource '";
1619     response_content += ((param1 != "") ? param1 : "Entity");
1620
1621     if(param2 != "") {
1622       response_content += "|";
1623       response_content += param2;
1624     }
1625
1626     response_content += "' ";
1627
1628     if(opType == "hide") response_content += "has been hidden.";
1629
1630     if(opType == "show") response_content += "has been shown.";
1631
1632     response_content += "\n";
1633   } else if((opType == "hidden") || (opType == "shown")) {
1634     response_content += "Result: ";
1635     response_content += result;
1636     response_content += "\n";
1637   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1638     response_content += "Message '";
1639     response_content += param1;
1640     response_content += "' sent to entity.";
1641     response_content += "\n";
1642   } else if(opType == "burst") {
1643     response_content += "Burst '";
1644     response_content += param1;
1645     response_content += "' executed. ";
1646     response_content += result;
1647     response_content += "\n";
1648   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1649     response_content += "Message '";
1650     response_content += param1;
1651     response_content += "' sent to client.";
1652     response_content += "\n";
1653   } else if(opType == "loadxml") {
1654     response_content += "Message '";
1655     response_content += param1;
1656     response_content += "' loaded.";
1657     response_content += "\n";
1658   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1659     response_content += "'";
1660     response_content += param1;
1661     response_content += "' applied on server FIFO queue";
1662     response_content += "\n";
1663   } else if(opType == "answerxml2e") {
1664     response_content += "'";
1665     response_content += param1;
1666     response_content += "' applied on client FIFO queue";
1667     response_content += "\n";
1668   } else if(opType == "diameterServerSessions") {
1669     response_content += "Maximum server socket connections updated to '";
1670     response_content += param1;
1671     response_content += "'.";
1672     response_content += "\n";
1673   }
1674 }
1675
1676 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
1677   CommandLine& cl(anna::CommandLine::instantiate());
1678   std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
1679
1680   if(sessionBasedModelsType == "RoundRobin") return -1;  // IEC also would return -1
1681
1682   try {
1683     // Service-Context-Id:
1684     anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
1685     std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
1686
1687     switch(chargingContext) {
1688     case anna::diameter::helpers::dcca::ChargingContext::Data:
1689     case anna::diameter::helpers::dcca::ChargingContext::Voice:
1690     case anna::diameter::helpers::dcca::ChargingContext::Content: {
1691       // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
1692       std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
1693       std::string diameterIdentity, optional;
1694       anna::U32 high, low;
1695       anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
1696
1697       if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
1698
1699       if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
1700
1701       if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
1702     }
1703     //case anna::diameter::helpers::dcca::ChargingContext::SMS:
1704     //case anna::diameter::helpers::dcca::ChargingContext::MMS:
1705     //default:
1706     //   return -1; // IEC model and Unknown traffic types
1707     }
1708   } catch(anna::RuntimeException &ex) {
1709     LOGDEBUG(
1710       std::string msg = ex.getText();
1711       msg += " | Round-robin between sessions will be used to send";
1712       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1713     );
1714   }
1715
1716   return -1;
1717 }
1718
1719 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
1720 throw() {
1721   anna::xml::Node* result = parent->createChild("launcher");
1722   anna::comm::Application::asXML(result);
1723   // Timming:
1724   result->createAttribute("StartTime", a_start_time.asString());
1725   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
1726   // Diameter:
1727   getCodecEngine()->asXML(result);
1728   // OAM:
1729   anna::diameter::comm::OamModule::instantiate().asXML(result);
1730   anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
1731   anna::diameter::codec::OamModule::instantiate().asXML(result);
1732   // Statistics:
1733   anna::statistics::Engine::instantiate().asXML(result);
1734   return result;
1735 }