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