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