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