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