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