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