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