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