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