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