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