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