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