033070bfcc95cde4521e956ec17ae91cc73009b6
[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 += "\nSend 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 += "\n";
767    result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
768    result += "\nis intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
769    result += "\nsubscriber id, session id, etc.";
770    result += "\n";
771    result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
772    result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
773    result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
774    result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
775    result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
776    result += "\n";
777    result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
778    result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
779    result += "\n    use sendxml/sendhex operations better than programming.";
780    result += "\n";
781    result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
782    result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
783    result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
784    result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
785    result += "\n";
786    result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
787    result += "\n";
788    result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
789    result += "\n details when unique log file is dumped:";
790    result += "\n";
791    result += "\n   [sent2e/send2eError]   Send to entity (success/error)";
792    result += "\n   [sent2c/send2cError]   Send to client (success/error)";
793    result += "\n   [fwd2e/fwd2eError]     Forward to entity a reception from client (success/error)";
794    result += "\n   [fwd2c/fwd2cError]     Forward to client a reception from entity (success/error)";
795    result += "\n   [recvfc]               Reception from client";
796    result += "\n   [recvfe]               Reception from entity";
797    result += "\n   [req2c-expired]        A request sent to client has been expired";
798    result += "\n   [req2e-expired]        A request sent to entity has been expired";
799    result += "\n   [recvfc-ans-unknown]   Reception from client of an unknown answer (probably former [req2c-expired]";
800    result += "\n                           has been logged)";
801    result += "\n   [recvfe-ans-unknown]   Reception from entity of an unknown answer (probably former [req2e-expired]";
802    result += "\n                           has been logged)";
803    result += "\n";
804    result += "\n-------------------------------------------------------------------------------------------- Load tests";
805    result += "\n";
806    result += "\nburst|<action>|[parameter]     Used for performance testing, we first program diameter requests";
807    result += "\n                                messages in order to launch them from client side to the configured";
808    result += "\n                                diameter entity. We could start the burst with an initial load";
809    result += "\n                                (non-asynchronous sending), after this, a new request will be sent";
810    result += "\n                                per answer received or expired context. There are 10 actions: clear,";
811    result += "\n                                load, start, push, pop, stop, repeat, send, goto and look.";
812    result += "\n";
813    result += "\n   burst|clear                 Clears all loaded burst messages.";
814    result += "\n   burst|load|<source_file>    Loads the next diameter message into launcher burst.";
815    result += "\n   burst|start|<initial load>  Starts (or restarts if already in progress) the message sending with";
816    result += "\n                                a certain initial load.";
817    result += "\n   burst|push|<load amount>    Sends specific non-aynchronous load.";
818    result += "\n   burst|pop|<release amount>  Skip send burst messages in order to reduce over-the-air requests.";
819    result += "\n                               Popping all OTA requests implies burst stop because no more answer";
820    result += "\n                                will arrive to the process. Burst output file (-burstLog command";
821    result += "\n                                line parameter) shows popped messages with crosses (x). Each cross";
822    result += "\n                                represents one received answer for which no new request is sent.";
823    result += "\n   burst|stop                  Stops the burst cycle. You can resume pushing 1 load amount.";
824    result += "\n   burst|repeat|[[yes]|no]     Restarts the burst launch when finish. If initial load or push load";
825    result += "\n                                amount is greater than burst list size, they will be limited when";
826    result += "\n                                the list is processed except when repeat mode is enabled.";
827    result += "\n   burst|send|<amount>         Sends messages from burst list. The main difference with start/push";
828    result += "\n                                operations is that burst won't be awaken. Externally we could control";
829    result += "\n                                sending time (no request will be sent for answers).";
830    result += "\n   burst|goto|<order>          Updates current burst pointer position.";
831    result += "\n   burst|look|<order>          Show programmed burst message for order provided.";
832    result += "\n";
833    result += "\n";
834    result += "\nUSING OPERATIONS INTERFACE";
835    result += "\n--------------------------";
836    result += "\n";
837    result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
838    result += "\n";
839    result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
840    result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
841    result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
842    result += "\n using curl client could be:";
843    result += "\n";
844    result += "\n   curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
845    result += "\n   curl -m 1 --data \"code|ccr.xml\" localhost:9000";
846    result += "\n   curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
847    result += "\n   curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
848    result += "\n   etc.";
849    result += "\n";
850    result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
851    result += "\n";
852    result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
853    result += "\n signal event:";
854    result += "\n   echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
855    result += "\n    then";
856    result += "\n   kill -12 <pid>";
857    result += "\n    or";
858    result += "\n   kill -s SIGUSR2 <pid>";
859    result += "\n    and then see the results:";
860    result += "\n   cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
861    result += "\n";
862    result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
863    result += "\n case over the output file. Take into account that all the content of the task file will be executed";
864    result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
865    result += "\n interface.";
866    result += "\n";
867    result += "\n";
868
869    return result;
870 }
871
872
873 std::string Launcher::programmedAnswers2c() const throw() {
874    std::string result = "\n";
875    result += "\n          ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n";
876
877    if (G_reactingAnswers2C.size() == 0) {
878       result += "No ocurrences found\n\n";
879    } else {
880       for (reacting_answers_const_iterator it = G_reactingAnswers2C.begin(); it != G_reactingAnswers2C.end(); it++) {
881          result += (*it).second->asXMLString();
882          result += "\n\n";
883       }
884    }
885
886    return result;
887 }
888
889
890 std::string Launcher::programmedAnswers2e() const throw() {
891    std::string result = "\n";
892    result += "\n\n          ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n";
893
894    if (G_reactingAnswers2E.size() == 0) {
895       result += "No ocurrences found\n\n";
896    } else {
897       for (reacting_answers_const_iterator it = G_reactingAnswers2E.begin(); it != G_reactingAnswers2E.end(); it++) {
898          result += (*it).second->asXMLString();
899          result += "\n\n";
900       }
901    }
902
903    return result;
904 }
905
906 void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() {
907    // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request.
908    // If user wants to test a specific answer without changing it, use send operations better than programming.
909    // Sequence substitution:
910    answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request));
911    answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request));
912
913    // Session-Id substitution:
914    try {
915       std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request);
916       LOGDEBUG(
917          std::string msg = "Extracted Session-Id: ";
918          msg += sessionId;
919          anna::Logger::debug(msg, ANNA_FILE_LOCATION);
920       );
921       answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId);
922    } catch (anna::RuntimeException &ex) {
923       ex.trace();
924    }
925
926    // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information,
927    // then it will be adapted with the received data at request.
928    if (answer->countAvp("Subscription-Id") > 0) {
929       std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
930       std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
931
932       if ((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information:
933          answer->removeAvp("Subscription-Id", 0 /* remove all */);
934       }
935
936       // Replacements:
937       if (msisdn != "") {
938          anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id");
939          sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
940          sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn);
941       }
942
943       if (imsi != "") {
944          anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another
945          sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
946          sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi);
947       }
948    }
949 }
950
951 // HTTP
952 void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message)
953 throw(anna::RuntimeException) {
954    LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
955
956    if (clientSocket.support(anna::http::Transport::className()) == false)
957       return;
958
959    MyHandler& httpHandler = a_contexts.get();
960    httpHandler.apply(clientSocket, message);
961 }
962
963 using namespace std;
964 using namespace anna::diameter;
965
966 int main(int argc, const char** argv) {
967    anna::Logger::setLevel(anna::Logger::Warning);
968    anna::Logger::initialize("launcher", new TraceWriter("launcher.traces", 2048000));
969    anna::time::functions::initialize(); // before application instantiation (it have a anna::time object)
970    anna::time::functions::setControlPoint(); // start control point (application lifetime)
971    Launcher app;
972    anna::http::functions::initialize();
973
974    try {
975       CommandLine& commandLine(anna::CommandLine::instantiate());
976       // General
977       commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
978       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)");
979       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);
980       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);
981       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).");
982       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.");
983       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");
984       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.");
985       // Communications
986       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");
987       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);
988       commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
989       commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
990       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");
991       commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
992       commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
993       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'.");
994       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");
995       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);
996       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);
997       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");
998       commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
999       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");
1000       commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
1001       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");
1002       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");
1003       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");
1004       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");
1005       commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
1006       commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
1007       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);
1008 //      commandLine.add("clone", anna::CommandLine::Argument::Optional, "Enables fork mode for request processing", false);
1009       commandLine.initialize(argv, argc);
1010       commandLine.verify();
1011       std::cout << commandLine.asString() << std::endl;
1012       app.start();
1013    } catch (Exception& ex) {
1014       cout << ex.asString() << endl;
1015    }
1016
1017    return 0;
1018 }
1019
1020 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
1021    a_myDiameterEngine = new MyDiameterEngine();
1022    a_myDiameterEngine->setRealm("ADL.ericsson.com");
1023    a_myDiameterEngine->setAutoBind(false);  // allow to create client-sessions without binding them, in order to set timeouts.
1024    //a_myDiameterEngine->setFreezeEndToEndOnSending();
1025    a_logFile = "launcher.log";
1026    a_burstLogFile = "launcher.burst";
1027    a_splitLog = false;
1028    a_detailedLog = false;
1029    a_timeEngine = NULL;
1030    a_counterRecorder = NULL;
1031    a_counterRecorderClock = NULL;
1032    a_entity = NULL;
1033    a_diameterLocalServer = NULL;
1034    a_cerPathfile = "cer.xml";
1035    a_dwrPathfile = "dwr.xml";
1036    // Burst
1037    a_burstCycle = 1;
1038    a_burstRepeat = false;
1039    a_burstActive = false;
1040    //a_burstMessages.clear();
1041    a_burstLoadIndx = 0;
1042    a_burstDeliveryIt = a_burstMessages.begin();
1043    a_otaRequest = 0;
1044    a_burstPopCounter = 0;
1045 }
1046
1047 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
1048    // Build CER
1049    //   <CER> ::= < Diameter Header: 257, REQ >
1050    //             { Origin-Host } 264 diameterIdentity
1051    //             { Origin-Realm } 296 idem
1052    //          1* { Host-IP-Address } 257, address
1053    //             { Vendor-Id } 266 Unsigned32
1054    //             { Product-Name } 269 UTF8String
1055    //             [Origin-State-Id] 278 Unsigned32
1056    //           * [ Supported-Vendor-Id ]  265 Unsigned32
1057    //           * [ Auth-Application-Id ] 258 Unsigned32
1058    //           * [Acct-Application-Id]  259 Unsigned32
1059    anna::diameter::codec::Message diameterCER;
1060    int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1061    std::string OH = a_myDiameterEngine->getHost();
1062    std::string OR = a_myDiameterEngine->getRealm();
1063    std::string hostIP = anna::functions::getHostnameIP(); // Address
1064    int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1065    std::string productName = "ANNA Diameter Launcher"; // UTF8String
1066    bool loadingError = false;
1067
1068    try {
1069       diameterCER.loadXML(a_cerPathfile);
1070    } catch (anna::RuntimeException &ex) {
1071       //ex.trace();
1072       loadingError = true;
1073    }
1074
1075    if (loadingError) {
1076       LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1077       diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1078       diameterCER.setApplicationId(applicationId);
1079       diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1080       diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1081       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>"
1082       diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1083       diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1084       diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1085    }
1086
1087    // Build DWR
1088    //   <DWR>  ::= < Diameter Header: 280, REQ >
1089    //              { Origin-Host }
1090    //              { Origin-Realm }
1091    anna::diameter::codec::Message diameterDWR;
1092    loadingError = false;
1093
1094    try {
1095       diameterDWR.loadXML(a_dwrPathfile);
1096    } catch (anna::RuntimeException &ex) {
1097       //ex.trace();
1098       loadingError = true;
1099    }
1100
1101    if (loadingError) {
1102       LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1103       diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1104       diameterDWR.setApplicationId(applicationId);
1105       diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1106       diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1107    }
1108
1109 //////////////////////////
1110 // IDEM FOR CEA AND DWA //
1111 //////////////////////////
1112 //            // Build CER
1113 //            //   <CER> ::= < Diameter Header: 257, REQ >
1114 //            //             { Origin-Host } 264 diameterIdentity
1115 //            //             { Origin-Realm } 296 idem
1116 //            //          1* { Host-IP-Address } 257, address
1117 //            //             { Vendor-Id } 266 Unsigned32
1118 //            //             { Product-Name } 269 UTF8String
1119 //            //             [Origin-State-Id] 278 Unsigned32
1120 //            //           * [ Supported-Vendor-Id ]  265 Unsigned32
1121 //            //           * [ Auth-Application-Id ] 258 Unsigned32
1122 //            //           * [Acct-Application-Id]  259 Unsigned32
1123 //            anna::diameter::codec::Message diameterCER;
1124 //            int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1125 //            std::string OH = a_myDiameterEngine->getHost();
1126 //            std::string OR = a_myDiameterEngine->getRealm();
1127 //            std::string hostIP = anna::functions::getHostnameIP(); // Address
1128 //            int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1129 //            std::string productName = "ANNA Diameter Launcher"; // UTF8String
1130 //            bool loadingError = false;
1131 //
1132 //            try {
1133 //               diameterCER.loadXML("cer.xml");
1134 //            } catch (anna::RuntimeException &ex) {
1135 //               ex.trace();
1136 //               loadingError = true;
1137 //            }
1138 //
1139 //            if (loadingError) {
1140 //               LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1141 //               diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1142 //               diameterCER.setApplicationId(applicationId);
1143 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1144 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1145 //               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>"
1146 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1147 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1148 //               diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1149 //            }
1150 //
1151 //            // Build DWR
1152 //            //   <DWR>  ::= < Diameter Header: 280, REQ >
1153 //            //              { Origin-Host }
1154 //            //              { Origin-Realm }
1155 //            anna::diameter::codec::Message diameterDWR;
1156 //            loadingError = false;
1157 //
1158 //            try {
1159 //               diameterDWR.loadXML("dwr.xml");
1160 //            } catch (anna::RuntimeException &ex) {
1161 //               ex.trace();
1162 //               loadingError = true;
1163 //            }
1164 //
1165 //            if (loadingError) {
1166 //               LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1167 //               diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1168 //               diameterDWR.setApplicationId(applicationId);
1169 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1170 //               diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1171 //            }
1172    // Assignment for CER/DWR and CEA/DWA:
1173    a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
1174    //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
1175 }
1176
1177 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
1178 //   if (!logEnabled()) return;
1179
1180    // Decode
1181    try { G_codecMsg.decode(db); } catch (anna::RuntimeException &ex) { ex.trace(); }
1182
1183    writeLogFile(G_codecMsg, logExtension, detail);
1184 }
1185
1186
1187 // Si ya lo tengo decodificado:
1188 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
1189 //   if (!logEnabled()) return;
1190    // Open target file:
1191    std::string targetFile = a_logFile;
1192
1193    if (a_splitLog) {
1194       targetFile += ".";
1195       targetFile += logExtension;
1196    }
1197
1198    ofstream out(targetFile.c_str(), ifstream::out | ifstream::app);
1199    // Set text to dump:
1200    std::string title = "[";
1201    title += logExtension;
1202    title += "]";
1203    // Build complete log:
1204    std::string log = "\n";
1205
1206    if (a_detailedLog) {
1207       anna::time::Date now;
1208       now.setNow();
1209       title += " ";
1210       title += now.asString();
1211       log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
1212       log += decodedMessage.asXMLString();
1213       log += "\n";
1214       log += anna::functions::highlight("Used resource");
1215       log += detail;
1216       log += "\n";
1217    } else {
1218       log += title;
1219       log += "\n";
1220       log += decodedMessage.asXMLString();
1221       log += "\n";
1222    }
1223
1224    // Write and close
1225    out.write(log.c_str(), log.size());
1226    out.close();
1227 }
1228
1229
1230 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
1231    ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app);
1232    out.write(buffer.c_str(), buffer.size());
1233    out.close();    // close() will be called when the object is destructed (i.e., when it goes out of scope).
1234    // you'd call close() only if you indeed for some reason wanted to close the filestream
1235    // earlier than it goes out of scope.
1236 }
1237
1238
1239 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
1240    CommandLine& cl(anna::CommandLine::instantiate());
1241
1242    if (!cl.exists(commandLineParameter) && optional) return; // start error if mandatory
1243
1244    std::string parameter = cl.getValue(commandLineParameter);
1245
1246    if (anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
1247       int msecs = cl.getIntegerValue(commandLineParameter);
1248
1249       if (msecs > a_timeEngine->getMaxTimeout()) {
1250          std::string msg = "Commandline parameter '";
1251          msg += commandLineParameter;
1252          msg += "' is greater than allowed max timeout for timming engine: ";
1253          msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
1254          throw RuntimeException(msg, ANNA_FILE_LOCATION);
1255       }
1256
1257       if (msecs <= a_timeEngine->getResolution()) {
1258          std::string msg = "Commandline parameter '";
1259          msg += commandLineParameter;
1260          msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
1261          msg += anna::functions::asString(a_timeEngine->getResolution());
1262          throw RuntimeException(msg, ANNA_FILE_LOCATION);
1263       }
1264
1265       return; // ok
1266    }
1267
1268    // Excepcion (por no ser entero):
1269    std::string msg = "Error at commandline parameter '";
1270    msg += commandLineParameter;
1271    msg += "' = '";
1272    msg += parameter;
1273    msg += "': must be a non-negative integer number";
1274    throw RuntimeException(msg, ANNA_FILE_LOCATION);
1275 }
1276
1277
1278 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
1279    if (diameterServerSessions <= 0) return;
1280
1281    std::string address;
1282    int port;
1283    CommandLine& cl(anna::CommandLine::instantiate());
1284    anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
1285    //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
1286    a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions);
1287    a_diameterLocalServer->setDescription("Launcher diameter local server");
1288    int allowedInactivityTime = 90000; // ms
1289
1290    if (cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
1291
1292    a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
1293 }
1294
1295
1296 void Launcher::initialize()
1297 throw(anna::RuntimeException) {
1298    anna::comm::Application::initialize();
1299    CommandLine& cl(anna::CommandLine::instantiate());
1300    anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
1301 //   if (cl.exists ("clone"))
1302 //      workMode = anna::comm::Communicator::WorkMode::Clone;
1303    a_communicator = new MyCommunicator(workMode);
1304    a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
1305
1306   // Counters record procedure:
1307   anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
1308   if (cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
1309   if (cntRecordPeriod != 0) {
1310     checkTimeMeasure("cntRecordPeriod");
1311     a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
1312
1313     std::string cntDir = ".";
1314     if (cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
1315     a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
1316   }
1317 }
1318
1319 void Launcher::run()
1320 throw(anna::RuntimeException) {
1321    LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
1322    CommandLine& cl(anna::CommandLine::instantiate());
1323    // Start time:
1324    a_start_time.setNow();
1325    // Statistics:
1326    anna::statistics::Engine::instantiate().enable();
1327    ///////////////////////////////
1328    // Diameter library COUNTERS //
1329    ///////////////////////////////
1330    anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
1331    oamDiameterComm.initializeCounterScope(1);  // 1000 - 1999
1332    anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
1333    oamDiameterCodec.initializeCounterScope(2);  // 2000 - 2999
1334
1335    /////////////////
1336    // COMM MODULE //
1337    /////////////////
1338    /* Main events */
1339    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
1340    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived,                 "", 1 /*1001*/);
1341    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
1342    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession,  "", 3 /*1003*/);
1343    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
1344    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession,  "", 5);
1345    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK,                  "", 6);
1346    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK,                 "", 7);
1347    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK,                   "", 8);
1348    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK,                  "", 9);
1349    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK,   "", 10);
1350    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK,  "", 11);
1351    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK,    "", 12);
1352    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK,   "", 13);
1353    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK,   "", 14);
1354    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK,  "", 15);
1355    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK,    "", 16);
1356    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK,   "", 17);
1357    /* Diameter Base (capabilities exchange & keep alive) */
1358    // as client
1359    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK,   "", 18);
1360    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK,  "", 19);
1361    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
1362    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK,   "", 21);
1363    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK,  "", 22);
1364    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
1365    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK,   "", 24);
1366    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK,  "", 25);
1367    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
1368    // as server
1369    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
1370    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK,   "", 28);
1371    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK,  "", 29);
1372    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
1373    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK,   "", 31);
1374    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK,  "", 32);
1375    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
1376    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK,   "", 34);
1377    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK,  "", 35);
1378    /* server socket operations (enable/disable listening port for any local server) */
1379    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
1380    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
1381    /* Connectivity */
1382    // clients
1383    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity,                  "", 38);
1384    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession,          "", 39);
1385    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession,     "", 40);
1386    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer,                 "", 41);
1387    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer,            "", 42);
1388    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity,                 "", 43);
1389    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity,            "", 44);
1390    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities,      "", 45);
1391    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
1392    // servers
1393    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient,                                    "", 47);
1394    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession,                             "", 48);
1395    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
1396    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession,                          "", 50);
1397    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer,                            "", 51);
1398    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer,                       "", 52);
1399    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers,                  "", 53);
1400    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers,             "", 54);
1401    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired,  "", 55);
1402    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired,  "", 56);
1403    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired,  "", 57);
1404    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown,  "", 58);
1405    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown,  "", 59);
1406    oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown,  "", 60);
1407    //////////////////
1408    // CODEC MODULE //
1409    //////////////////
1410    /* Avp decoding */
1411    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength,                          "", 0 /*2000*/);
1412    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
1413    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength,                                               "", 2 /*2002*/);
1414    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence,                                         "", 3 /*2003*/);
1415    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit,                                    "", 4 /*2004*/);
1416    /* Message decoding */
1417    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
1418    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength,       "", 6 /*2006*/);
1419    /* Avp validation */
1420    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
1421    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules,      "", 11 /*2011*/);
1422    /* Message validation */
1423    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
1424    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags,     "", 13 /*2013*/);
1425    /* Level validation */
1426    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule,                                       "", 14 /*2014*/);
1427    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality,                               "", 15 /*2015*/);
1428    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded,                 "", 16 /*2016*/);
1429    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded,                 "", 17 /*2017*/);
1430    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
1431    oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified,      "", 19 /*2019*/);
1432
1433    /////////////////////////////////
1434    // Counter recorder associated //
1435    /////////////////////////////////
1436    if (a_counterRecorderClock) {
1437      oamDiameterComm.setCounterRecorder(a_counterRecorder);
1438      oamDiameterCodec.setCounterRecorder(a_counterRecorder);
1439      a_timeEngine->activate(a_counterRecorderClock); // start clock
1440    }
1441
1442    // Checking command line parameters
1443    if (cl.exists("sessionBasedModelsClientSocketSelection")) {
1444       std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
1445
1446       if ((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
1447          throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
1448       }
1449    }
1450
1451    // Tracing:
1452    if (cl.exists("trace"))
1453       anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
1454
1455    LOGINFORMATION(
1456       // Help on startup traces:
1457       anna::Logger::information(help(), ANNA_FILE_LOCATION);
1458       // Test messages dtd:
1459       std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
1460       msg += anna::diameter::codec::MessageDTD;
1461       anna::Logger::information(msg, ANNA_FILE_LOCATION);
1462    );
1463    // HTTP Server:
1464    if (cl.exists("httpServer")) {
1465      anna::comm::Network& network = anna::comm::Network::instantiate();
1466      std::string address;
1467      int port;
1468      anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
1469      //const anna::comm::Device* device = network.find(Device::asAddress(address)); // aqui hay que proporcionar una IP !
1470      const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // Artimaña para resolver (IP o hostname)
1471      a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
1472    }
1473
1474    // Stack:
1475    anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
1476    anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
1477
1478    try {
1479       anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id */);
1480       // Analyze comma-separated list:
1481       anna::Tokenizer lst;
1482       std::string dictionaryParameter = cl.getValue("dictionary");
1483       lst.apply(dictionaryParameter, ",");
1484
1485       if (lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
1486          anna::Tokenizer::const_iterator tok_min(lst.begin());
1487          anna::Tokenizer::const_iterator tok_max(lst.end());
1488          anna::Tokenizer::const_iterator tok_iter;
1489          std::string pathFile;
1490          d->allowUpdates();
1491
1492          for (tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1493             pathFile = anna::Tokenizer::data(tok_iter);
1494             d->load(pathFile);
1495          }
1496       }
1497
1498       codecEngine->setDictionary(d);
1499       LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
1500    } catch (anna::RuntimeException &ex) {
1501       ex.trace();
1502    }
1503
1504    // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
1505    // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
1506    if (cl.exists("integrationAndDebugging")) {
1507       codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
1508       codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
1509    }
1510
1511    codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
1512
1513    // Diameter Server:
1514    if (cl.exists("diameterServer"))
1515       startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
1516
1517    // Optional command line parameters ////////////////////////////////////////////////////////
1518    checkTimeMeasure("allowedInactivityTime");
1519    checkTimeMeasure("tcpConnectDelay");
1520    checkTimeMeasure("answersTimeout");
1521    checkTimeMeasure("ceaTimeout");
1522    checkTimeMeasure("watchdogPeriod");
1523    checkTimeMeasure("reconnectionPeriod");
1524    int tcpConnectDelay = 200; // ms
1525    anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
1526    anna::Millisecond ceaTimeout;
1527    anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
1528    int reconnectionPeriod = 10000; // ms
1529
1530    if (cl.exists("tcpConnectDelay"))         tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
1531
1532    if (cl.exists("answersTimeout"))          answersTimeout = cl.getIntegerValue("answersTimeout");
1533
1534    if (cl.exists("ceaTimeout"))              ceaTimeout = cl.getIntegerValue("ceaTimeout");
1535    else                                      ceaTimeout = answersTimeout;
1536
1537    if (cl.exists("watchdogPeriod"))          watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
1538
1539    if (cl.exists("reconnectionPeriod"))      reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
1540
1541    a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
1542    a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
1543    std::string originHost = "";
1544    std::string originRealm = "";
1545
1546    if (cl.exists("cer"))                  a_cerPathfile = cl.getValue("cer");
1547
1548    if (cl.exists("dwr"))                  a_dwrPathfile = cl.getValue("dwr");
1549
1550    if (cl.exists("originHost"))           originHost = cl.getValue("originHost");
1551
1552    if (cl.exists("originRealm"))          originRealm = cl.getValue("originRealm");
1553
1554    a_myDiameterEngine->setHost(originHost);
1555    a_myDiameterEngine->setRealm(originRealm);
1556
1557    // Diameter entity:
1558    if (cl.exists("entity")) {
1559       int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
1560
1561       if (entityServerSessions > 0) {
1562          baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
1563          anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
1564          a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
1565          a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity");
1566          a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
1567          a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
1568          a_entity->bind();
1569       }
1570    }
1571
1572    // Logs
1573    if (cl.exists("log")) a_logFile = cl.getValue("log");
1574
1575    if (cl.exists("splitLog")) a_splitLog = true;
1576
1577    if (cl.exists("detailedLog")) a_detailedLog = true;
1578
1579    if (cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
1580
1581    // Log statistics concepts
1582    if (cl.exists("logStatisticSamples")) {
1583       std::string list = cl.getValue("logStatisticSamples");
1584       anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
1585
1586       if (list == "all") {
1587          if (statEngine.enableSampleLog(/* -1: all concepts */))
1588             LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
1589       } else {
1590          anna::Tokenizer lst;
1591          lst.apply(cl.getValue("logStatisticSamples"), ",");
1592
1593          if (lst.size() >= 1) {
1594             anna::Tokenizer::const_iterator tok_min(lst.begin());
1595             anna::Tokenizer::const_iterator tok_max(lst.end());
1596             anna::Tokenizer::const_iterator tok_iter;
1597             int conceptId;
1598
1599             for (tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1600                conceptId = atoi(anna::Tokenizer::data(tok_iter));
1601
1602                if (statEngine.enableSampleLog(conceptId))
1603                   LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
1604             }
1605          }
1606       }
1607    }
1608
1609    a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
1610    if (cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
1611    a_communicator->accept();
1612 }
1613
1614 void MyCommunicator::eventBreakConnection(Server* server)
1615 throw() {
1616    LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION));
1617    terminate();
1618    anna::comm::Communicator::eventBreakConnection(server);
1619 }
1620
1621 void MyCommunicator::terminate()
1622 throw() {
1623    if (hasRequestedStop() == true)
1624       return;
1625
1626    requestStop();
1627 }
1628
1629 void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request)
1630 throw(anna::RuntimeException) {
1631    const anna::DataBlock& body = request.getBody();
1632
1633    if (body.getSize() == 0)
1634       throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION);
1635
1636    LOGINFORMATION(
1637       string msg("Received body: ");
1638       msg += anna::functions::asString(body);
1639       anna::Logger::information(msg, ANNA_FILE_LOCATION);
1640    );
1641    std::string body_content;
1642    body_content.assign(body.getData(), body.getSize());
1643    // Operation:
1644    std::string response_content;
1645
1646    try {
1647       Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1648       my_app.eventOperation(body_content, response_content);
1649    } catch (RuntimeException &ex) {
1650       ex.trace();
1651    }
1652
1653    anna::http::Response* response = allocateResponse();
1654    response->setStatusCode(200);  // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1655    anna::DataBlock db_content(true);
1656    db_content = response_content;
1657    response->setBody(db_content);
1658 //   response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT");
1659 //   anna::http::Header* keepAlive = response->find("Keep-Alive");
1660 //
1661 //   if (keepAlive == NULL)
1662 //      keepAlive = response->createHeader("Keep-Alive");
1663 //
1664 //   keepAlive->setValue("Verificacion del cambio 1.0.7");
1665
1666    try {
1667       clientSocket.send(*response);
1668    } catch (Exception& ex) {
1669       ex.trace();
1670    }
1671 }
1672
1673 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1674    LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1675    CommandLine& cl(anna::CommandLine::instantiate());
1676    LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1677    response_content = "Operation processed with exception. See traces\n"; // supposed
1678    std::string result = "";
1679    anna::DataBlock db_aux(true);
1680
1681    ///////////////////////////////////////////////////////////////////
1682    // Simple operations without arguments:
1683
1684    // Help:
1685    if (operation == "help") {
1686       std::string s_help = help();
1687       std::cout << s_help << std::endl;
1688       LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1689       response_content = "Help dumped on stdout and information-level traces (launcher.traces file)\n";
1690       return;
1691    }
1692
1693    // Reset performance data:
1694    if (operation == "collect") {
1695       resetCounters();
1696       resetStatistics();
1697       response_content = "All process counters & statistic information have been reset\n";
1698       return;
1699    }
1700    ///////////////////////////////////////////////////////////////////
1701
1702    // Tokenize operation
1703    Tokenizer params;
1704    params.apply(operation, "|");
1705    int numParams = params.size() - 1;
1706
1707    // No operation has more than 2 arguments ...
1708    if (numParams > 2) {
1709       LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1710       throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1711    }
1712
1713    // Get the operation type:
1714    Tokenizer::const_iterator tok_iter = params.begin();
1715    std::string opType = Tokenizer::data(tok_iter);
1716
1717    // Check the number of parameters:
1718    bool wrongBody = false;
1719    if ( ((opType == "code")||(opType == "decode")) && (numParams != 2) ) wrongBody = true;
1720    if ( ((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1) ) wrongBody = true;
1721    if ( (opType == "burst") && (numParams < 1) ) wrongBody = true;
1722    if ( ((opType == "sendxml2c")||(opType == "sendhex2c")||(opType == "loadxml")||(opType == "diameterServerSessions")) && (numParams != 1) ) wrongBody = true;
1723    if (wrongBody) {
1724      // Launch exception
1725      std::string msg = "Wrong body content format on HTTP Request for '";
1726      msg += opType;
1727      msg += "' operation (missing parameter/s)";
1728      throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1729    }
1730
1731    // All seems ok:
1732    std::string param1, param2;
1733    if (numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1734    if (numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1735
1736
1737    // Operations:
1738    if (opType == "code") {
1739       G_codecMsg.loadXML(param1);
1740       std::string hexString = anna::functions::asHexString(G_codecMsg.code());
1741       // write to outfile
1742       ofstream outfile(param2.c_str(), ifstream::out);
1743       outfile.write(hexString.c_str(), hexString.size());
1744       outfile.close();
1745
1746    } else if (opType == "decode") {
1747       // Get DataBlock from file with hex content:
1748       if (!getDataBlockFromHexFile(param1, db_aux))
1749          throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1750
1751       // Decode
1752       try { G_codecMsg.decode(db_aux); } catch (anna::RuntimeException &ex) { ex.trace(); }
1753
1754       std::string xmlString = G_codecMsg.asXMLString();
1755       // write to outfile
1756       ofstream outfile(param2.c_str(), ifstream::out);
1757       outfile.write(xmlString.c_str(), xmlString.size());
1758       outfile.close();
1759
1760    } else if ((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1761       anna::diameter::comm::Entity *entity = getEntity();
1762       if (!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1763       if (param1 != "") {
1764          if (param2 != "") {
1765             std::string key = param1;
1766             key += "|";
1767             key += param2;
1768
1769             if (opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1770             if (opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1771             if (opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1772             if (opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1773          } else {
1774             std::string address;
1775             int port;
1776             anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1777
1778             if (opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1779             if (opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1780             if (opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1781             if (opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1782          }
1783       } else {
1784          if (opType == "hide") entity->hide();
1785          if (opType == "show") entity->show();
1786          if (opType == "hidden") result = entity->hidden() ? "true" : "false";
1787          if (opType == "shown") result = entity->shown() ? "true" : "false";
1788       }
1789    } else if ((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1790
1791       anna::diameter::comm::Entity *entity = getEntity();
1792       if (!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1793
1794       if ((opType == "sendxml") || (opType == "sendxml2e")) {
1795         G_codecMsg.loadXML(param1);
1796         G_commMsgSent2e.clearBody();
1797         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)
1798         G_commMsgSent2e.setBody(G_codecMsg.code());
1799       }
1800       else {
1801         // Get DataBlock from file with hex content:
1802         if (!getDataBlockFromHexFile(param1, db_aux))
1803           throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1804         G_commMsgSent2e.setBody(db_aux);
1805       }
1806
1807       bool success = entity->send(G_commMsgSent2e, cl.exists("balance"));
1808
1809       // Detailed log:
1810       if (logEnabled()) {
1811          anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1812          anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1813          std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1814          writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
1815       }
1816    } else if ((opType == "burst")) {
1817       anna::diameter::comm::Entity *entity = getEntity();
1818       if (!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1819
1820       // burst|clear                     clears all loaded burst messages.
1821       // burst|load|<source_file>        loads the next diameter message into launcher burst.
1822       // burst|start|<initial load>      starts the message sending with a certain initial load.
1823       // burst|push|<load amount>        sends specific non-aynchronous load.
1824       // burst|stop                      stops the burst cycle.
1825       // burst|repeat|[[yes]|no]         restarts the burst launch when finish.
1826       // burst|send|<amount>             send messages from burst list. The main difference with
1827       //                                 start/push operations is that burst won't be awaken.
1828       //                                 Externally we could control sending time (no request
1829       //                                 will be sent for answers).
1830       // burst|goto|<order>              Updates current burst pointer position.
1831       // burst|look|<order>              Show programmed burst message for order provided.
1832
1833       if (param1 == "clear") {
1834          result = "Removed ";
1835          result += anna::functions::asString(clearBurst());
1836          result += " elements.";
1837       } else if (param1 == "load") {
1838          if (param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1839
1840          G_codecMsg.loadXML(param2);
1841
1842          if (G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1843          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)
1844
1845          int position = loadBurstMessage(G_codecMsg.code());
1846          result = "Loaded '";
1847          result += param2;
1848          result += "' file into burst list position ";
1849          result += anna::functions::asString(position);
1850       } else if (param1 == "start") {
1851          if (param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1852
1853          int initialLoad = atoi(param2.c_str());
1854          int processed = startBurst(initialLoad);
1855
1856          if (processed > 0) {
1857             result = "Initial load completed for ";
1858             result += anna::functions::entriesAsString(processed, "message");
1859             result += ".";
1860          }
1861       } else if (param1 == "push") {
1862          if (param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1863
1864          int pushed = pushBurst(atoi(param2.c_str()));
1865
1866          if (pushed > 0) {
1867             result = "Pushed ";
1868             result += anna::functions::entriesAsString(pushed, "message");
1869             result += ".";
1870          }
1871       } else if (param1 == "pop") {
1872          if (param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1873
1874          int releaseLoad = atoi(param2.c_str());
1875          int popped = popBurst(releaseLoad);
1876
1877          if (popped > 0) {
1878             result = "Burst popped for ";
1879             result += anna::functions::entriesAsString(popped, "message");
1880             result += ".";
1881          }
1882       } else if (param1 == "stop") {
1883          int left = stopBurst();
1884
1885          if (left != -1) {
1886             result += anna::functions::entriesAsString(left, "message");
1887             result += " left to the end of the cycle.";
1888          }
1889       } else if (param1 == "repeat") {
1890          if (param2 == "") param2 = "yes";
1891
1892          bool repeat = (param2 == "yes");
1893          repeatBurst(repeat);
1894          result += (repeat ? "Mode on." : "Mode off.");
1895       } else if (param1 == "send") {
1896          if (param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1897
1898          int sent = sendBurst(atoi(param2.c_str()));
1899
1900          if (sent > 0) {
1901             result = "Sent ";
1902             result += anna::functions::entriesAsString(sent, "message");
1903             result += ".";
1904          }
1905       } else if (param1 == "goto") {
1906          if (param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1907
1908          result = gotoBurst(atoi(param2.c_str()));
1909          result += ".";
1910       } else if (param1 == "look") {
1911          if (param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1912
1913          result = "\n\n";
1914          result += lookBurst(atoi(param2.c_str()));
1915          result += "\n\n";
1916       } else {
1917          throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1918       }
1919
1920    } else if ((opType == "sendxml2c") || (opType == "sendhex2c")) {
1921       anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
1922       if (!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1923
1924       if (opType == "sendxml2c") {
1925         G_codecMsg.loadXML(param1);
1926         G_commMsgSent2c.clearBody();
1927         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)
1928         G_commMsgSent2c.setBody(G_codecMsg.code());
1929       }
1930       else {
1931         // Get DataBlock from file with hex content:
1932         if (!getDataBlockFromHexFile(param1, db_aux))
1933           throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1934         G_commMsgSent2c.setBody(db_aux);
1935       }
1936
1937       bool success = localServer->send(G_commMsgSent2c);
1938
1939       // Detailed log:
1940       if (logEnabled()) {
1941          anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1942          std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1943          writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
1944       }
1945
1946    } else if (opType == "loadxml") {
1947       G_codecMsg.loadXML(param1);
1948       std::string xmlString = G_codecMsg.asXMLString();
1949       std::cout << xmlString << std::endl;
1950
1951    } else if (opType == "diameterServerSessions") {
1952
1953       int diameterServerSessions = atoi(param1.c_str());
1954
1955       if (!getDiameterLocalServer())
1956          startDiameterServer(diameterServerSessions);
1957       else
1958          getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
1959    } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
1960       anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
1961
1962       if (!localServer)
1963          throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1964
1965       if (param1 != "") {
1966          anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
1967          anna::diameter::codec::Message *message = engine->createMessage(param1);
1968          LOGDEBUG
1969          (
1970             anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1971          );
1972
1973          if (message->isRequest())
1974             throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1975
1976          int code = message->getId().first;
1977          reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
1978
1979          if (it != G_reactingAnswers2C.end()) { // found: replace
1980             LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
1981             engine->releaseMessage((*it).second);
1982          }
1983
1984          G_reactingAnswers2C[code] = message;
1985       } else { // answers query on stdout
1986          std::cout << programmedAnswers2c() << std::endl;
1987          response_content = "Programmed answers dumped on stdout\n";
1988          return;
1989       }
1990    } else if (opType == "answerxml2e") {
1991       anna::diameter::comm::Entity *entity = getEntity();
1992
1993       if (!entity)
1994          throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1995
1996       if (param1 != "") {
1997          anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
1998          anna::diameter::codec::Message *message = engine->createMessage(param1);
1999          LOGDEBUG
2000          (
2001             anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2002          );
2003
2004          if (message->isRequest())
2005             throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2006
2007          int code = message->getId().first;
2008          reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
2009
2010          if (it != G_reactingAnswers2E.end()) { // found: replace
2011             LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
2012             engine->releaseMessage((*it).second);
2013          }
2014
2015          G_reactingAnswers2E[code] = message;
2016       } else { // answers query on stdout
2017          std::cout << programmedAnswers2e() << std::endl;
2018          response_content = "Programmed answers dumped on stdout\n";
2019          return;
2020       }
2021    } else {
2022       LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
2023       throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
2024    }
2025
2026    // HTTP response
2027    response_content = "Operation processed; ";
2028
2029    if ((opType == "decode") || (opType == "code")) {
2030       response_content += "File '";
2031       response_content += param2;
2032       response_content += "' created.";
2033       response_content += "\n";
2034    } else if ((opType == "hide") || (opType == "show")) {
2035       response_content += "Resource '";
2036       response_content += ((param1 != "") ? param1 : "Entity");
2037
2038       if (param2 != "") {
2039          response_content += "|";
2040          response_content += param2;
2041       }
2042
2043       response_content += "' ";
2044
2045       if (opType == "hide") response_content += "has been hidden.";
2046
2047       if (opType == "show") response_content += "has been shown.";
2048
2049       response_content += "\n";
2050    } else if ((opType == "hidden") || (opType == "shown")) {
2051       response_content += "Result: ";
2052       response_content += result;
2053       response_content += "\n";
2054    } else if ((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
2055       response_content += "Message '";
2056       response_content += param1;
2057       response_content += "' sent to entity.";
2058       response_content += "\n";
2059    } else if (opType == "burst") {
2060       response_content += "Burst '";
2061       response_content += param1;
2062       response_content += "' executed. ";
2063       response_content += result;
2064       response_content += "\n";
2065    } else if ((opType == "sendxml2c")||(opType == "sendhex2c")) {
2066       response_content += "Message '";
2067       response_content += param1;
2068       response_content += "' sent to client.";
2069       response_content += "\n";
2070    } else if (opType == "loadxml") {
2071       response_content += "Message '";
2072       response_content += param1;
2073       response_content += "' loaded.";
2074       response_content += "\n";
2075    } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
2076       response_content += "Answer to client '";
2077       response_content += param1;
2078       response_content += "' programmed.";
2079       response_content += "\n";
2080    } else if (opType == "answerxml2e") {
2081       response_content += "Answer to entity '";
2082       response_content += param1;
2083       response_content += "' programmed.";
2084       response_content += "\n";
2085    } else if (opType == "diameterServerSessions") {
2086       response_content += "Maximum server socket connections updated to '";
2087       response_content += param1;
2088       response_content += "'.";
2089       response_content += "\n";
2090    }
2091 }
2092
2093
2094 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
2095    CommandLine& cl(anna::CommandLine::instantiate());
2096    std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
2097
2098    if (sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
2099
2100    try {
2101       // Service-Context-Id:
2102       anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
2103       std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
2104
2105       switch (chargingContext) {
2106       case anna::diameter::helpers::dcca::ChargingContext::Data:
2107       case anna::diameter::helpers::dcca::ChargingContext::Voice:
2108       case anna::diameter::helpers::dcca::ChargingContext::Content: {
2109          // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
2110          std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
2111          std::string diameterIdentity, optional;
2112          anna::U32 high, low;
2113          anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
2114
2115          if (sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
2116
2117          if (sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
2118
2119          if (sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
2120       }
2121       //case anna::diameter::helpers::dcca::ChargingContext::SMS:
2122       //case anna::diameter::helpers::dcca::ChargingContext::MMS:
2123       //default:
2124       //   return -1; // IEC model and Unknown traffic types
2125       }
2126    } catch (anna::RuntimeException &ex) {
2127       LOGDEBUG(
2128          std::string msg = ex.getText();
2129          msg += " | Round-robin between sessions will be used to send";
2130          anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2131       );
2132    }
2133
2134    return -1;
2135 }
2136
2137
2138 void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2139 throw(anna::RuntimeException) {
2140    LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
2141    // Performance stats:
2142    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2143    CommandLine& cl(anna::CommandLine::instantiate());
2144    // CommandId:
2145    anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2146    LOGDEBUG
2147    (
2148       std::string msg = "Request received: ";
2149       msg += anna::diameter::functions::commandIdAsPairString(cid);
2150       msg += " | DiameterServer: ";
2151       msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2152       msg += " | EventTime: ";
2153       msg += anna::time::functions::currentTimeAsString();
2154       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2155    );
2156
2157    // Write reception
2158    if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
2159
2160    // Lookup reacting answers list:
2161    int code = cid.first;
2162    reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
2163
2164    if (it != G_reactingAnswers2E.end()) {
2165       anna::diameter::codec::Message *answer_message = (*it).second;
2166       // Prepare answer:
2167       my_app.getCommunicator()->prepareAnswer(answer_message, message);
2168
2169       try {
2170          G_commMsgSent2e.setBody(answer_message->code());
2171          /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
2172
2173          if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
2174       } catch (anna::RuntimeException &ex) {
2175          ex.trace();
2176
2177          if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
2178       }
2179    } else { // not found: forward to client (if exists)
2180       // Forward to client:
2181       anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2182
2183       if (localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
2184          try {
2185             anna::diameter::comm::Message *msg = G_commMessages.create();
2186             msg->setBody(message);
2187             msg->setRequestClientSessionKey(clientSession->getKey());
2188             bool success = localServer->send(msg);
2189
2190             // Detailed log:
2191             if (my_app.logEnabled()) {
2192                anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2193                std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2194                my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
2195             }
2196          } catch (anna::RuntimeException &ex) {
2197             ex.trace();
2198          }
2199       }
2200    }
2201 }
2202
2203
2204 void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response)
2205 throw(anna::RuntimeException) {
2206    LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
2207    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2208    CommandLine& cl(anna::CommandLine::instantiate());
2209    anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2210    anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2211    anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2212    const anna::DataBlock* message = response.getMessage();
2213    const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(response.getSession());
2214    bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2215    bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2216    bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2217    bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2218    bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2219    // CommandId:
2220    anna::diameter::CommandId request_cid = request->getCommandId();
2221    LOGDEBUG
2222    (
2223       std::string msg = "Response received for original diameter request: ";
2224       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2225       msg += " | Response: ";
2226       msg += response.asString();
2227       msg += " | DiameterServer: ";
2228       msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2229       msg += " | EventTime: ";
2230       msg += anna::time::functions::currentTimeAsString();
2231       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2232    );
2233
2234    if (isUnavailable) {
2235       //if (isApplicationMessage)
2236       LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION));
2237    }
2238
2239    if (contextExpired) {
2240       //if (isApplicationMessage)
2241       LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
2242
2243       if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2244          if (my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString());
2245       }
2246    }
2247
2248    if (isOK) {
2249       LOGDEBUG(
2250          std::string msg = "Received response for diameter message:  ";
2251          msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2252          anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2253       );
2254       // Write reception
2255       bool alreadyDecodedOnG_codecMsg = false;
2256
2257       if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2258          if (my_app.logEnabled()) {
2259             my_app.writeLogFile(*message, "recvfe", clientSession->asString());
2260             alreadyDecodedOnG_codecMsg = true;
2261          }
2262       }
2263
2264       // Forward to client:
2265       anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2266
2267       if (localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
2268          try {
2269             G_commMsgFwd2c.setBody(*message);
2270             bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey());
2271             G_commMessages.release(request);
2272             // Detailed log:
2273             anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
2274             std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2275
2276             if (my_app.logEnabled()) {
2277                if (alreadyDecodedOnG_codecMsg)
2278                   my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail);
2279                else
2280                   my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
2281             }
2282          } catch (anna::RuntimeException &ex) {
2283             ex.trace();
2284          }
2285       }
2286    }
2287
2288    // Triggering burst:
2289    if (isOK || contextExpired) my_app.sendBurstMessage();
2290 }
2291
2292
2293 void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2294 throw(anna::RuntimeException) {
2295    LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
2296    // Performance stats:
2297    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2298    // CommandId:
2299    anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2300    LOGDEBUG
2301    (
2302       std::string msg = "Out-of-context response received from entity: ";
2303       msg += anna::diameter::functions::commandIdAsPairString(cid);
2304       msg += " | DiameterServer: ";
2305       msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2306       msg += " | EventTime: ";
2307       msg += anna::time::functions::currentTimeAsString();
2308       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2309    );
2310
2311    // Write reception
2312    if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
2313 }
2314
2315
2316
2317
2318 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2319 throw(anna::RuntimeException) {
2320    LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
2321    // Performance stats:
2322    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2323    CommandLine& cl(anna::CommandLine::instantiate());
2324    // CommandId:
2325    anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2326    LOGDEBUG
2327    (
2328       std::string msg = "Request received: ";
2329       msg += anna::diameter::functions::commandIdAsPairString(cid);
2330       msg += " | DiameterServer: ";
2331       msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2332       msg += " | EventTime: ";
2333       msg += anna::time::functions::currentTimeAsString();
2334       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2335    );
2336
2337    // Write reception
2338    if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2339
2340    // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
2341    int code = cid.first;
2342    reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
2343    bool programmed = (it != G_reactingAnswers2C.end());
2344    anna::diameter::comm::Entity *entity = my_app.getEntity();
2345
2346    if (!programmed && entity) { // forward condition (no programmed answer + entity available)
2347       anna::diameter::comm::Message *msg = G_commMessages.create();
2348       msg->setBody(message);
2349       msg->setRequestServerSessionKey(serverSession->getKey());
2350       bool success = entity->send(msg, cl.exists("balance"));
2351
2352       // Detailed log:
2353       if (my_app.logEnabled()) {
2354          anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
2355          anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
2356          std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2357          my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
2358       }
2359
2360       return;
2361    }
2362
2363    // Error analisys:
2364    bool analysisOK = true; // by default
2365    anna::diameter::codec::Message *answer_message = NULL;
2366
2367    if (!cl.exists("ignoreErrors")) { // Error analysis
2368       answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg;
2369       answer_message->clear();
2370
2371       // Decode
2372       try { G_codecMsg.decode(message, answer_message); } catch (anna::RuntimeException &ex) { ex.trace(); }
2373
2374       answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
2375       analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
2376    }
2377
2378    // Programmed answer only when all is ok
2379    if (analysisOK) {
2380       if (programmed) {
2381          answer_message = (*it).second;
2382          // Prepare answer:
2383          my_app.getCommunicator()->prepareAnswer(answer_message, message);
2384       } else return; // nothing done
2385    }
2386
2387    anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION));
2388    anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
2389
2390    if (!analysisOK)
2391       codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
2392
2393    try {
2394       G_commMsgSent2c.setBody(answer_message->code());
2395       /* response = NULL =*/serverSession->send(&G_commMsgSent2c);
2396
2397       if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
2398    } catch (anna::RuntimeException &ex) {
2399       ex.trace();
2400
2401       if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
2402    }
2403    
2404    // Restore validation mode
2405    codecEngine->setValidationMode(backupVM);
2406 }
2407
2408 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
2409 throw(anna::RuntimeException) {
2410    LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
2411    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2412    CommandLine& cl(anna::CommandLine::instantiate());
2413    anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2414    anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2415    anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2416    const anna::DataBlock* message = response.getMessage();
2417    const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
2418    bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2419    bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2420    bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2421    bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2422    bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2423    // CommandId:
2424    anna::diameter::CommandId request_cid = request->getCommandId();
2425    LOGDEBUG
2426    (
2427       std::string msg = "Response received for original diameter request: ";
2428       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2429       msg += " | Response: ";
2430       msg += response.asString();
2431       msg += " | LocalServer: ";
2432       msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2433       msg += " | EventTime: ";
2434       msg += anna::time::functions::currentTimeAsString();
2435       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2436    );
2437
2438    if (isUnavailable) {
2439       //if (isApplicationMessage)
2440       LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
2441    }
2442
2443    if (contextExpired) {
2444       //if (isApplicationMessage)
2445       LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
2446
2447       if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2448          if (my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString());
2449       }
2450    }
2451
2452    if (isOK) {
2453       LOGDEBUG(
2454          std::string msg = "Received response for diameter message:  ";
2455          msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2456          anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2457       );
2458
2459       // Write reception
2460       if (my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString());
2461
2462       // This is not very usual, but answers could arrive from clients:
2463       anna::diameter::comm::Entity *entity = my_app.getEntity();
2464
2465       if (entity) {
2466          anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
2467          std::string detail;
2468
2469          if (my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2470
2471          try {
2472             G_commMsgFwd2e.setBody(*message);
2473
2474             // Metodo 1:
2475             if (usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e);
2476
2477             // Metodo 2:
2478             //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey());
2479             //bool success = entity->send(G_commMsgFwd2e);
2480             G_commMessages.release(request);
2481
2482             if (my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded
2483          } catch (anna::RuntimeException &ex) {
2484             ex.trace();
2485
2486             if (my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded
2487          }
2488       }
2489    }
2490 }
2491
2492 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2493 throw(anna::RuntimeException) {
2494    LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
2495    // Performance stats:
2496    Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2497    // CommandId:
2498    anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2499    LOGDEBUG
2500    (
2501       std::string msg = "Out-of-context response received from client: ";
2502       msg += anna::diameter::functions::commandIdAsPairString(cid);
2503       msg += " | DiameterServer: ";
2504       msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2505       msg += " | EventTime: ";
2506       msg += anna::time::functions::currentTimeAsString();
2507       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2508    );
2509
2510    if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
2511 }
2512
2513
2514 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2515 throw() {
2516    anna::xml::Node* result = parent->createChild("launcher");
2517    anna::comm::Application::asXML(result);
2518    // Timming:
2519    result->createAttribute("StartTime", a_start_time.asString());
2520    result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2521    // Diameter:
2522    (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
2523    // OAM:
2524    anna::diameter::comm::OamModule::instantiate().asXML(result);
2525    anna::diameter::codec::OamModule::instantiate().asXML(result);
2526    // Statistics:
2527    anna::statistics::Engine::instantiate().asXML(result);
2528    return result;
2529 }
2530