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