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