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