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