Make Fix Mode commandline configurable
[anna.git] / example / diameter / launcher / main.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // http://redmine.teslayout.com/projects/anna-suite
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     *  Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #include <fstream>
38 #include <iostream>
39 #include <time.h>
40 #include <sys/stat.h> // chmod
41 #include <fcntl.h> // open / write
42
43 #include <string>
44 #include <map>
45 #include <deque>
46
47
48 #include <anna/config/defines.hpp>
49 #include <anna/comm/comm.hpp>
50 #include <anna/core/core.hpp>
51 #include <anna/xml/xml.hpp>
52 #include <anna/app/functions.hpp>
53 #include <anna/http/Request.hpp>
54 #include <anna/http/Response.hpp>
55 #include <anna/http/Handler.hpp>
56 #include <anna/http/Transport.hpp>
57 #include <anna/http/functions.hpp>
58 #include <anna/comm/functions.hpp>
59 #include <anna/timex/Engine.hpp>
60 #include <anna/timex/Clock.hpp>
61 #include <anna/diameter/stack/Engine.hpp>
62 #include <anna/diameter/codec/Engine.hpp>
63 #include <anna/diameter.comm/OamModule.hpp>
64 #include <anna/diameter.comm/ClientSession.hpp>
65 #include <anna/diameter.comm/LocalServer.hpp>
66 #include <anna/diameter.comm/Engine.hpp>
67 #include <anna/diameter.comm/Entity.hpp>
68 #include <anna/diameter.comm/Response.hpp>
69 #include <anna/diameter/functions.hpp>
70 #include <anna/diameter/codec/OamModule.hpp>
71 #include <anna/diameter/codec/functions.hpp>
72 #include <anna/time/functions.hpp>
73 #include <anna/time/Date.hpp>
74 #include <anna/diameter/helpers/base/defines.hpp>
75 #include <anna/diameter/helpers/base/functions.hpp>
76 #include <anna/diameter/helpers/dcca/defines.hpp>
77 #include <anna/diameter/helpers/dcca/functions.hpp>
78 #include <anna/statistics/Engine.hpp>
79 #include <anna/core/functions.hpp>
80
81 namespace anna {
82 class DataBlock;
83 }
84
85 namespace anna {
86 namespace diameter {
87 namespace comm {
88 class Entity;
89 class Response;
90 class LocalServer;
91 }
92 }
93 }
94
95 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
96 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
97
98
99 // Auxiliary message for sendings
100 anna::diameter::comm::Message G_commMsgSent2c, G_commMsgSent2e, G_commMsgFwd2c, G_commMsgFwd2e;
101 anna::diameter::comm::Message G_commMsg;
102 anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg;
103 anna::Recycler<anna::diameter::comm::Message> G_commMessages; // create on requests forwards without programmed answer / release in answers forward
104
105 // Auxiliary resources for answers programming
106 class ProgrammedAnswers {
107
108 typedef std::deque<anna::diameter::codec::Message*> codec_messages_deque;
109 typedef std::deque<anna::diameter::codec::Message*>::iterator codec_messages_deque_iterator;
110 typedef std::deque<anna::diameter::codec::Message*>::const_iterator codec_messages_deque_const_iterator;
111 typedef std::map < int /* message code */, codec_messages_deque* > reacting_answers_container;
112 typedef std::map < int /* message code */, codec_messages_deque* >::iterator  reacting_answers_iterator;
113 typedef std::map < int /* message code */, codec_messages_deque* >::const_iterator  reacting_answers_const_iterator;
114
115   reacting_answers_container a_deques;
116   bool a_rotate;
117
118   public:
119     ProgrammedAnswers() { a_rotate = false; }
120     ~ProgrammedAnswers() { clear(); }
121
122     bool rotate() const throw() { return a_rotate; }
123     void rotate(bool r) throw() { a_rotate = r; }
124
125     void clear () throw() {
126       for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
127         anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
128         engine->releaseMessage(*(it->second->begin()));
129         delete(it->second);
130       }
131       a_deques.clear();
132     }
133
134     void dump () throw() {
135       std::string outfilename, xmlString;
136       for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
137         int sequence = 1;
138         for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
139           // programmed_answer.<code>.<sequence>
140           outfilename = "programmed_answer.";
141           outfilename += anna::functions::asString(it->first);
142           outfilename += ".";
143           outfilename += anna::functions::asString(sequence++);
144           outfilename += ".xml";
145           std::ofstream outfile(outfilename.c_str(), std::ifstream::out);
146           xmlString =  (*itm)->asXMLString();
147           outfile.write(xmlString.c_str(), xmlString.size());
148           outfile.close();
149         }
150       }
151     }
152
153     void addMessage(int code, anna::diameter::codec::Message *message) throw() {
154       reacting_answers_const_iterator it = a_deques.find(code);
155       if (it != a_deques.end()) {
156         it->second->push_back(message);
157       }
158       else {
159         codec_messages_deque *deque = new codec_messages_deque;
160         a_deques[code] = deque;
161         deque->push_back(message);
162       }
163     }
164
165     anna::diameter::codec::Message* getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty
166       anna::diameter::codec::Message *result = NULL;
167       reacting_answers_const_iterator it = a_deques.find(code);
168       if (it != a_deques.end()) {
169         if (!it->second->empty()) result = *(it->second->begin());
170       }
171       return result;
172     }
173
174     void nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty)
175       reacting_answers_const_iterator it = a_deques.find(code);
176       if (it != a_deques.end()) {
177         if (!it->second->empty()) {
178           anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
179           if (a_rotate) {
180             addMessage(code, *(it->second->begin()));
181           }
182           else {
183             engine->releaseMessage(*(it->second->begin()));
184           }
185           it->second->pop_front();
186         }
187       }
188     }
189
190     std::string asString(const char *queueName) const throw() {
191       std::string result = "";
192       std::string aux = "FIFO QUEUE '";
193       aux += queueName;
194       aux += "', Rotation ";
195       aux += a_rotate ? "enabled":"disabled";
196       result += anna::functions::highlightJustify(aux);
197       if(a_deques.size() != 0) {
198         for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
199           if (it->second->size() != 0) {      
200             aux = "Answer code ";
201             aux += anna::functions::asString(it->first);
202             result += anna::functions::highlightJustify(aux, anna::functions::TextHighlightMode::OverAndUnderline,
203                                                              anna::functions::TextJustifyMode::Left, '-');
204             for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
205               result += (*itm)->asXMLString();
206               result += "\n";
207             }
208             result += "\n";
209           }
210         }
211       }
212       else {
213         result = "No ocurrences found\n\n";
214       }
215       return result;
216     }
217 };
218
219 ProgrammedAnswers G_reactingAnswers2C, G_reactingAnswers2E;
220
221
222
223 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
224 // COUNTERS RECORD PROCEDURE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
225 class MyCounterRecorderClock : public anna::timex::Clock {
226 public:
227   MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) :
228     anna::timex::Clock(clockName, timeout) {;}
229   //virtual ~MyCounterRecorderClock();
230
231   virtual bool tick() throw(RuntimeException) {
232     anna::diameter::comm::OamModule::instantiate().recordCounters();
233     anna::diameter::codec::OamModule::instantiate().recordCounters();
234     return true;
235   }
236 };
237
238 class MyCounterRecorder : public anna::oam::CounterRecorder {
239
240   // attributes
241   int a_stream;
242   std::string a_fileNamePrefix;
243   std::string a_fileName;
244   time_t a_previousTime;
245   std::string a_fixedLine;
246
247   // pure virtual definitions:
248   void open() throw(anna::RuntimeException) {
249     static char str [256];
250     const time_t now = ::time(NULL);
251     struct tm tmNow;
252     struct tm tmPrevious;
253     anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow));
254     anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious));
255     sprintf(
256       str, ".Date%04d%02d%02d.Time%02d%02d%02d",
257       1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
258       tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec);
259     a_fileName = a_fileNamePrefix;
260     a_fileName += str;
261     LOGDEBUG(
262       std::string msg("Flush counters | ");
263       msg += a_fileName;
264       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
265     );
266
267     if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1)
268       throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
269
270     sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d",
271             1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1,
272             tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min,
273             1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
274             tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min
275            );
276     a_fixedLine = str;
277   }
278
279
280   void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) {
281     static char line [356];
282     anna::oam::Counter::type_t value = counter;
283     sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str());
284
285     if(write(a_stream, line, anna_strlen(line)) == -1)
286       throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
287   }
288
289   void close() throw() {
290     if(a_stream != -1) {
291       ::close(a_stream);
292       a_stream = -1;
293     }
294
295     chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR);
296     a_previousTime = ::time(NULL);
297   }
298
299   std::string asString() const throw() {
300     std::string result = "Physical counters dump at file '";
301     result += a_fileName;
302     result += "'. Another way to see counters: context dump (kill -10 <pid>";
303     return result;
304   }
305
306 public:
307   MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) {
308     a_previousTime = ::time(NULL);
309   }
310 };
311
312 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
313
314
315 class MyDiameterEntity : public anna::diameter::comm::Entity {
316
317   void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
318   void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
319   void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
320   void eventDPA(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
321
322   // Reimplementation
323   int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw();
324 };
325
326 class MyLocalServer : public anna::diameter::comm::LocalServer {
327
328   void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
329   void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
330   void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
331   void eventDPA(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
332 };
333
334 class MyDiameterEngine : public anna::diameter::comm::Engine {
335 public:
336
337   static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; }
338   MyDiameterEngine() {;}
339
340 // Default implementation is enough
341 //   void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied
342 //   void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied
343 //   void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied
344
345 private:
346   anna::Recycler<MyDiameterEntity> a_entitiesRecycler;
347
348   anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); }
349
350   void releaseEntity(anna::diameter::comm::Entity* entity) throw() {
351     MyDiameterEntity* aux = static_cast <MyDiameterEntity*>(entity);
352     a_entitiesRecycler.release(aux);
353   }
354
355   anna::Recycler<MyLocalServer> a_localServersRecycler;
356
357   anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); }
358
359   void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() {
360     MyLocalServer* aux = static_cast <MyLocalServer*>(localServer);
361     a_localServersRecycler.release(aux);
362   }
363 };
364
365
366 class MyHandler : public anna::http::Handler {
367 public:
368   MyHandler() :  anna::http::Handler("http_converter::MyHandler") {
369     allocateResponse()->createHeader(anna::http::Header::Type::Date);
370   }
371
372 private:
373
374   void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException);
375   void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;}
376 };
377
378 class MyCommunicator : public anna::comm::Communicator {
379 public:
380   MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode),
381     a_contexts("Contexts")
382   {;}
383
384   void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw();
385   void terminate() throw();
386
387 private:
388   anna::ThreadData <MyHandler> a_contexts;
389   void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException);
390   void eventBreakConnection(Server* server) throw();
391 };
392
393 class Launcher : public anna::comm::Application {
394
395   MyCommunicator *a_communicator;
396   MyDiameterEngine *a_myDiameterEngine;
397   anna::diameter::comm::Entity *a_entity;
398   std::string a_logFile, a_burstLogFile;
399   std::ofstream a_burstLogStream;
400   bool a_splitLog, a_detailedLog, a_dumpLog;
401   anna::time::Date a_start_time;
402   anna::timex::Engine* a_timeEngine;
403   MyCounterRecorder *a_counterRecorder;
404   MyCounterRecorderClock *a_counterRecorderClock;
405   std::string a_cerPathfile;
406   std::string a_dwrPathfile;
407
408   // Burst feature
409   int a_burstCycle;
410   bool a_burstRepeat;
411   bool a_burstActive;
412   std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages;
413   int a_burstLoadIndx;
414   std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
415   int a_otaRequest;
416   int a_burstPopCounter;
417
418   anna::comm::ServerSocket* a_httpServerSocket; // HTTP
419   anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER
420   void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException);
421   void initialize() throw(anna::RuntimeException); // HTTP
422   void run() throw(anna::RuntimeException);
423
424 public:
425   Launcher();
426
427   MyCommunicator *getCommunicator() throw() { return a_communicator; }
428   MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); }
429   void baseProtocolSetupAsClient(void) throw(anna::RuntimeException);
430   anna::diameter::comm::Entity *getEntity() throw() { return a_entity; }
431   anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; }
432   void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException);
433   bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
434   void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw();
435   void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw();
436   void writeBurstLogFile(const std::string &buffer) throw();
437   bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
438   void startDiameterServer(int) throw(anna::RuntimeException);
439
440   anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
441   void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); }
442   void resetCounters() throw();
443   void signalUSR2() throw(anna::RuntimeException);
444   std::string help() const throw();
445
446   // helpers
447   bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw();
448
449   // Burst feature
450   int clearBurst() throw(); // returns removed
451   int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
452   void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
453   int startBurst(int initialLoad) throw();  // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
454   int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative)
455   int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative)
456   int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
457   int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
458   bool burstActive() const throw() { return a_burstActive; }
459   bool sendBurstMessage(bool anyway = false) throw();
460   std::string lookBurst(int order) const throw();
461   std::string gotoBurst(int order) throw();
462 };
463
464 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
465   // Get hex string
466   static char buffer[8192];
467   std::ifstream infile(pathfile.c_str(), std::ifstream::in);
468
469   if(infile.is_open()) {
470     infile >> buffer;
471     std::string hexString(buffer, strlen(buffer));
472     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
473     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
474     LOGDEBUG(
475       std::string msg = "Hex string (remove colons if exists): ";
476       msg += hexString;
477       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
478     );
479     anna::functions::fromHexString(hexString, db);
480     // Close file
481     infile.close();
482     return true;
483   }
484
485   return false;
486 }
487
488 int Launcher::clearBurst() throw() {
489   int size = a_burstMessages.size();
490
491   if(size) {
492     std::map<int, anna::diameter::comm::Message*>::const_iterator it;
493     std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
494     std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
495
496     for(it = it_min; it != it_max; it++) G_commMessages.release((*it).second);
497
498     a_burstMessages.clear();
499   } else {
500     std::string msg = "Burst list already empty. Nothing done";
501     std::cout << msg << std::endl;
502     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
503   }
504
505   a_burstActive = false;
506   a_burstLoadIndx = 0;
507   a_burstDeliveryIt = a_burstMessages.begin();
508   return size;
509 }
510
511
512 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
513   anna::diameter::comm::Message *msg = G_commMessages.create();
514   msg->setBody(db);
515   a_burstMessages[a_burstLoadIndx++] = msg;
516   return (a_burstLoadIndx - 1);
517 }
518
519 int Launcher::stopBurst() throw() {
520   if(!a_burstActive) {
521     std::string msg = "Burst launch is already stopped. Nothing done";
522     std::cout << msg << std::endl;
523     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
524     return -1;
525   }
526
527   a_burstActive = false;
528   // Remaining on cycle:
529   return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
530 }
531
532 int Launcher::popBurst(int releaseAmount) throw() {
533   if(!a_burstActive) {
534     std::string msg = "Burst launch is stopped. Nothing done";
535     std::cout << msg << std::endl;
536     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
537     return -1;
538   }
539
540   if(releaseAmount < 1) {
541     std::string msg = "No valid release amount is specified. Ignoring burst pop";
542     std::cout << msg << std::endl;
543     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
544     return -2;
545   }
546
547   int currentOTArequests = a_entity->getOTARequests();
548   a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
549   return a_burstPopCounter;
550 }
551
552 int Launcher::pushBurst(int loadAmount) throw() {
553   if(a_burstMessages.size() == 0) {
554     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
555     std::cout << msg << std::endl;
556     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
557     return -1;
558   }
559
560   if(loadAmount < 1) {
561     std::string msg = "No valid load amount is specified. Ignoring burst push";
562     std::cout << msg << std::endl;
563     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
564     return -2;
565   }
566
567   a_burstActive = true;
568   int count;
569
570   for(count = 0; count < loadAmount; count++)
571     if(!sendBurstMessage()) break;
572
573   return count;
574 }
575
576
577 int Launcher::sendBurst(int loadAmount) throw() {
578   if(a_burstMessages.size() == 0) {
579     std::string msg = "Burst data not found (empty list). Ignoring burst launch";
580     std::cout << msg << std::endl;
581     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
582     return -1;
583   }
584
585   if(loadAmount < 1) {
586     std::string msg = "No valid load amount is specified. Ignoring burst send";
587     std::cout << msg << std::endl;
588     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
589     return -2;
590   }
591
592   int count;
593
594   for(count = 0; count < loadAmount; count++)
595     if(!sendBurstMessage(true /* anyway */)) break;
596
597   return count;
598 }
599
600
601
602 int Launcher::startBurst(int initialLoad) throw() {
603   if(initialLoad < 1) {
604     std::string msg = "No initial load is specified. Ignoring burst start";
605     std::cout << msg << std::endl;
606     LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
607     return -2;
608   }
609
610   a_burstActive = true;
611   a_burstCycle = 1;
612   a_burstDeliveryIt = a_burstMessages.begin();
613   return (pushBurst(initialLoad));
614 }
615
616 bool Launcher::sendBurstMessage(bool anyway) throw() {
617   if(!anyway && !burstActive()) return false;
618
619   if(a_burstPopCounter > 0) {
620     if(burstLogEnabled()) writeBurstLogFile("x");
621
622     a_burstPopCounter--;
623     return false;
624   }
625
626   if(a_burstDeliveryIt == a_burstMessages.end()) {
627     a_burstDeliveryIt = a_burstMessages.begin();
628
629     if(!anyway) {
630       if(a_burstRepeat) {
631         a_burstCycle++;
632
633         if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
634       } else {
635         if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
636
637         stopBurst();
638         return false;
639       }
640     }
641   }
642
643   anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
644   int order = (*a_burstDeliveryIt).first + 1;
645   a_burstDeliveryIt++;
646   bool dot = true;
647   // sending
648   bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
649
650   if(burstLogEnabled()) {
651     if(a_burstMessages.size() >= 100)
652       dot = (order  % (a_burstMessages.size() / 100));
653
654     if(dot) {
655       writeBurstLogFile(".");
656     } else {
657       writeBurstLogFile(anna::functions::asString(" %d", order));
658       int otaReqs  = a_entity->getOTARequests();
659
660       if(result && (otaReqs != a_otaRequest)) {
661         // false if was a sending after an answer received (no OTA change in this case)
662         // true after push and pop operations
663         a_otaRequest = otaReqs;
664         writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
665       }
666     }
667   }
668
669   // Detailed log:
670   if(logEnabled()) {
671     anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
672     anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
673     std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
674     writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
675   }
676
677   return result;
678 }
679
680
681 std::string Launcher::lookBurst(int order) const throw() {
682   std::string result = "No message found for order provided (";
683   result += anna::functions::asString(order);
684   result += ")";
685   std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
686
687   if(it != a_burstMessages.end()) {
688     // Decode
689     try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
690
691     result = G_codecMsg.asXMLString();
692   }
693
694   return result;
695 }
696
697 std::string Launcher::gotoBurst(int order) throw() {
698   std::string result = "Position not found for order provided (";
699   std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
700
701   if(it != a_burstMessages.end()) {
702     a_burstDeliveryIt = it;
703     result = "Position updated for order provided (";
704   }
705
706   result += anna::functions::asString(order);
707   result += ")";
708   return result;
709 }
710
711 ////////////////////////////////////////////////////
712
713
714 void Launcher::resetCounters() throw() {
715   // Diameter::comm module:
716   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
717   oamDiameterComm.resetCounters();
718 }
719
720 void Launcher::signalUSR2() throw(anna::RuntimeException) {
721   LOGNOTICE(
722     std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
723     msg += SIGUSR2_TASKS_INPUT_FILENAME;
724     msg += "' (results will be written at '";
725     msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
726     msg += "')";
727     anna::Logger::notice(msg, ANNA_FILE_LOCATION);
728   );
729   // Operation:
730   std::string line;
731   std::string response_content;
732   std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
733   std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
734
735   if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
736
737   if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
738
739   while(getline(in_file, line)) {
740     LOGDEBUG(
741       std::string msg = "Processing line: ";
742       msg += line;
743       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
744     );
745
746     try {
747       eventOperation(line, response_content);
748     } catch(RuntimeException &ex) {
749       ex.trace();
750     }
751
752     out_file << response_content;
753   }
754
755   in_file.close();
756   out_file.close();
757 }
758
759
760 std::string Launcher::help() const throw() {
761   std::string result = "\n";
762   result += "\n                     ------------- HELP -------------\n";
763   result += "\n";
764   result += "\nOVERVIEW";
765   result += "\n--------";
766   result += "\n";
767   result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
768   result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
769   result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
770   result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
771   result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
772   result += "\n send it to another process.";
773   result += "\n";
774   result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
775   result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
776   result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
777   result += "\n generation, expiration control and many more features.";
778   result += "\n";
779   result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
780   result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
781   result += "\n";
782   result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
783   result += "\n   kill -10 <pid>";
784   result += "\n    or";
785   result += "\n   kill -s SIGUSR1 <pid>";
786   result += "\n    and then";
787   result += "\n   vi /var/tmp/anna.context.<pid>";
788   result += "\n";
789   result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
790   result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
791   result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
792   result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
793   result += "\n measurements.";
794   result += "\n";
795   result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
796   result += "\n";
797   result += "\n";
798   result += "\nCOMMAND LINE";
799   result += "\n------------";
800   result += "\n";
801   result += "\nStart the launcher process without arguments in order to see all the startup configuration";
802   result += "\n posibilities, many of which could be modified on the air through the management interface";
803   result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
804   result += "\n";
805   result += "\nAs mandatory, the stack definition given through the xml dictionary:";
806   result += "\n   -dictionary <path to dictionary file>";
807   result += "\n";
808   result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
809   result += "\n   -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0";
810   result += "\n";
811   result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
812   result += "\n   -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0";
813   result += "\n";
814   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
815   result += "\n will need to program the answers to be replied through the operations interface. To balance the";
816   result += "\n traffic at your client side you shall use '-balance' and '-sessionBasedModelsClientSocketSelection'";
817   result += "\n arguments in order to define the balancing behaviour.";
818   result += "\n";
819   result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
820   result += "\n customized ones using '-cer <xml message file>' and '-dwr <xml message file>'.";
821   result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
822   result += "\n customized ones using operations interface.";
823   result += "\n";
824   result += "\n";
825   result += "\nDYNAMIC OPERATIONS";
826   result += "\n------------------";
827   result += "\n";
828   result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
829   result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
830   result += "\n separated by pipes. These are the available commands:";
831   result += "\n";
832   result += "\n--------------------------------------------------------------------------------------- General purpose";
833   result += "\n";
834   result += "\nhelp                                 This help. Startup information-level traces also dump this help.";
835   result += "\n";
836   result += "\n------------------------------------------------------------------------------------ Parsing operations";
837   result += "\n";
838   result += "\ncode|<source_file>|<target_file>     Encodes source file (pathfile) into target file (pathfile).";
839   result += "\ndecode|<source_file>|<target_file>   Decodes source file (pathfile) into target file (pathfile).";
840   result += "\nloadxml|<source_file>                Reinterpret xml source file (pathfile).";
841   result += "\n";
842   result += "\n------------------------------------------------------------------------------------------- Hot changes";
843   result += "\n";
844   result += "\ndiameterServerSessions|<integer>     Updates the maximum number of accepted connections to diameter";
845   result += "\n                                      server socket.";
846   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
847   result += "\n                                      performance measurement. Context data is written at";
848   result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
849   result += "\n";
850   result += "\n<visibility action>|[<address>:<port>]|[socket id]";
851   result += "\n";
852   result += "\n       Actions: hide, show (update state) and hidden, shown (query state).";
853   result += "\n       Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
854   result += "\n       If missing server (first parameter) all applications sockets will be affected.";
855   result += "\n       If missing socket (second parameter) for specific server, all its sockets will be affected.";
856   result += "\n";
857   result += "\n       All application client sessions are shown on startup, but standard delivery only use primary";
858   result += "\n        server ones except if fails. Balance configuration use all the allowed sockets. You could also";
859   result += "\n        use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
860   result += "\n        client sessions, but for this, hide/show feature seems easier.";
861   result += "\n";
862   result += "\n--------------------------------------------------------------------------------------- Flow operations";
863   result += "\n";
864   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
865   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
866   result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
867   result += "\nanswerxml2e|[source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
868   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
869   result += "\n                           as many queues as different message codes have been programmed.";
870   result += "\nanswerxml2c|[source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
871   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
872   result += "\n                           as many queues as different message codes have been programmed.";
873   result += "\nanswerxml|[source_file]    Same as 'answerxml2c'.";
874   result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
875   result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
876   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
877   result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
878   result += "\nanswerxml(2e/2c)|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
879   result += "\nanswerxml(2e/2c)|rotate    Enable the corresponding queue rotation, useful in performance tests.";
880   result += "\n                           Rotation consists in add again to the queue, each element retrieved for answering.";
881   result += "\n";
882   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
883   result += "\nspecial scenarios (protocol errors):";
884   result += "\n";
885   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
886   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
887   result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
888   result += "\n";
889   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
890   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
891   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
892   result += "\n";
893   result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
894   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
895   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
896   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
897   result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
898   result += "\n";
899   result += "\nIn the most complete situation (process with both client and server side) there are internally";
900   result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
901   result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
902   result += "\n each one we could program different answers corresponding to different request codes received.";
903   result += "\n";
904   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
905   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
906   result += "\n    use sendxml/sendhex operations better than programming.";
907   result += "\n";
908   result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
909   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
910   result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
911   result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
912   result += "\n";
913   result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
914   result += "\n";
915   result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
916   result += "\n details when unique log file is dumped:";
917   result += "\n";
918   result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
919   result += "\n   [sent2c/send2cError]   Send to client (success/error)";
920   result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
921   result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
922   result += "\n   [recvfc]               Reception from client";
923   result += "\n   [recvfe]               Reception from entity";
924   result += "\n   [req2c-expired]        A request sent to client has been expired";
925   result += "\n   [req2e-expired]        A request sent to entity has been expired";
926   result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
927   result += "\n                           has been logged)";
928   result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
929   result += "\n                           has been logged)";
930   result += "\n";
931   result += "\n-------------------------------------------------------------------------------------------- Load tests";
932   result += "\n";
933   result += "\nburst|<action>|[parameter]     Used for performance testing, we first program diameter requests";
934   result += "\n                                messages in order to launch them from client side to the configured";
935   result += "\n                                diameter entity. We could start the burst with an initial load";
936   result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
937   result += "\n                                per answer received or expired context. There are 10 actions: clear,";
938   result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
939   result += "\n";
940   result += "\n   burst|clear                 Clears all loaded burst messages.";
941   result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
942   result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
943   result += "\n                                a certain initial load.";
944   result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
945   result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
946   result += "\n                               Popping all OTA requests implies burst stop because no more answer";
947   result += "\n                                will arrive to the process. Burst output file (-burstLog command";
948   result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
949   result += "\n                                represents one received answer for which no new request is sent.";
950   result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
951   result += "\n   burst|repeat|[[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
952   result += "\n                                amount is greater than burst list size, they will be limited when";
953   result += "\n                                the list is processed except when repeat mode is enabled.";
954   result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
955   result += "\n                                operations is that burst won't be awaken. Externally we could control";
956   result += "\n                                sending time (no request will be sent for answers).";
957   result += "\n   burst|goto|<order>          Updates current burst pointer position.";
958   result += "\n   burst|look|<order>          Show programmed burst message for order provided.";
959   result += "\n";
960   result += "\n";
961   result += "\nUSING OPERATIONS INTERFACE";
962   result += "\n--------------------------";
963   result += "\n";
964   result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
965   result += "\n";
966   result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
967   result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
968   result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
969   result += "\n using curl client could be:";
970   result += "\n";
971   result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
972   result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
973   result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
974   result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
975   result += "\n   etc.";
976   result += "\n";
977   result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
978   result += "\n";
979   result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
980   result += "\n signal event:";
981   result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
982   result += "\n    then";
983   result += "\n   kill -12 <pid>";
984   result += "\n    or";
985   result += "\n   kill -s SIGUSR2 <pid>";
986   result += "\n    and then see the results:";
987   result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
988   result += "\n";
989   result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
990   result += "\n case over the output file. Take into account that all the content of the task file will be executed";
991   result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
992   result += "\n interface.";
993   result += "\n";
994   result += "\n";
995   return result;
996 }
997
998
999 void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() {
1000   // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request.
1001   // If user wants to test a specific answer without changing it, use send operations better than programming.
1002   // Sequence substitution:
1003   answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request));
1004   answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request));
1005
1006   // Session-Id substitution:
1007   try {
1008     std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request);
1009     LOGDEBUG(
1010       std::string msg = "Extracted Session-Id: ";
1011       msg += sessionId;
1012       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1013     );
1014     answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId);
1015   } catch(anna::RuntimeException &ex) {
1016     ex.trace();
1017   }
1018
1019   // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information,
1020   // then it will be adapted with the received data at request.
1021   if(answer->countAvp("Subscription-Id") > 0) {
1022     std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
1023     std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
1024
1025     if((msisdn != "") || (imsi != "")) {  // Both request & answer have SID: replace answer one with the request information:
1026       answer->removeAvp("Subscription-Id", 0 /* remove all */);
1027     }
1028
1029     // Replacements:
1030     if(msisdn != "") {
1031       anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id");
1032       sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
1033       sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn);
1034     }
1035
1036     if(imsi != "") {
1037       anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another
1038       sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
1039       sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi);
1040     }
1041   }
1042 }
1043
1044 // HTTP
1045 void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message)
1046 throw(anna::RuntimeException) {
1047   LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
1048
1049   if(clientSocket.support(anna::http::Transport::className()) == false)
1050     return;
1051
1052   MyHandler& httpHandler = a_contexts.get();
1053   httpHandler.apply(clientSocket, message);
1054 }
1055
1056 using namespace std;
1057 using namespace anna::diameter;
1058
1059 int main(int argc, const char** argv) {
1060   anna::Logger::setLevel(anna::Logger::Warning);
1061   anna::Logger::initialize("launcher", new TraceWriter("launcher.trace", 2048000));
1062   anna::time::functions::initialize(); // before application instantiation (it have a anna::time object)
1063   anna::time::functions::setControlPoint(); // start control point (application lifetime)
1064   Launcher app;
1065   anna::http::functions::initialize();
1066
1067   try {
1068     CommandLine& commandLine(anna::CommandLine::instantiate());
1069     // General
1070     commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
1071     commandLine.add("log", anna::CommandLine::Argument::Optional, "Process log file (operations result, traffic log, etc.). By default 'launcher.log'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever)");
1072     commandLine.add("splitLog", anna::CommandLine::Argument::Optional, "Splits log file (appends to log filename, extensions with the type of event: see help on startup information-level traces). No log files for code/decode and load operations are created", false);
1073     commandLine.add("detailedLog", anna::CommandLine::Argument::Optional, "Insert detailed information at log files. Should be disabled on automatic tests. Useful on '-balance' mode to know messages flow along the sockets", false);
1074     commandLine.add("dumpLog", anna::CommandLine::Argument::Optional, "Write to disk every incoming/outcoming message named as '<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'", false);
1075     commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample.<concept id>.csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it).");
1076     commandLine.add("burstLog", anna::CommandLine::Argument::Optional, "Burst operations log file. By default 'launcher.burst'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst list size, plus OTA requests when changed.");
1077     commandLine.add("cntDir", anna::CommandLine::Argument::Optional, "Counters directory. By default is the current execution directory. Warning: a counter file will be dump per record period; take care about the possible accumulation of files");
1078     commandLine.add("cntRecordPeriod", anna::CommandLine::Argument::Optional, "Counters record procedure period in milliseconds. If missing, default value of 300000 (5 minutes) will be assigned. Value of 0 disables the record procedure.");
1079     // Communications
1080     commandLine.add("httpServer", anna::CommandLine::Argument::Optional, "HTTP Management interface address (using i.e. curl tool) in '<address>:<port>' format. For example: 10.20.30.40:8080");
1081     commandLine.add("httpServerShared", anna::CommandLine::Argument::Optional, "Enables shared bind for HTTP Management interface address. It would be useful i.e. to allow a great amount of curl operations per second", false);
1082     commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
1083     commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
1084     commandLine.add("entity", anna::CommandLine::Argument::Optional, "Target diameter entity (comma-separated '<address>:<port>' format). For example: 10.20.30.40:3868,10.20.30.41:3868");
1085     commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
1086     commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
1087     commandLine.add("sessionBasedModelsClientSocketSelection", anna::CommandLine::Argument::Optional, "By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied; usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin'.");
1088     commandLine.add("dictionary", anna::CommandLine::Argument::Mandatory, "Diameter dictionary pathfiles (could be one or more ocurrences in a comma separated list, in order to accumulate loads). For example: avps_etsi.xml,avps_ietf.xml,avps_tgpp.xml,commands_qosControl.xml");
1089     commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false);
1090     commandLine.add("ignoreErrors", anna::CommandLine::Argument::Optional, "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", false);
1091     commandLine.add("allowedInactivityTime", anna::CommandLine::Argument::Optional, "Milliseconds for the maximum allowed inactivity time on server sessions born over the local server before being reset. If missing, default value of 90000 will be assigned");
1092     commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
1093     commandLine.add("answersTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait pending application answers from diameter peers. If missing, default value of 10000 will be assigned");
1094     commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
1095     commandLine.add("watchdogPeriod", anna::CommandLine::Argument::Optional, "Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default value of 30000 will be assigned");
1096     commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned");
1097     commandLine.add("cer", anna::CommandLine::Argument::Optional, "Pathfile for the Capabilities Exchange Request xml message. If missing, \"cer.xml\" is searched. If missing again, process creates own CER");
1098     commandLine.add("dwr", anna::CommandLine::Argument::Optional, "Pathfile for the Device Watchdog Request xml message. If missing, \"dwr.xml\" is searched. If missing again, process creates own DWR");
1099     commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
1100     commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
1101     commandLine.add("integrationAndDebugging", anna::CommandLine::Argument::Optional, "Sets validation mode to 'Always' (default validates only after decoding), and validation depth to 'Complete' (default validates until 'FirstError')", false);
1102     commandLine.add("fixMode", anna::CommandLine::Argument::Optional, "Sets message fix mode (unreconized values will assume default 'BeforeEncoding'). Allowed: 'BeforeEncoding', 'AfterDecoding', 'Always', 'Never'");
1103
1104     commandLine.initialize(argv, argc);
1105     commandLine.verify();
1106     std::cout << commandLine.asString() << std::endl;
1107     app.start();
1108   } catch(Exception& ex) {
1109     cout << ex.asString() << endl;
1110   }
1111
1112   return 0;
1113 }
1114
1115 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
1116   a_myDiameterEngine = new MyDiameterEngine();
1117   a_myDiameterEngine->setRealm("ADL.ericsson.com");
1118   a_myDiameterEngine->setAutoBind(false);  // allow to create client-sessions without binding them, in order to set timeouts.
1119   //a_myDiameterEngine->setFreezeEndToEndOnSending();
1120   a_logFile = "launcher.log";
1121   a_burstLogFile = "launcher.burst";
1122   a_splitLog = false;
1123   a_detailedLog = false;
1124   a_dumpLog = false;
1125   a_timeEngine = NULL;
1126   a_counterRecorder = NULL;
1127   a_counterRecorderClock = NULL;
1128   a_entity = NULL;
1129   a_diameterLocalServer = NULL;
1130   a_cerPathfile = "cer.xml";
1131   a_dwrPathfile = "dwr.xml";
1132   // Burst
1133   a_burstCycle = 1;
1134   a_burstRepeat = false;
1135   a_burstActive = false;
1136   //a_burstMessages.clear();
1137   a_burstLoadIndx = 0;
1138   a_burstDeliveryIt = a_burstMessages.begin();
1139   a_otaRequest = 0;
1140   a_burstPopCounter = 0;
1141 }
1142
1143 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
1144   // Build CER
1145   //   <CER> ::= < Diameter Header: 257, REQ >
1146   //             { Origin-Host } 264 diameterIdentity
1147   //             { Origin-Realm } 296 idem
1148   //          1* { Host-IP-Address } 257, address
1149   //             { Vendor-Id } 266 Unsigned32
1150   //             { Product-Name } 269 UTF8String
1151   //             [Origin-State-Id] 278 Unsigned32
1152   //           * [ Supported-Vendor-Id ]  265 Unsigned32
1153   //           * [ Auth-Application-Id ] 258 Unsigned32
1154   //           * [Acct-Application-Id]  259 Unsigned32
1155   anna::diameter::codec::Message diameterCER;
1156   int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1157   std::string OH = a_myDiameterEngine->getHost();
1158   std::string OR = a_myDiameterEngine->getRealm();
1159   std::string hostIP = anna::functions::getHostnameIP(); // Address
1160   int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1161   std::string productName = "ANNA Diameter Launcher"; // UTF8String
1162   bool loadingError = false;
1163
1164   try {
1165     diameterCER.loadXML(a_cerPathfile);
1166   } catch(anna::RuntimeException &ex) {
1167     //ex.trace();
1168     loadingError = true;
1169   }
1170
1171   if(loadingError) {
1172     LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1173     diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1174     diameterCER.setApplicationId(applicationId);
1175     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1176     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1177     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>"
1178     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1179     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1180     diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1181   }
1182
1183   // Build DWR
1184   //   <DWR>  ::= < Diameter Header: 280, REQ >
1185   //              { Origin-Host }
1186   //              { Origin-Realm }
1187   anna::diameter::codec::Message diameterDWR;
1188   loadingError = false;
1189
1190   try {
1191     diameterDWR.loadXML(a_dwrPathfile);
1192   } catch(anna::RuntimeException &ex) {
1193     //ex.trace();
1194     loadingError = true;
1195   }
1196
1197   if(loadingError) {
1198     LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1199     diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1200     diameterDWR.setApplicationId(applicationId);
1201     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1202     diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1203   }
1204
1205 //////////////////////////
1206 // IDEM FOR CEA AND DWA //
1207 //////////////////////////
1208 //            // Build CER
1209 //            //   <CER> ::= < Diameter Header: 257, REQ >
1210 //            //             { Origin-Host } 264 diameterIdentity
1211 //            //             { Origin-Realm } 296 idem
1212 //            //          1* { Host-IP-Address } 257, address
1213 //            //             { Vendor-Id } 266 Unsigned32
1214 //            //             { Product-Name } 269 UTF8String
1215 //            //             [Origin-State-Id] 278 Unsigned32
1216 //            //           * [ Supported-Vendor-Id ]  265 Unsigned32
1217 //            //           * [ Auth-Application-Id ] 258 Unsigned32
1218 //            //           * [Acct-Application-Id]  259 Unsigned32
1219 //            anna::diameter::codec::Message diameterCER;
1220 //            int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1221 //            std::string OH = a_myDiameterEngine->getHost();
1222 //            std::string OR = a_myDiameterEngine->getRealm();
1223 //            std::string hostIP = anna::functions::getHostnameIP(); // Address
1224 //            int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1225 //            std::string productName = "ANNA Diameter Launcher"; // UTF8String
1226 //            bool loadingError = false;
1227 //
1228 //            try {
1229 //               diameterCER.loadXML("cer.xml");
1230 //            } catch (anna::RuntimeException &ex) {
1231 //               ex.trace();
1232 //               loadingError = true;
1233 //            }
1234 //
1235 //            if (loadingError) {
1236 //               LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1237 //               diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1238 //               diameterCER.setApplicationId(applicationId);
1239 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1240 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1241 //               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>"
1242 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1243 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1244 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1245 //            }
1246 //
1247 //            // Build DWR
1248 //            //   <DWR>  ::= < Diameter Header: 280, REQ >
1249 //            //              { Origin-Host }
1250 //            //              { Origin-Realm }
1251 //            anna::diameter::codec::Message diameterDWR;
1252 //            loadingError = false;
1253 //
1254 //            try {
1255 //               diameterDWR.loadXML("dwr.xml");
1256 //            } catch (anna::RuntimeException &ex) {
1257 //               ex.trace();
1258 //               loadingError = true;
1259 //            }
1260 //
1261 //            if (loadingError) {
1262 //               LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1263 //               diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1264 //               diameterDWR.setApplicationId(applicationId);
1265 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1266 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1267 //            }
1268   // Assignment for CER/DWR and CEA/DWA:
1269   a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
1270   //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
1271 }
1272
1273 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
1274 //   if (!logEnabled()) return;
1275
1276   // Decode
1277   try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
1278
1279   writeLogFile(G_codecMsg, logExtension, detail);
1280 }
1281
1282
1283 // Si ya lo tengo decodificado:
1284 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
1285 //   if (!logEnabled()) return;
1286   // Open target file:
1287   std::string targetFile = a_logFile;
1288
1289   if(a_splitLog) {
1290     targetFile += ".";
1291     targetFile += logExtension;
1292   }
1293
1294   ofstream out(targetFile.c_str(), ifstream::out | ifstream::app);
1295   // Set text to dump:
1296   std::string title = "[";
1297   title += logExtension;
1298   title += "]";
1299   // Build complete log:
1300   std::string log = "\n";
1301   std::string xml = decodedMessage.asXMLString();
1302
1303
1304   if(a_detailedLog) {
1305     anna::time::Date now;
1306     now.setNow();
1307     title += " ";
1308     title += now.asString();
1309     log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
1310     log += xml;
1311     log += "\n";
1312     log += anna::functions::highlight("Used resource");
1313     log += detail;
1314     log += "\n";
1315   } else {
1316     log += title;
1317     log += "\n";
1318     log += xml;
1319     log += "\n";
1320   }
1321
1322   if(a_dumpLog) {
1323     std::string name = anna::functions::asString(decodedMessage.getHopByHop());
1324     name += ".";
1325     name += anna::functions::asString(decodedMessage.getEndToEnd());
1326     name += ".";
1327     name += anna::functions::asString(decodedMessage.getId().first);
1328     name += ".";
1329     name += ((decodedMessage.getId().second) ? "request.":"answer.");
1330     name += logExtension;
1331     name += ".xml";
1332     ofstream outMsg(name.c_str(), ifstream::out | ifstream::app);
1333     outMsg.write(xml.c_str(), xml.size());
1334     outMsg.close();
1335   }
1336
1337   // Write and close
1338   out.write(log.c_str(), log.size());
1339   out.close();
1340 }
1341
1342
1343 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
1344   ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app);
1345   out.write(buffer.c_str(), buffer.size());
1346   out.close();    // close() will be called when the object is destructed (i.e., when it goes out of scope).
1347   // you'd call close() only if you indeed for some reason wanted to close the filestream
1348   // earlier than it goes out of scope.
1349 }
1350
1351
1352 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
1353   CommandLine& cl(anna::CommandLine::instantiate());
1354
1355   if(!cl.exists(commandLineParameter) && optional) return;  // start error if mandatory
1356
1357   std::string parameter = cl.getValue(commandLineParameter);
1358
1359   if(anna::functions::isLike("^[0-9]+$", parameter)) {  // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
1360     int msecs = cl.getIntegerValue(commandLineParameter);
1361
1362     if(msecs > a_timeEngine->getMaxTimeout()) {
1363       std::string msg = "Commandline parameter '";
1364       msg += commandLineParameter;
1365       msg += "' is greater than allowed max timeout for timming engine: ";
1366       msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
1367       throw RuntimeException(msg, ANNA_FILE_LOCATION);
1368     }
1369
1370     if(msecs <= a_timeEngine->getResolution()) {
1371       std::string msg = "Commandline parameter '";
1372       msg += commandLineParameter;
1373       msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
1374       msg += anna::functions::asString(a_timeEngine->getResolution());
1375       throw RuntimeException(msg, ANNA_FILE_LOCATION);
1376     }
1377
1378     return; // ok
1379   }
1380
1381   // Excepcion (por no ser entero):
1382   std::string msg = "Error at commandline parameter '";
1383   msg += commandLineParameter;
1384   msg += "' = '";
1385   msg += parameter;
1386   msg += "': must be a non-negative integer number";
1387   throw RuntimeException(msg, ANNA_FILE_LOCATION);
1388 }
1389
1390
1391 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
1392   if(diameterServerSessions <= 0) return;
1393
1394   std::string address;
1395   int port;
1396   CommandLine& cl(anna::CommandLine::instantiate());
1397   anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
1398   //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
1399   a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions);
1400   a_diameterLocalServer->setDescription("Launcher diameter local server");
1401   int allowedInactivityTime = 90000; // ms
1402
1403   if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
1404
1405   a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
1406 }
1407
1408
1409 void Launcher::initialize()
1410 throw(anna::RuntimeException) {
1411   anna::comm::Application::initialize();
1412   CommandLine& cl(anna::CommandLine::instantiate());
1413   anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
1414 //   if (cl.exists ("clone"))
1415 //      workMode = anna::comm::Communicator::WorkMode::Clone;
1416   a_communicator = new MyCommunicator(workMode);
1417   a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
1418   // Counters record procedure:
1419   anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
1420
1421   if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
1422
1423   if(cntRecordPeriod != 0) {
1424     checkTimeMeasure("cntRecordPeriod");
1425     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
1426     std::string cntDir = ".";
1427
1428     if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
1429
1430     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
1431   }
1432 }
1433
1434 void Launcher::run()
1435 throw(anna::RuntimeException) {
1436   LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
1437   CommandLine& cl(anna::CommandLine::instantiate());
1438   // Start time:
1439   a_start_time.setNow();
1440   // Statistics:
1441   anna::statistics::Engine::instantiate().enable();
1442   ///////////////////////////////
1443   // Diameter library COUNTERS //
1444   ///////////////////////////////
1445   anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
1446   oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
1447   anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
1448   oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
1449   /////////////////
1450   // COMM MODULE //
1451   /////////////////
1452   /* Main events */
1453   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
1454   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
1455   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
1456   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
1457   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
1458   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
1459   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
1460   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
1461   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
1462   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
1463   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
1464   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
1465   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
1466   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
1467   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
1468   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
1469   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
1470   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
1471   /* Diameter Base (capabilities exchange & keep alive) */
1472   // as client
1473   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
1474   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
1475   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
1476   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
1477   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
1478   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
1479   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
1480   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
1481   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
1482   // as server
1483   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
1484   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
1485   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
1486   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
1487   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
1488   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
1489   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
1490   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
1491   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
1492   /* server socket operations (enable/disable listening port for any local server) */
1493   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
1494   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
1495   /* Connectivity */
1496   // clients
1497   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
1498   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
1499   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
1500   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
1501   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
1502   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
1503   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
1504   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
1505   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
1506   // servers
1507   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
1508   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
1509   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
1510   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
1511   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
1512   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
1513   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
1514   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
1515   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
1516   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
1517   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
1518   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 58);
1519   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 59);
1520   oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 60);
1521   //////////////////
1522   // CODEC MODULE //
1523   //////////////////
1524   /* Avp decoding */
1525   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
1526   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
1527   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
1528   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
1529   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
1530   /* Message decoding */
1531   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
1532   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
1533   /* Avp validation */
1534   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
1535   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
1536   /* Message validation */
1537   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
1538   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
1539   /* Level validation */
1540   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
1541   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
1542   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
1543   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
1544   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
1545   oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
1546
1547   /////////////////////////////////
1548   // Counter recorder associated //
1549   /////////////////////////////////
1550   if(a_counterRecorderClock) {
1551     oamDiameterComm.setCounterRecorder(a_counterRecorder);
1552     oamDiameterCodec.setCounterRecorder(a_counterRecorder);
1553     a_timeEngine->activate(a_counterRecorderClock); // start clock
1554   }
1555
1556   // Checking command line parameters
1557   if(cl.exists("sessionBasedModelsClientSocketSelection")) {
1558     std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
1559
1560     if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
1561       throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
1562     }
1563   }
1564
1565   // Tracing:
1566   if(cl.exists("trace"))
1567     anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
1568
1569   LOGINFORMATION(
1570     // Help on startup traces:
1571     anna::Logger::information(help(), ANNA_FILE_LOCATION);
1572     // Test messages dtd:
1573     std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
1574     msg += anna::diameter::codec::MessageDTD;
1575     anna::Logger::information(msg, ANNA_FILE_LOCATION);
1576   );
1577
1578   // HTTP Server:
1579   if(cl.exists("httpServer")) {
1580     anna::comm::Network& network = anna::comm::Network::instantiate();
1581     std::string address;
1582     int port;
1583     anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
1584     //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
1585     const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
1586     a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
1587   }
1588
1589   // Stack:
1590   anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
1591   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
1592   anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
1593   // Analyze comma-separated list:
1594   anna::Tokenizer lst;
1595   std::string dictionaryParameter = cl.getValue("dictionary");
1596   lst.apply(dictionaryParameter, ",");
1597
1598   if(lst.size() >= 1) {  // always true (at least one, because -dictionary is mandatory)
1599     anna::Tokenizer::const_iterator tok_min(lst.begin());
1600     anna::Tokenizer::const_iterator tok_max(lst.end());
1601     anna::Tokenizer::const_iterator tok_iter;
1602     std::string pathFile;
1603     d->allowUpdates();
1604
1605     for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1606       pathFile = anna::Tokenizer::data(tok_iter);
1607       d->load(pathFile);
1608     }
1609   }
1610
1611   codecEngine->setDictionary(d);
1612   LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
1613
1614   if(lst.size() > 1) {
1615     std::string all_in_one = "./dictionary-all-in-one.xml";
1616     std::ofstream out(all_in_one.c_str(), std::ifstream::out);
1617     std::string buffer = d->asXMLString();
1618     out.write(buffer.c_str(), buffer.size());
1619     out.close();
1620     std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
1621   }
1622
1623
1624
1625   // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
1626   // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
1627   if(cl.exists("integrationAndDebugging")) {
1628     codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
1629     codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
1630   }
1631
1632   // Fix mode
1633   if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
1634     std::string fixMode = cl.getValue("fixMode");
1635     anna::diameter::codec::Engine::FixMode::_v fm;
1636     if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
1637     else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
1638     else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
1639     else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
1640     else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
1641     codecEngine->setFixMode(fm);
1642   }
1643
1644   codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
1645
1646   // Diameter Server:
1647   if(cl.exists("diameterServer"))
1648     startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
1649
1650   // Optional command line parameters ////////////////////////////////////////////////////////
1651   checkTimeMeasure("allowedInactivityTime");
1652   checkTimeMeasure("tcpConnectDelay");
1653   checkTimeMeasure("answersTimeout");
1654   checkTimeMeasure("ceaTimeout");
1655   checkTimeMeasure("watchdogPeriod");
1656   checkTimeMeasure("reconnectionPeriod");
1657   int tcpConnectDelay = 200; // ms
1658   anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
1659   anna::Millisecond ceaTimeout;
1660   anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
1661   int reconnectionPeriod = 10000; // ms
1662
1663   if(cl.exists("tcpConnectDelay"))         tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
1664
1665   if(cl.exists("answersTimeout"))          answersTimeout = cl.getIntegerValue("answersTimeout");
1666
1667   if(cl.exists("ceaTimeout"))              ceaTimeout = cl.getIntegerValue("ceaTimeout");
1668   else                                      ceaTimeout = answersTimeout;
1669
1670   if(cl.exists("watchdogPeriod"))          watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
1671
1672   if(cl.exists("reconnectionPeriod"))      reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
1673
1674   a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
1675   a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
1676   std::string originHost = "";
1677   std::string originRealm = "";
1678
1679   if(cl.exists("cer"))                  a_cerPathfile = cl.getValue("cer");
1680
1681   if(cl.exists("dwr"))                  a_dwrPathfile = cl.getValue("dwr");
1682
1683   if(cl.exists("originHost"))           originHost = cl.getValue("originHost");
1684
1685   if(cl.exists("originRealm"))          originRealm = cl.getValue("originRealm");
1686
1687   a_myDiameterEngine->setHost(originHost);
1688   a_myDiameterEngine->setRealm(originRealm);
1689
1690   // Diameter entity:
1691   if(cl.exists("entity")) {
1692     int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
1693
1694     if(entityServerSessions > 0) {
1695       baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
1696       anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
1697       a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
1698       a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity");
1699       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
1700       a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
1701       a_entity->bind();
1702     }
1703   }
1704
1705   // Logs
1706   if(cl.exists("log")) a_logFile = cl.getValue("log");
1707
1708   if(cl.exists("splitLog")) a_splitLog = true;
1709
1710   if(cl.exists("detailedLog")) a_detailedLog = true;
1711
1712   if(cl.exists("dumpLog")) a_dumpLog = true;
1713
1714   if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
1715
1716   // Log statistics concepts
1717   if(cl.exists("logStatisticSamples")) {
1718     std::string list = cl.getValue("logStatisticSamples");
1719     anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
1720
1721     if(list == "all") {
1722       if(statEngine.enableSampleLog(/* -1: all concepts */))
1723         LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
1724     } else {
1725       anna::Tokenizer lst;
1726       lst.apply(cl.getValue("logStatisticSamples"), ",");
1727
1728       if(lst.size() >= 1) {
1729         anna::Tokenizer::const_iterator tok_min(lst.begin());
1730         anna::Tokenizer::const_iterator tok_max(lst.end());
1731         anna::Tokenizer::const_iterator tok_iter;
1732         int conceptId;
1733
1734         for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1735           conceptId = atoi(anna::Tokenizer::data(tok_iter));
1736
1737           if(statEngine.enableSampleLog(conceptId))
1738             LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
1739         }
1740       }
1741     }
1742   }
1743
1744   a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
1745
1746   if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket);  // HTTP
1747
1748   a_communicator->accept();
1749 }
1750
1751 void MyCommunicator::eventBreakConnection(Server* server)
1752 throw() {
1753   LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION));
1754   terminate();
1755   anna::comm::Communicator::eventBreakConnection(server);
1756 }
1757
1758 void MyCommunicator::terminate()
1759 throw() {
1760   if(hasRequestedStop() == true)
1761     return;
1762
1763   requestStop();
1764 }
1765
1766 void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request)
1767 throw(anna::RuntimeException) {
1768   const anna::DataBlock& body = request.getBody();
1769
1770   if(body.getSize() == 0)
1771     throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION);
1772
1773   LOGINFORMATION(
1774     string msg("Received body: ");
1775     msg += anna::functions::asString(body);
1776     anna::Logger::information(msg, ANNA_FILE_LOCATION);
1777   );
1778   std::string body_content;
1779   body_content.assign(body.getData(), body.getSize());
1780   // Operation:
1781   std::string response_content;
1782
1783   try {
1784     Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1785     my_app.eventOperation(body_content, response_content);
1786   } catch(RuntimeException &ex) {
1787     ex.trace();
1788   }
1789
1790   anna::http::Response* response = allocateResponse();
1791   response->setStatusCode(200);  // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1792   anna::DataBlock db_content(true);
1793   db_content = response_content;
1794   response->setBody(db_content);
1795 //   response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT");
1796 //   anna::http::Header* keepAlive = response->find("Keep-Alive");
1797 //
1798 //   if (keepAlive == NULL)
1799 //      keepAlive = response->createHeader("Keep-Alive");
1800 //
1801 //   keepAlive->setValue("Verificacion del cambio 1.0.7");
1802
1803   try {
1804     clientSocket.send(*response);
1805   } catch(Exception& ex) {
1806     ex.trace();
1807   }
1808 }
1809
1810 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1811   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1812   CommandLine& cl(anna::CommandLine::instantiate());
1813   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1814   response_content = "Operation processed with exception. See traces\n"; // supposed
1815   std::string result = "";
1816   anna::DataBlock db_aux(true);
1817
1818   ///////////////////////////////////////////////////////////////////
1819   // Simple operations without arguments:
1820
1821   // Help:
1822   if(operation == "help") {
1823     std::string s_help = help();
1824     std::cout << s_help << std::endl;
1825     LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1826     response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n";
1827     return;
1828   }
1829
1830   // Reset performance data:
1831   if(operation == "collect") {
1832     resetCounters();
1833     resetStatistics();
1834     response_content = "All process counters & statistic information have been reset\n";
1835     return;
1836   }
1837
1838   ///////////////////////////////////////////////////////////////////
1839   // Tokenize operation
1840   Tokenizer params;
1841   params.apply(operation, "|");
1842   int numParams = params.size() - 1;
1843
1844   // No operation has more than 2 arguments ...
1845   if(numParams > 2) {
1846     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1847     throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1848   }
1849
1850   // Get the operation type:
1851   Tokenizer::const_iterator tok_iter = params.begin();
1852   std::string opType = Tokenizer::data(tok_iter);
1853   // Check the number of parameters:
1854   bool wrongBody = false;
1855
1856   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1857
1858   if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1859
1860   if((opType == "burst") && (numParams < 1)) wrongBody = true;
1861
1862   if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1863
1864   if(wrongBody) {
1865     // Launch exception
1866     std::string msg = "Wrong body content format on HTTP Request for '";
1867     msg += opType;
1868     msg += "' operation (missing parameter/s)";
1869     throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1870   }
1871
1872   // All seems ok:
1873   std::string param1, param2;
1874
1875   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1876
1877   if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1878
1879   // Operations:
1880   if(opType == "code") {
1881     G_codecMsg.loadXML(param1);
1882     std::string hexString = anna::functions::asHexString(G_codecMsg.code());
1883     // write to outfile
1884     ofstream outfile(param2.c_str(), ifstream::out);
1885     outfile.write(hexString.c_str(), hexString.size());
1886     outfile.close();
1887   } else if(opType == "decode") {
1888     // Get DataBlock from file with hex content:
1889     if(!getDataBlockFromHexFile(param1, db_aux))
1890       throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1891
1892     // Decode
1893     try { G_codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1894
1895     std::string xmlString = G_codecMsg.asXMLString();
1896     // write to outfile
1897     ofstream outfile(param2.c_str(), ifstream::out);
1898     outfile.write(xmlString.c_str(), xmlString.size());
1899     outfile.close();
1900   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1901     anna::diameter::comm::Entity *entity = getEntity();
1902
1903     if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1904
1905     if(param1 != "") {
1906       if(param2 != "") {
1907         std::string key = param1;
1908         key += "|";
1909         key += param2;
1910
1911         if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1912
1913         if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1914
1915         if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1916
1917         if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1918       } else {
1919         std::string address;
1920         int port;
1921         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1922
1923         if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1924
1925         if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1926
1927         if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1928
1929         if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1930       }
1931     } else {
1932       if(opType == "hide") entity->hide();
1933
1934       if(opType == "show") entity->show();
1935
1936       if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1937
1938       if(opType == "shown") result = entity->shown() ? "true" : "false";
1939     }
1940   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1941     anna::diameter::comm::Entity *entity = getEntity();
1942
1943     if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1944
1945     if((opType == "sendxml") || (opType == "sendxml2e")) {
1946       G_codecMsg.loadXML(param1);
1947       G_commMsgSent2e.clearBody();
1948       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
1949
1950       G_commMsgSent2e.setBody(G_codecMsg.code());
1951     } else {
1952       // Get DataBlock from file with hex content:
1953       if(!getDataBlockFromHexFile(param1, db_aux))
1954         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1955
1956       G_commMsgSent2e.setBody(db_aux);
1957     }
1958
1959     bool success = entity->send(G_commMsgSent2e, cl.exists("balance"));
1960
1961     // Detailed log:
1962     if(logEnabled()) {
1963       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1964       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1965       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1966       writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
1967     }
1968   } else if((opType == "burst")) {
1969     anna::diameter::comm::Entity *entity = getEntity();
1970
1971     if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1972
1973     // burst|clear                     clears all loaded burst messages.
1974     // burst|load|<source_file>        loads the next diameter message into launcher burst.
1975     // burst|start|<initial load>      starts the message sending with a certain initial load.
1976     // burst|push|<load amount>        sends specific non-aynchronous load.
1977     // burst|stop                      stops the burst cycle.
1978     // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1979     // burst|send|<amount>             send messages from burst list. The main difference with
1980     //                                 start/push operations is that burst won't be awaken.
1981     //                                 Externally we could control sending time (no request
1982     //                                 will be sent for answers).
1983     // burst|goto|<order>              Updates current burst pointer position.
1984     // burst|look|<order>              Show programmed burst message for order provided.
1985
1986     if(param1 == "clear") {
1987       result = "Removed ";
1988       result += anna::functions::asString(clearBurst());
1989       result += " elements.";
1990     } else if(param1 == "load") {
1991       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1992
1993       G_codecMsg.loadXML(param2);
1994
1995       if(G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1996       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher)
1997
1998       int position = loadBurstMessage(G_codecMsg.code());
1999       result = "Loaded '";
2000       result += param2;
2001       result += "' file into burst list position ";
2002       result += anna::functions::asString(position);
2003     } else if(param1 == "start") {
2004       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
2005
2006       int initialLoad = atoi(param2.c_str());
2007       int processed = startBurst(initialLoad);
2008
2009       if(processed > 0) {
2010         result = "Initial load completed for ";
2011         result += anna::functions::entriesAsString(processed, "message");
2012         result += ".";
2013       }
2014     } else if(param1 == "push") {
2015       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
2016
2017       int pushed = pushBurst(atoi(param2.c_str()));
2018
2019       if(pushed > 0) {
2020         result = "Pushed ";
2021         result += anna::functions::entriesAsString(pushed, "message");
2022         result += ".";
2023       }
2024     } else if(param1 == "pop") {
2025       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
2026
2027       int releaseLoad = atoi(param2.c_str());
2028       int popped = popBurst(releaseLoad);
2029
2030       if(popped > 0) {
2031         result = "Burst popped for ";
2032         result += anna::functions::entriesAsString(popped, "message");
2033         result += ".";
2034       }
2035     } else if(param1 == "stop") {
2036       int left = stopBurst();
2037
2038       if(left != -1) {
2039         result += anna::functions::entriesAsString(left, "message");
2040         result += " left to the end of the cycle.";
2041       }
2042     } else if(param1 == "repeat") {
2043       if(param2 == "") param2 = "yes";
2044
2045       bool repeat = (param2 == "yes");
2046       repeatBurst(repeat);
2047       result += (repeat ? "Mode on." : "Mode off.");
2048     } else if(param1 == "send") {
2049       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
2050
2051       int sent = sendBurst(atoi(param2.c_str()));
2052
2053       if(sent > 0) {
2054         result = "Sent ";
2055         result += anna::functions::entriesAsString(sent, "message");
2056         result += ".";
2057       }
2058     } else if(param1 == "goto") {
2059       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
2060
2061       result = gotoBurst(atoi(param2.c_str()));
2062       result += ".";
2063     } else if(param1 == "look") {
2064       if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
2065
2066       result = "\n\n";
2067       result += lookBurst(atoi(param2.c_str()));
2068       result += "\n\n";
2069     } else {
2070       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
2071     }
2072   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2073     anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
2074
2075     if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
2076
2077     if(opType == "sendxml2c") {
2078       G_codecMsg.loadXML(param1);
2079       G_commMsgSent2c.clearBody();
2080       try { G_codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
2081
2082       G_commMsgSent2c.setBody(G_codecMsg.code());
2083     } else {
2084       // Get DataBlock from file with hex content:
2085       if(!getDataBlockFromHexFile(param1, db_aux))
2086         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
2087
2088       G_commMsgSent2c.setBody(db_aux);
2089     }
2090
2091     bool success = localServer->send(G_commMsgSent2c);
2092
2093     // Detailed log:
2094     if(logEnabled()) {
2095       anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2096       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2097       writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
2098     }
2099   } else if(opType == "loadxml") {
2100     G_codecMsg.loadXML(param1);
2101     std::string xmlString = G_codecMsg.asXMLString();
2102     std::cout << xmlString << std::endl;
2103   } else if(opType == "diameterServerSessions") {
2104     int diameterServerSessions = atoi(param1.c_str());
2105
2106     if(!getDiameterLocalServer())
2107       startDiameterServer(diameterServerSessions);
2108     else
2109       getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
2110   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2111     anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
2112
2113     if(!localServer)
2114       throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
2115
2116     if(param1 == "") { // programmed answers FIFO's to stdout
2117       std::cout << G_reactingAnswers2C.asString("ANSWERS TO CLIENT") << std::endl;
2118       response_content = "Programmed answers dumped on stdout\n";
2119       return;
2120     } else if (param1 == "rotate") {
2121       G_reactingAnswers2C.rotate(true);
2122     } else if (param1 == "exhaust") {
2123       G_reactingAnswers2C.rotate(false);
2124     } else if (param1 == "clear") {
2125       G_reactingAnswers2C.clear();
2126     } else if (param1 == "dump") {
2127       G_reactingAnswers2C.dump();
2128     } else {
2129       anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2130       anna::diameter::codec::Message *message = engine->createMessage(param1);
2131       LOGDEBUG
2132       (
2133         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2134       );
2135
2136       if(message->isRequest())
2137         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2138
2139       int code = message->getId().first;
2140       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2141       G_reactingAnswers2C.addMessage(code, message);
2142     }
2143   } else if(opType == "answerxml2e") {
2144     anna::diameter::comm::Entity *entity = getEntity();
2145
2146     if(!entity)
2147       throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
2148
2149     if(param1 == "") { // programmed answers FIFO's to stdout
2150       std::cout << G_reactingAnswers2E.asString("ANSWERS TO ENTITY") << std::endl;
2151       response_content = "Programmed answers dumped on stdout\n";
2152       return;
2153     } else if (param1 == "rotate") {
2154       G_reactingAnswers2C.rotate(true);
2155     } else if (param1 == "exhaust") {
2156       G_reactingAnswers2C.rotate(false);
2157     } else if (param1 == "clear") {
2158       G_reactingAnswers2E.clear();
2159     } else if (param1 == "dump") {
2160       G_reactingAnswers2E.dump();
2161     } else { 
2162       anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2163       anna::diameter::codec::Message *message = engine->createMessage(param1);
2164       LOGDEBUG
2165       (
2166         anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2167       );
2168
2169       if(message->isRequest())
2170         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2171
2172       int code = message->getId().first;
2173       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
2174       G_reactingAnswers2E.addMessage(code, message);
2175     }
2176   } else {
2177     LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
2178     throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
2179   }
2180
2181   // HTTP response
2182   response_content = "Operation processed; ";
2183
2184   if((opType == "decode") || (opType == "code")) {
2185     response_content += "File '";
2186     response_content += param2;
2187     response_content += "' created.";
2188     response_content += "\n";
2189   } else if((opType == "hide") || (opType == "show")) {
2190     response_content += "Resource '";
2191     response_content += ((param1 != "") ? param1 : "Entity");
2192
2193     if(param2 != "") {
2194       response_content += "|";
2195       response_content += param2;
2196     }
2197
2198     response_content += "' ";
2199
2200     if(opType == "hide") response_content += "has been hidden.";
2201
2202     if(opType == "show") response_content += "has been shown.";
2203
2204     response_content += "\n";
2205   } else if((opType == "hidden") || (opType == "shown")) {
2206     response_content += "Result: ";
2207     response_content += result;
2208     response_content += "\n";
2209   } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
2210     response_content += "Message '";
2211     response_content += param1;
2212     response_content += "' sent to entity.";
2213     response_content += "\n";
2214   } else if(opType == "burst") {
2215     response_content += "Burst '";
2216     response_content += param1;
2217     response_content += "' executed. ";
2218     response_content += result;
2219     response_content += "\n";
2220   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2221     response_content += "Message '";
2222     response_content += param1;
2223     response_content += "' sent to client.";
2224     response_content += "\n";
2225   } else if(opType == "loadxml") {
2226     response_content += "Message '";
2227     response_content += param1;
2228     response_content += "' loaded.";
2229     response_content += "\n";
2230   } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2231     response_content += "Answer to client '";
2232     response_content += param1;
2233     response_content += "' programmed.";
2234     response_content += "\n";
2235   } else if(opType == "answerxml2e") {
2236     response_content += "Answer to entity '";
2237     response_content += param1;
2238     response_content += "' programmed.";
2239     response_content += "\n";
2240   } else if(opType == "diameterServerSessions") {
2241     response_content += "Maximum server socket connections updated to '";
2242     response_content += param1;
2243     response_content += "'.";
2244     response_content += "\n";
2245   }
2246 }
2247
2248
2249 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
2250   CommandLine& cl(anna::CommandLine::instantiate());
2251   std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
2252
2253   if(sessionBasedModelsType == "RoundRobin") return -1;  // IEC also would return -1
2254
2255   try {
2256     // Service-Context-Id:
2257     anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
2258     std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
2259
2260     switch(chargingContext) {
2261     case anna::diameter::helpers::dcca::ChargingContext::Data:
2262     case anna::diameter::helpers::dcca::ChargingContext::Voice:
2263     case anna::diameter::helpers::dcca::ChargingContext::Content: {
2264       // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
2265       std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
2266       std::string diameterIdentity, optional;
2267       anna::U32 high, low;
2268       anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
2269
2270       if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
2271
2272       if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
2273
2274       if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
2275     }
2276     //case anna::diameter::helpers::dcca::ChargingContext::SMS:
2277     //case anna::diameter::helpers::dcca::ChargingContext::MMS:
2278     //default:
2279     //   return -1; // IEC model and Unknown traffic types
2280     }
2281   } catch(anna::RuntimeException &ex) {
2282     LOGDEBUG(
2283       std::string msg = ex.getText();
2284       msg += " | Round-robin between sessions will be used to send";
2285       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2286     );
2287   }
2288
2289   return -1;
2290 }
2291
2292
2293 void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2294 throw(anna::RuntimeException) {
2295   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
2296   // Performance stats:
2297   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2298   CommandLine& cl(anna::CommandLine::instantiate());
2299   // CommandId:
2300   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2301   LOGDEBUG
2302   (
2303     std::string msg = "Request received: ";
2304     msg += anna::diameter::functions::commandIdAsPairString(cid);
2305     msg += " | DiameterServer: ";
2306     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2307     msg += " | EventTime: ";
2308     msg += anna::time::functions::currentTimeAsString();
2309     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2310   );
2311
2312   // Write reception
2313   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
2314
2315   // Lookup reacting answers list:
2316   int code = cid.first;
2317   anna::diameter::codec::Message *answer_message = G_reactingAnswers2E.getMessage(code);
2318   if (answer_message) {
2319     // Prepare answer:
2320     my_app.getCommunicator()->prepareAnswer(answer_message, message);
2321
2322     try {
2323       G_commMsgSent2e.setBody(answer_message->code());
2324       /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
2325
2326       if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
2327     } catch(anna::RuntimeException &ex) {
2328       ex.trace();
2329
2330       if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
2331     }
2332
2333     // Pop front the reacting answer:
2334     G_reactingAnswers2E.nextMessage(code);
2335     return;
2336   }
2337
2338   LOGDEBUG
2339   (
2340     std::string msg = "No answers programmed (maybe sold out) for request coming from entity: ";
2341     msg += anna::diameter::functions::commandIdAsPairString(cid);
2342     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2343   );
2344
2345   // not found: forward to client (if exists)
2346   // Forward to client:
2347   anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2348
2349   if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
2350     try {
2351       anna::diameter::comm::Message *msg = G_commMessages.create();
2352       msg->setBody(message);
2353       msg->setRequestClientSessionKey(clientSession->getKey());
2354       bool success = localServer->send(msg);
2355
2356       // Detailed log:
2357       if(my_app.logEnabled()) {
2358         anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2359         std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2360         my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
2361       }
2362     } catch(anna::RuntimeException &ex) {
2363       ex.trace();
2364     }
2365   }
2366 }
2367
2368
2369 void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response)
2370 throw(anna::RuntimeException) {
2371   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
2372   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2373   CommandLine& cl(anna::CommandLine::instantiate());
2374   anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2375   anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2376   anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2377   const anna::DataBlock* message = response.getMessage();
2378   const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(response.getSession());
2379   bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2380   bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2381   bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2382   bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2383   bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2384   // CommandId:
2385   anna::diameter::CommandId request_cid = request->getCommandId();
2386   LOGDEBUG
2387   (
2388     std::string msg = "Response received for original diameter request: ";
2389     msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2390     msg += " | Response: ";
2391     msg += response.asString();
2392     msg += " | DiameterServer: ";
2393     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2394     msg += " | EventTime: ";
2395     msg += anna::time::functions::currentTimeAsString();
2396     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2397   );
2398
2399   if(isUnavailable) {
2400     //if (isApplicationMessage)
2401     LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION));
2402   }
2403
2404   if(contextExpired) {
2405     //if (isApplicationMessage)
2406     LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
2407
2408     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2409       if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString());
2410     }
2411   }
2412
2413   if(isOK) {
2414     LOGDEBUG(
2415       std::string msg = "Received response for diameter message:  ";
2416       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2417       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2418     );
2419     // Write reception
2420     bool alreadyDecodedOnG_codecMsg = false;
2421
2422     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2423       if(my_app.logEnabled()) {
2424         my_app.writeLogFile(*message, "recvfe", clientSession->asString());
2425         alreadyDecodedOnG_codecMsg = true;
2426       }
2427     }
2428
2429     // Forward to client:
2430     anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2431
2432     if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
2433       try {
2434         G_commMsgFwd2c.setBody(*message);
2435         bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey());
2436         G_commMessages.release(request);
2437         // Detailed log:
2438         anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
2439         std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2440
2441         if(my_app.logEnabled()) {
2442           if(alreadyDecodedOnG_codecMsg)
2443             my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail);
2444           else
2445             my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
2446         }
2447       } catch(anna::RuntimeException &ex) {
2448         ex.trace();
2449       }
2450     }
2451   }
2452
2453   // Triggering burst:
2454   if(isOK || contextExpired) my_app.sendBurstMessage();
2455 }
2456
2457
2458 void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2459 throw(anna::RuntimeException) {
2460   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
2461   // Performance stats:
2462   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2463   // CommandId:
2464   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2465   LOGDEBUG
2466   (
2467     std::string msg = "Out-of-context response received from entity: ";
2468     msg += anna::diameter::functions::commandIdAsPairString(cid);
2469     msg += " | DiameterServer: ";
2470     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2471     msg += " | EventTime: ";
2472     msg += anna::time::functions::currentTimeAsString();
2473     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2474   );
2475
2476   // Write reception
2477   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
2478 }
2479
2480 void MyDiameterEntity::eventDPA(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2481 throw(anna::RuntimeException) {
2482   LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventDPA", ANNA_FILE_LOCATION));
2483   // Performance stats:
2484   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2485   // CommandId:
2486   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2487   LOGDEBUG
2488   (
2489     std::string msg = "Disconnect-Peer-Answer received from entity: ";
2490     msg += anna::diameter::functions::commandIdAsPairString(cid);
2491     msg += " | DiameterServer: ";
2492     msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2493     msg += " | EventTime: ";
2494     msg += anna::time::functions::currentTimeAsString();
2495     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2496   );
2497
2498   // Write reception
2499   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
2500 }
2501
2502 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2503 throw(anna::RuntimeException) {
2504   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
2505   // Performance stats:
2506   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2507   CommandLine& cl(anna::CommandLine::instantiate());
2508   // CommandId:
2509   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2510   LOGDEBUG
2511   (
2512     std::string msg = "Request received: ";
2513     msg += anna::diameter::functions::commandIdAsPairString(cid);
2514     msg += " | DiameterServer: ";
2515     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2516     msg += " | EventTime: ";
2517     msg += anna::time::functions::currentTimeAsString();
2518     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2519   );
2520
2521   // Write reception
2522   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2523
2524   // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
2525   int code = cid.first;
2526   anna::diameter::codec::Message *programmed_answer = G_reactingAnswers2C.getMessage(code);
2527   bool programmed = (programmed_answer != NULL);
2528
2529   anna::diameter::comm::Entity *entity = my_app.getEntity();
2530   if(!programmed && entity) {  // forward condition (no programmed answer + entity available)
2531     anna::diameter::comm::Message *msg = G_commMessages.create();
2532     msg->setBody(message);
2533     msg->setRequestServerSessionKey(serverSession->getKey());
2534     bool success = entity->send(msg, cl.exists("balance"));
2535
2536     // Detailed log:
2537     if(my_app.logEnabled()) {
2538       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
2539       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
2540       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2541       my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
2542     }
2543
2544     return;
2545   }
2546
2547   // Error analisys:
2548   bool analysisOK = true; // by default
2549   anna::diameter::codec::Message *answer_message = NULL;
2550
2551   if(!cl.exists("ignoreErrors")) {  // Error analysis
2552     answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg;
2553     answer_message->clear();
2554
2555     // Decode
2556     try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); }
2557
2558     answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
2559     analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
2560   }
2561
2562   // Programmed answer only when all is ok
2563   if(analysisOK) {
2564     if(programmed) {
2565       answer_message = programmed_answer;
2566       // Prepare answer:
2567       my_app.getCommunicator()->prepareAnswer(answer_message, message);
2568     } else return; // nothing done
2569   }
2570
2571   anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION));
2572   anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
2573
2574   if(!analysisOK)
2575     codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
2576
2577   try {
2578     G_commMsgSent2c.setBody(answer_message->code());
2579     /* response = NULL =*/serverSession->send(&G_commMsgSent2c);
2580
2581     if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
2582   } catch(anna::RuntimeException &ex) {
2583     ex.trace();
2584
2585     if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
2586   }
2587
2588   // Restore validation mode
2589   codecEngine->setValidationMode(backupVM);
2590
2591   // Pop front the reacting answer:
2592   if(analysisOK && programmed) G_reactingAnswers2C.nextMessage(code);
2593 }
2594
2595 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
2596 throw(anna::RuntimeException) {
2597   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
2598   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2599   CommandLine& cl(anna::CommandLine::instantiate());
2600   anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2601   anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2602   anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2603   const anna::DataBlock* message = response.getMessage();
2604   const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
2605   bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2606   bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2607   bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2608   bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2609   bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2610   // CommandId:
2611   anna::diameter::CommandId request_cid = request->getCommandId();
2612   LOGDEBUG
2613   (
2614     std::string msg = "Response received for original diameter request: ";
2615     msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2616     msg += " | Response: ";
2617     msg += response.asString();
2618     msg += " | LocalServer: ";
2619     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2620     msg += " | EventTime: ";
2621     msg += anna::time::functions::currentTimeAsString();
2622     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2623   );
2624
2625   if(isUnavailable) {
2626     //if (isApplicationMessage)
2627     LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
2628   }
2629
2630   if(contextExpired) {
2631     //if (isApplicationMessage)
2632     LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
2633
2634     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
2635       if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString());
2636     }
2637   }
2638
2639   if(isOK) {
2640     LOGDEBUG(
2641       std::string msg = "Received response for diameter message:  ";
2642       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2643       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2644     );
2645
2646     // Write reception
2647     if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString());
2648
2649     // This is not very usual, but answers could arrive from clients:
2650     anna::diameter::comm::Entity *entity = my_app.getEntity();
2651
2652     if(entity) {
2653       anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
2654       std::string detail;
2655
2656       if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>";  // esto no deberia ocurrir
2657
2658       try {
2659         G_commMsgFwd2e.setBody(*message);
2660
2661         // Metodo 1:
2662         if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e);
2663
2664         // Metodo 2:
2665         //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey());
2666         //bool success = entity->send(G_commMsgFwd2e);
2667         G_commMessages.release(request);
2668
2669         if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail);  // forwarded
2670       } catch(anna::RuntimeException &ex) {
2671         ex.trace();
2672
2673         if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail);  // forwarded
2674       }
2675     }
2676   }
2677 }
2678
2679 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2680 throw(anna::RuntimeException) {
2681   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
2682   // Performance stats:
2683   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2684   // CommandId:
2685   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2686   LOGDEBUG
2687   (
2688     std::string msg = "Out-of-context response received from client: ";
2689     msg += anna::diameter::functions::commandIdAsPairString(cid);
2690     msg += " | DiameterServer: ";
2691     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2692     msg += " | EventTime: ";
2693     msg += anna::time::functions::currentTimeAsString();
2694     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2695   );
2696
2697   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
2698 }
2699
2700 void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2701 throw(anna::RuntimeException) {
2702   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION));
2703   // Performance stats:
2704   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2705   // CommandId:
2706   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2707   LOGDEBUG
2708   (
2709     std::string msg = "Disconnect-Peer-Answer response received from client: ";
2710     msg += anna::diameter::functions::commandIdAsPairString(cid);
2711     msg += " | DiameterServer: ";
2712     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2713     msg += " | EventTime: ";
2714     msg += anna::time::functions::currentTimeAsString();
2715     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2716   );
2717
2718   if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2719 }
2720
2721 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2722 throw() {
2723   anna::xml::Node* result = parent->createChild("launcher");
2724   anna::comm::Application::asXML(result);
2725   // Timming:
2726   result->createAttribute("StartTime", a_start_time.asString());
2727   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2728   // Diameter:
2729   (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
2730   // OAM:
2731   anna::diameter::comm::OamModule::instantiate().asXML(result);
2732   anna::diameter::codec::OamModule::instantiate().asXML(result);
2733   // Statistics:
2734   anna::statistics::Engine::instantiate().asXML(result);
2735   return result;
2736 }
2737