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