1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
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
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.
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.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
40 #include <sys/stat.h> // chmod
41 #include <fcntl.h> // open / write
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>
95 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
96 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
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
105 // Auxiliary resources for answers programming
106 class ProgrammedAnswers {
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;
115 reacting_answers_container a_deques;
118 ProgrammedAnswers() {};
119 ~ProgrammedAnswers() {
120 for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
121 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
122 engine->releaseMessage(*(it->second->begin()));
127 void addMessage(int code, anna::diameter::codec::Message *message) throw() {
128 reacting_answers_const_iterator it = a_deques.find(code);
129 if (it != a_deques.end()) {
130 it->second->push_back(message);
133 codec_messages_deque *deque = new codec_messages_deque;
134 a_deques[code] = deque;
135 deque->push_back(message);
139 anna::diameter::codec::Message* getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty
140 anna::diameter::codec::Message *result = NULL;
141 reacting_answers_const_iterator it = a_deques.find(code);
142 if (it != a_deques.end()) {
143 if (!it->second->empty()) result = *(it->second->begin());
148 void nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty)
149 reacting_answers_const_iterator it = a_deques.find(code);
150 if (it != a_deques.end()) {
151 if (!it->second->empty()) {
152 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
153 engine->releaseMessage(*(it->second->begin()));
154 it->second->pop_front();
159 std::string asString() const throw() {
160 std::string result = "No ocurrences found\n\n";
161 if(a_deques.size() != 0) {
162 for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
163 result += "Answer code .............................................................. ";
164 result += anna::functions::asString(it->first); result += "\n";
165 for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
166 result += (*itm)->asXMLString();
176 ProgrammedAnswers G_reactingAnswers2C, G_reactingAnswers2E;
180 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
181 // COUNTERS RECORD PROCEDURE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
182 class MyCounterRecorderClock : public anna::timex::Clock {
184 MyCounterRecorderClock(const char *clockName, const anna::Millisecond & timeout) :
185 anna::timex::Clock(clockName, timeout) {;}
186 //virtual ~MyCounterRecorderClock();
188 virtual bool tick() throw(RuntimeException) {
189 anna::diameter::comm::OamModule::instantiate().recordCounters();
190 anna::diameter::codec::OamModule::instantiate().recordCounters();
195 class MyCounterRecorder : public anna::oam::CounterRecorder {
199 std::string a_fileNamePrefix;
200 std::string a_fileName;
201 time_t a_previousTime;
202 std::string a_fixedLine;
204 // pure virtual definitions:
205 void open() throw(anna::RuntimeException) {
206 static char str [256];
207 const time_t now = ::time(NULL);
209 struct tm tmPrevious;
210 anna_memcpy(&tmNow, localtime(&now), sizeof(tmNow));
211 anna_memcpy(&tmPrevious, localtime(&a_previousTime), sizeof(tmPrevious));
213 str, ".Date%04d%02d%02d.Time%02d%02d%02d",
214 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
215 tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec);
216 a_fileName = a_fileNamePrefix;
219 std::string msg("Flush counters | ");
221 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
224 if((a_stream = ::open(a_fileName.c_str(), O_WRONLY | O_CREAT, S_IWUSR)) == -1)
225 throw RuntimeException(anna::functions::asString("Error opening file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
227 sprintf(str, "%04d-%02d-%02d %02d:%02d|%04d-%02d-%02d %02d:%02d",
228 1900 + (tmPrevious.tm_year), (tmPrevious.tm_mon) + 1,
229 tmPrevious.tm_mday, tmPrevious.tm_hour, tmPrevious.tm_min,
230 1900 + (tmNow.tm_year), (tmNow.tm_mon) + 1,
231 tmNow.tm_mday, tmNow.tm_hour, tmNow.tm_min
237 void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) {
238 static char line [356];
239 anna::oam::Counter::type_t value = counter;
240 sprintf(line, "%s|%06d|%07u|%s\n", a_fixedLine.c_str(), counter.getReference(), value, counter.getName().c_str());
242 if(write(a_stream, line, anna_strlen(line)) == -1)
243 throw RuntimeException(anna::functions::asString("Error writting to file '%s'; errno = %d", a_fileName.c_str(), errno), ANNA_FILE_LOCATION);
246 void close() throw() {
252 chmod(a_fileName.c_str(), S_IWUSR | S_IRUSR);
253 a_previousTime = ::time(NULL);
256 std::string asString() const throw() {
257 std::string result = "Physical counters dump at file '";
258 result += a_fileName;
259 result += "'. Another way to see counters: context dump (kill -10 <pid>";
264 MyCounterRecorder(const std::string &fnp) : a_stream(-1), a_fileNamePrefix(fnp) {
265 a_previousTime = ::time(NULL);
269 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
272 class MyDiameterEntity : public anna::diameter::comm::Entity {
274 void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
275 void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
276 void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
279 int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw();
282 class MyLocalServer : public anna::diameter::comm::LocalServer {
284 void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
285 void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
286 void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
289 class MyDiameterEngine : public anna::diameter::comm::Engine {
292 static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; }
293 MyDiameterEngine() {;}
295 // Default implementation is enough
296 // void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied
297 // void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied
298 // void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied
301 anna::Recycler<MyDiameterEntity> a_entitiesRecycler;
303 anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); }
305 void releaseEntity(anna::diameter::comm::Entity* entity) throw() {
306 MyDiameterEntity* aux = static_cast <MyDiameterEntity*>(entity);
307 a_entitiesRecycler.release(aux);
310 anna::Recycler<MyLocalServer> a_localServersRecycler;
312 anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); }
314 void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() {
315 MyLocalServer* aux = static_cast <MyLocalServer*>(localServer);
316 a_localServersRecycler.release(aux);
321 class MyHandler : public anna::http::Handler {
323 MyHandler() : anna::http::Handler("http_converter::MyHandler") {
324 allocateResponse()->createHeader(anna::http::Header::Type::Date);
329 void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException);
330 void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;}
333 class MyCommunicator : public anna::comm::Communicator {
335 MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode),
336 a_contexts("Contexts")
339 void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw();
340 void terminate() throw();
343 anna::ThreadData <MyHandler> a_contexts;
344 void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException);
345 void eventBreakConnection(Server* server) throw();
348 class Launcher : public anna::comm::Application {
350 MyCommunicator *a_communicator;
351 MyDiameterEngine *a_myDiameterEngine;
352 anna::diameter::comm::Entity *a_entity;
353 std::string a_logFile, a_burstLogFile;
354 std::ofstream a_burstLogStream;
355 bool a_splitLog, a_detailedLog;
356 anna::time::Date a_start_time;
357 anna::timex::Engine* a_timeEngine;
358 MyCounterRecorder *a_counterRecorder;
359 MyCounterRecorderClock *a_counterRecorderClock;
360 std::string a_cerPathfile;
361 std::string a_dwrPathfile;
367 std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages;
369 std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
371 int a_burstPopCounter;
373 anna::comm::ServerSocket* a_httpServerSocket; // HTTP
374 anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER
375 void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException);
376 void initialize() throw(anna::RuntimeException); // HTTP
377 void run() throw(anna::RuntimeException);
382 MyCommunicator *getCommunicator() throw() { return a_communicator; }
383 MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); }
384 void baseProtocolSetupAsClient(void) throw(anna::RuntimeException);
385 anna::diameter::comm::Entity *getEntity() throw() { return a_entity; }
386 anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; }
387 void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException);
388 bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
389 void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw();
390 void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw();
391 void writeBurstLogFile(const std::string &buffer) throw();
392 bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
393 void startDiameterServer(int) throw(anna::RuntimeException);
395 anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
396 void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); }
397 void resetCounters() throw();
398 void signalUSR2() throw(anna::RuntimeException);
399 std::string help() const throw();
402 bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw();
405 int clearBurst() throw(); // returns removed
406 int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
407 void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
408 int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
409 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)
410 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)
411 int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
412 int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
413 bool burstActive() const throw() { return a_burstActive; }
414 bool sendBurstMessage(bool anyway = false) throw();
415 std::string lookBurst(int order) const throw();
416 std::string gotoBurst(int order) throw();
419 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
421 static char buffer[8192];
422 std::ifstream infile(pathfile.c_str(), std::ifstream::in);
424 if(infile.is_open()) {
426 std::string hexString(buffer, strlen(buffer));
427 // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
428 hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
430 std::string msg = "Hex string (remove colons if exists): ";
432 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
434 anna::functions::fromHexString(hexString, db);
443 int Launcher::clearBurst() throw() {
444 int size = a_burstMessages.size();
447 std::map<int, anna::diameter::comm::Message*>::const_iterator it;
448 std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
449 std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
451 for(it = it_min; it != it_max; it++) G_commMessages.release((*it).second);
453 a_burstMessages.clear();
455 std::string msg = "Burst list already empty. Nothing done";
456 std::cout << msg << std::endl;
457 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
460 a_burstActive = false;
462 a_burstDeliveryIt = a_burstMessages.begin();
467 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
468 anna::diameter::comm::Message *msg = G_commMessages.create();
470 a_burstMessages[a_burstLoadIndx++] = msg;
471 return (a_burstLoadIndx - 1);
474 int Launcher::stopBurst() throw() {
476 std::string msg = "Burst launch is already stopped. Nothing done";
477 std::cout << msg << std::endl;
478 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
482 a_burstActive = false;
483 // Remaining on cycle:
484 return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
487 int Launcher::popBurst(int releaseAmount) throw() {
489 std::string msg = "Burst launch is stopped. Nothing done";
490 std::cout << msg << std::endl;
491 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
495 if(releaseAmount < 1) {
496 std::string msg = "No valid release amount is specified. Ignoring burst pop";
497 std::cout << msg << std::endl;
498 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
502 int currentOTArequests = a_entity->getOTARequests();
503 a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
504 return a_burstPopCounter;
507 int Launcher::pushBurst(int loadAmount) throw() {
508 if(a_burstMessages.size() == 0) {
509 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
510 std::cout << msg << std::endl;
511 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
516 std::string msg = "No valid load amount is specified. Ignoring burst push";
517 std::cout << msg << std::endl;
518 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
522 a_burstActive = true;
525 for(count = 0; count < loadAmount; count++)
526 if(!sendBurstMessage()) break;
532 int Launcher::sendBurst(int loadAmount) throw() {
533 if(a_burstMessages.size() == 0) {
534 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
535 std::cout << msg << std::endl;
536 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
541 std::string msg = "No valid load amount is specified. Ignoring burst send";
542 std::cout << msg << std::endl;
543 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
549 for(count = 0; count < loadAmount; count++)
550 if(!sendBurstMessage(true /* anyway */)) break;
557 int Launcher::startBurst(int initialLoad) throw() {
558 if(initialLoad < 1) {
559 std::string msg = "No initial load is specified. Ignoring burst start";
560 std::cout << msg << std::endl;
561 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
565 a_burstActive = true;
567 a_burstDeliveryIt = a_burstMessages.begin();
568 return (pushBurst(initialLoad));
571 bool Launcher::sendBurstMessage(bool anyway) throw() {
572 if(!anyway && !burstActive()) return false;
574 if(a_burstPopCounter > 0) {
575 if(burstLogEnabled()) writeBurstLogFile("x");
581 if(a_burstDeliveryIt == a_burstMessages.end()) {
582 a_burstDeliveryIt = a_burstMessages.begin();
588 if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
590 if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
598 anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
599 int order = (*a_burstDeliveryIt).first + 1;
603 bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
605 if(burstLogEnabled()) {
606 if(a_burstMessages.size() >= 100)
607 dot = (order % (a_burstMessages.size() / 100));
610 writeBurstLogFile(".");
612 writeBurstLogFile(anna::functions::asString(" %d", order));
613 int otaReqs = a_entity->getOTARequests();
615 if(result && (otaReqs != a_otaRequest)) {
616 // false if was a sending after an answer received (no OTA change in this case)
617 // true after push and pop operations
618 a_otaRequest = otaReqs;
619 writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
626 anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
627 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
628 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
629 writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
636 std::string Launcher::lookBurst(int order) const throw() {
637 std::string result = "No message found for order provided (";
638 result += anna::functions::asString(order);
640 std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
642 if(it != a_burstMessages.end()) {
644 try { G_codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
646 result = G_codecMsg.asXMLString();
652 std::string Launcher::gotoBurst(int order) throw() {
653 std::string result = "Position not found for order provided (";
654 std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
656 if(it != a_burstMessages.end()) {
657 a_burstDeliveryIt = it;
658 result = "Position updated for order provided (";
661 result += anna::functions::asString(order);
666 ////////////////////////////////////////////////////
669 void Launcher::resetCounters() throw() {
670 // Diameter::comm module:
671 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
672 oamDiameterComm.resetCounters();
675 void Launcher::signalUSR2() throw(anna::RuntimeException) {
677 std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
678 msg += SIGUSR2_TASKS_INPUT_FILENAME;
679 msg += "' (results will be written at '";
680 msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
682 anna::Logger::notice(msg, ANNA_FILE_LOCATION);
686 std::string response_content;
687 std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
688 std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
690 if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
692 if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
694 while(getline(in_file, line)) {
696 std::string msg = "Processing line: ";
698 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
702 eventOperation(line, response_content);
703 } catch(RuntimeException &ex) {
707 out_file << response_content;
715 std::string Launcher::help() const throw() {
716 std::string result = "\n";
717 result += "\n ------------- HELP -------------\n";
719 result += "\nOVERVIEW";
720 result += "\n--------";
722 result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
723 result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
724 result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
725 result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
726 result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
727 result += "\n send it to another process.";
729 result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
730 result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
731 result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
732 result += "\n generation, expiration control and many more features.";
734 result += "\nProcess traces are dump on \"launcher.traces\" and could have any trace level (POSIX levels), usually";
735 result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
737 result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
738 result += "\n kill -10 <pid>";
740 result += "\n kill -s SIGUSR1 <pid>";
741 result += "\n and then";
742 result += "\n vi /var/tmp/anna.context.<pid>";
744 result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
745 result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
746 result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
747 result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
748 result += "\n measurements.";
750 result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
753 result += "\nCOMMAND LINE";
754 result += "\n------------";
756 result += "\nStart the launcher process without arguments in order to see all the startup configuration";
757 result += "\n posibilities, many of which could be modified on the air through the management interface";
758 result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
760 result += "\nAs mandatory, the stack definition given through the xml dictionary:";
761 result += "\n -dictionary <path to dictionary file>";
763 result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
764 result += "\n -diameterServer localhost:3868 -diameterServerSessions 10 -entityServerSessions 0";
766 result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
767 result += "\n -entity 192.168.12.11:3868,192.168.12.21:3868 -entityServerSessions 10 -diameterServerSessions 0";
769 result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
770 result += "\n will need to program the answers to be replied through the operations interface. To balance the";
771 result += "\n traffic at your client side you shall use '-balance' and '-sessionBasedModelsClientSocketSelection'";
772 result += "\n arguments in order to define the balancing behaviour.";
774 result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
775 result += "\n customized ones using '-cer <xml message file>' and '-dwr <xml message file>'.";
776 result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
777 result += "\n customized ones using operations interface.";
780 result += "\nDYNAMIC OPERATIONS";
781 result += "\n------------------";
783 result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
784 result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
785 result += "\n separated by pipes. These are the available commands:";
787 result += "\n--------------------------------------------------------------------------------------- General purpose";
789 result += "\nhelp This help. Startup information-level traces also dump this help.";
791 result += "\n------------------------------------------------------------------------------------ Parsing operations";
793 result += "\ncode|<source_file>|<target_file> Encodes source file (pathfile) into target file (pathfile).";
794 result += "\ndecode|<source_file>|<target_file> Decodes source file (pathfile) into target file (pathfile).";
795 result += "\nloadxml|<source_file> Reinterpret xml source file (pathfile).";
797 result += "\n------------------------------------------------------------------------------------------- Hot changes";
799 result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter";
800 result += "\n server socket.";
801 result += "\ncollect Reset statistics and counters to start a new test stage of";
802 result += "\n performance measurement. Context data is written at";
803 result += "\n '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
805 result += "\n<visibility action>|[<address>:<port>]|[socket id]";
807 result += "\n Actions: hide, show (update state) and hidden, shown (query state).";
808 result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
809 result += "\n If missing server (first parameter) all applications sockets will be affected.";
810 result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected.";
812 result += "\n All application client sessions are shown on startup, but standard delivery only use primary";
813 result += "\n server ones except if fails. Balance configuration use all the allowed sockets. You could also";
814 result += "\n use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
815 result += "\n client sessions, but for this, hide/show feature seems easier.";
817 result += "\n--------------------------------------------------------------------------------------- Flow operations";
819 result += "\nsendxml2e|<source_file> Sends xml source file (pathfile) through configured entity.";
820 result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to client.";
821 result += "\nsendxml|<source_file> Same as 'sendxml2e'.";
822 result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for corresponding request from entity.";
823 result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for corresponding request from client.";
824 result += "\nanswerxml|[source_file] Same as 'answerxml2c'.";
825 result += "\n List programmed answers if no parameter provided.";
827 result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
828 result += "\nspecial scenarios (protocol errors):";
830 result += "\nsendhex2e|<source_file> Sends hex source file (pathfile) through configured entity.";
831 result += "\nsendhex2c|<source_file> Sends hex source file (pathfile) to client.";
832 result += "\nsendhex|<source_file> Same as 'sendhex2e'.";
834 result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
835 result += "\nis intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
836 result += "\nsubscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
838 result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
839 result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
840 result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
841 result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
842 result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
844 result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
845 result += "\n to the peer which sent the request. If user wants to test a specific answer without changing it,";
846 result += "\n use sendxml/sendhex operations better than programming.";
848 result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
849 result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
850 result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
851 result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
853 result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
855 result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
856 result += "\n details when unique log file is dumped:";
858 result += "\n [sent2e/send2eError] Send to entity (success/error)";
859 result += "\n [sent2c/send2cError] Send to client (success/error)";
860 result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)";
861 result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)";
862 result += "\n [recvfc] Reception from client";
863 result += "\n [recvfe] Reception from entity";
864 result += "\n [req2c-expired] A request sent to client has been expired";
865 result += "\n [req2e-expired] A request sent to entity has been expired";
866 result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired]";
867 result += "\n has been logged)";
868 result += "\n [recvfe-ans-unknown] Reception from entity of an unknown answer (probably former [req2e-expired]";
869 result += "\n has been logged)";
871 result += "\n-------------------------------------------------------------------------------------------- Load tests";
873 result += "\nburst|<action>|[parameter] Used for performance testing, we first program diameter requests";
874 result += "\n messages in order to launch them from client side to the configured";
875 result += "\n diameter entity. We could start the burst with an initial load";
876 result += "\n (non-asynchronous sending), after this, a new request will be sent";
877 result += "\n per answer received or expired context. There are 10 actions: clear,";
878 result += "\n load, start, push, pop, stop, repeat, send, goto and look.";
880 result += "\n burst|clear Clears all loaded burst messages.";
881 result += "\n burst|load|<source_file> Loads the next diameter message into launcher burst.";
882 result += "\n burst|start|<initial load> Starts (or restarts if already in progress) the message sending with";
883 result += "\n a certain initial load.";
884 result += "\n burst|push|<load amount> Sends specific non-aynchronous load.";
885 result += "\n burst|pop|<release amount> Skip send burst messages in order to reduce over-the-air requests.";
886 result += "\n Popping all OTA requests implies burst stop because no more answer";
887 result += "\n will arrive to the process. Burst output file (-burstLog command";
888 result += "\n line parameter) shows popped messages with crosses (x). Each cross";
889 result += "\n represents one received answer for which no new request is sent.";
890 result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount.";
891 result += "\n burst|repeat|[[yes]|no] Restarts the burst launch when finish. If initial load or push load";
892 result += "\n amount is greater than burst list size, they will be limited when";
893 result += "\n the list is processed except when repeat mode is enabled.";
894 result += "\n burst|send|<amount> Sends messages from burst list. The main difference with start/push";
895 result += "\n operations is that burst won't be awaken. Externally we could control";
896 result += "\n sending time (no request will be sent for answers).";
897 result += "\n burst|goto|<order> Updates current burst pointer position.";
898 result += "\n burst|look|<order> Show programmed burst message for order provided.";
901 result += "\nUSING OPERATIONS INTERFACE";
902 result += "\n--------------------------";
904 result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
906 result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
907 result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
908 result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
909 result += "\n using curl client could be:";
911 result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
912 result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000";
913 result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
914 result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
917 result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
919 result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
920 result += "\n signal event:";
921 result += "\n echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
923 result += "\n kill -12 <pid>";
925 result += "\n kill -s SIGUSR2 <pid>";
926 result += "\n and then see the results:";
927 result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
929 result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
930 result += "\n case over the output file. Take into account that all the content of the task file will be executed";
931 result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
932 result += "\n interface.";
939 void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() {
940 // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request.
941 // If user wants to test a specific answer without changing it, use send operations better than programming.
942 // Sequence substitution:
943 answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request));
944 answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request));
946 // Session-Id substitution:
948 std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request);
950 std::string msg = "Extracted Session-Id: ";
952 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
954 answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId);
955 } catch(anna::RuntimeException &ex) {
959 // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information,
960 // then it will be adapted with the received data at request.
961 if(answer->countAvp("Subscription-Id") > 0) {
962 std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
963 std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
965 if((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information:
966 answer->removeAvp("Subscription-Id", 0 /* remove all */);
971 anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id");
972 sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
973 sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn);
977 anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another
978 sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
979 sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi);
985 void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message)
986 throw(anna::RuntimeException) {
987 LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
989 if(clientSocket.support(anna::http::Transport::className()) == false)
992 MyHandler& httpHandler = a_contexts.get();
993 httpHandler.apply(clientSocket, message);
997 using namespace anna::diameter;
999 int main(int argc, const char** argv) {
1000 anna::Logger::setLevel(anna::Logger::Warning);
1001 anna::Logger::initialize("launcher", new TraceWriter("launcher.traces", 2048000));
1002 anna::time::functions::initialize(); // before application instantiation (it have a anna::time object)
1003 anna::time::functions::setControlPoint(); // start control point (application lifetime)
1005 anna::http::functions::initialize();
1008 CommandLine& commandLine(anna::CommandLine::instantiate());
1010 commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
1011 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)");
1012 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);
1013 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);
1014 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).");
1015 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.");
1016 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");
1017 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.");
1019 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");
1020 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);
1021 commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
1022 commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
1023 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");
1024 commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
1025 commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
1026 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'.");
1027 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");
1028 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);
1029 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);
1030 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");
1031 commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
1032 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");
1033 commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
1034 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");
1035 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");
1036 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");
1037 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");
1038 commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
1039 commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
1040 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);
1041 // commandLine.add("clone", anna::CommandLine::Argument::Optional, "Enables fork mode for request processing", false);
1042 commandLine.initialize(argv, argc);
1043 commandLine.verify();
1044 std::cout << commandLine.asString() << std::endl;
1046 } catch(Exception& ex) {
1047 cout << ex.asString() << endl;
1053 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
1054 a_myDiameterEngine = new MyDiameterEngine();
1055 a_myDiameterEngine->setRealm("ADL.ericsson.com");
1056 a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
1057 //a_myDiameterEngine->setFreezeEndToEndOnSending();
1058 a_logFile = "launcher.log";
1059 a_burstLogFile = "launcher.burst";
1061 a_detailedLog = false;
1062 a_timeEngine = NULL;
1063 a_counterRecorder = NULL;
1064 a_counterRecorderClock = NULL;
1066 a_diameterLocalServer = NULL;
1067 a_cerPathfile = "cer.xml";
1068 a_dwrPathfile = "dwr.xml";
1071 a_burstRepeat = false;
1072 a_burstActive = false;
1073 //a_burstMessages.clear();
1074 a_burstLoadIndx = 0;
1075 a_burstDeliveryIt = a_burstMessages.begin();
1077 a_burstPopCounter = 0;
1080 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
1082 // <CER> ::= < Diameter Header: 257, REQ >
1083 // { Origin-Host } 264 diameterIdentity
1084 // { Origin-Realm } 296 idem
1085 // 1* { Host-IP-Address } 257, address
1086 // { Vendor-Id } 266 Unsigned32
1087 // { Product-Name } 269 UTF8String
1088 // [Origin-State-Id] 278 Unsigned32
1089 // * [ Supported-Vendor-Id ] 265 Unsigned32
1090 // * [ Auth-Application-Id ] 258 Unsigned32
1091 // * [Acct-Application-Id] 259 Unsigned32
1092 anna::diameter::codec::Message diameterCER;
1093 int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1094 std::string OH = a_myDiameterEngine->getHost();
1095 std::string OR = a_myDiameterEngine->getRealm();
1096 std::string hostIP = anna::functions::getHostnameIP(); // Address
1097 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1098 std::string productName = "ANNA Diameter Launcher"; // UTF8String
1099 bool loadingError = false;
1102 diameterCER.loadXML(a_cerPathfile);
1103 } catch(anna::RuntimeException &ex) {
1105 loadingError = true;
1109 LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1110 diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1111 diameterCER.setApplicationId(applicationId);
1112 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1113 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1114 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>"
1115 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1116 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1117 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1121 // <DWR> ::= < Diameter Header: 280, REQ >
1124 anna::diameter::codec::Message diameterDWR;
1125 loadingError = false;
1128 diameterDWR.loadXML(a_dwrPathfile);
1129 } catch(anna::RuntimeException &ex) {
1131 loadingError = true;
1135 LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1136 diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1137 diameterDWR.setApplicationId(applicationId);
1138 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1139 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1142 //////////////////////////
1143 // IDEM FOR CEA AND DWA //
1144 //////////////////////////
1146 // // <CER> ::= < Diameter Header: 257, REQ >
1147 // // { Origin-Host } 264 diameterIdentity
1148 // // { Origin-Realm } 296 idem
1149 // // 1* { Host-IP-Address } 257, address
1150 // // { Vendor-Id } 266 Unsigned32
1151 // // { Product-Name } 269 UTF8String
1152 // // [Origin-State-Id] 278 Unsigned32
1153 // // * [ Supported-Vendor-Id ] 265 Unsigned32
1154 // // * [ Auth-Application-Id ] 258 Unsigned32
1155 // // * [Acct-Application-Id] 259 Unsigned32
1156 // anna::diameter::codec::Message diameterCER;
1157 // int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
1158 // std::string OH = a_myDiameterEngine->getHost();
1159 // std::string OR = a_myDiameterEngine->getRealm();
1160 // std::string hostIP = anna::functions::getHostnameIP(); // Address
1161 // int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1162 // std::string productName = "ANNA Diameter Launcher"; // UTF8String
1163 // bool loadingError = false;
1166 // diameterCER.loadXML("cer.xml");
1167 // } catch (anna::RuntimeException &ex) {
1169 // loadingError = true;
1172 // if (loadingError) {
1173 // LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
1174 // diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
1175 // diameterCER.setApplicationId(applicationId);
1176 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1177 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1178 // 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>"
1179 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1180 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1181 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
1185 // // <DWR> ::= < Diameter Header: 280, REQ >
1186 // // { Origin-Host }
1187 // // { Origin-Realm }
1188 // anna::diameter::codec::Message diameterDWR;
1189 // loadingError = false;
1192 // diameterDWR.loadXML("dwr.xml");
1193 // } catch (anna::RuntimeException &ex) {
1195 // loadingError = true;
1198 // if (loadingError) {
1199 // LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
1200 // diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
1201 // diameterDWR.setApplicationId(applicationId);
1202 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
1203 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
1205 // Assignment for CER/DWR and CEA/DWA:
1206 a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
1207 //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
1210 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
1211 // if (!logEnabled()) return;
1214 try { G_codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
1216 writeLogFile(G_codecMsg, logExtension, detail);
1220 // Si ya lo tengo decodificado:
1221 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
1222 // if (!logEnabled()) return;
1223 // Open target file:
1224 std::string targetFile = a_logFile;
1228 targetFile += logExtension;
1231 ofstream out(targetFile.c_str(), ifstream::out | ifstream::app);
1232 // Set text to dump:
1233 std::string title = "[";
1234 title += logExtension;
1236 // Build complete log:
1237 std::string log = "\n";
1240 anna::time::Date now;
1243 title += now.asString();
1244 log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
1245 log += decodedMessage.asXMLString();
1247 log += anna::functions::highlight("Used resource");
1253 log += decodedMessage.asXMLString();
1258 out.write(log.c_str(), log.size());
1263 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
1264 ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app);
1265 out.write(buffer.c_str(), buffer.size());
1266 out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
1267 // you'd call close() only if you indeed for some reason wanted to close the filestream
1268 // earlier than it goes out of scope.
1272 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
1273 CommandLine& cl(anna::CommandLine::instantiate());
1275 if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory
1277 std::string parameter = cl.getValue(commandLineParameter);
1279 if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
1280 int msecs = cl.getIntegerValue(commandLineParameter);
1282 if(msecs > a_timeEngine->getMaxTimeout()) {
1283 std::string msg = "Commandline parameter '";
1284 msg += commandLineParameter;
1285 msg += "' is greater than allowed max timeout for timming engine: ";
1286 msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
1287 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1290 if(msecs <= a_timeEngine->getResolution()) {
1291 std::string msg = "Commandline parameter '";
1292 msg += commandLineParameter;
1293 msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
1294 msg += anna::functions::asString(a_timeEngine->getResolution());
1295 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1301 // Excepcion (por no ser entero):
1302 std::string msg = "Error at commandline parameter '";
1303 msg += commandLineParameter;
1306 msg += "': must be a non-negative integer number";
1307 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1311 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
1312 if(diameterServerSessions <= 0) return;
1314 std::string address;
1316 CommandLine& cl(anna::CommandLine::instantiate());
1317 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
1318 //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
1319 a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions);
1320 a_diameterLocalServer->setDescription("Launcher diameter local server");
1321 int allowedInactivityTime = 90000; // ms
1323 if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
1325 a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
1329 void Launcher::initialize()
1330 throw(anna::RuntimeException) {
1331 anna::comm::Application::initialize();
1332 CommandLine& cl(anna::CommandLine::instantiate());
1333 anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
1334 // if (cl.exists ("clone"))
1335 // workMode = anna::comm::Communicator::WorkMode::Clone;
1336 a_communicator = new MyCommunicator(workMode);
1337 a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
1338 // Counters record procedure:
1339 anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
1341 if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
1343 if(cntRecordPeriod != 0) {
1344 checkTimeMeasure("cntRecordPeriod");
1345 a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
1346 std::string cntDir = ".";
1348 if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
1350 a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
1354 void Launcher::run()
1355 throw(anna::RuntimeException) {
1356 LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
1357 CommandLine& cl(anna::CommandLine::instantiate());
1359 a_start_time.setNow();
1361 anna::statistics::Engine::instantiate().enable();
1362 ///////////////////////////////
1363 // Diameter library COUNTERS //
1364 ///////////////////////////////
1365 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
1366 oamDiameterComm.initializeCounterScope(1); // 1000 - 1999
1367 anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
1368 oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999
1373 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
1374 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/);
1375 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
1376 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/);
1377 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
1378 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5);
1379 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6);
1380 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7);
1381 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8);
1382 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9);
1383 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10);
1384 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11);
1385 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12);
1386 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13);
1387 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14);
1388 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15);
1389 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16);
1390 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17);
1391 /* Diameter Base (capabilities exchange & keep alive) */
1393 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18);
1394 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19);
1395 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
1396 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21);
1397 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22);
1398 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
1399 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24);
1400 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25);
1401 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
1403 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
1404 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28);
1405 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29);
1406 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
1407 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31);
1408 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32);
1409 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
1410 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34);
1411 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35);
1412 /* server socket operations (enable/disable listening port for any local server) */
1413 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
1414 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
1417 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38);
1418 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39);
1419 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40);
1420 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41);
1421 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42);
1422 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43);
1423 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44);
1424 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45);
1425 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
1427 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47);
1428 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48);
1429 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
1430 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50);
1431 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51);
1432 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52);
1433 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53);
1434 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54);
1435 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55);
1436 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56);
1437 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57);
1438 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 58);
1439 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 59);
1440 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 60);
1445 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/);
1446 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
1447 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/);
1448 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/);
1449 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/);
1450 /* Message decoding */
1451 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
1452 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/);
1453 /* Avp validation */
1454 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
1455 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/);
1456 /* Message validation */
1457 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
1458 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/);
1459 /* Level validation */
1460 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/);
1461 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/);
1462 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/);
1463 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/);
1464 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
1465 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/);
1467 /////////////////////////////////
1468 // Counter recorder associated //
1469 /////////////////////////////////
1470 if(a_counterRecorderClock) {
1471 oamDiameterComm.setCounterRecorder(a_counterRecorder);
1472 oamDiameterCodec.setCounterRecorder(a_counterRecorder);
1473 a_timeEngine->activate(a_counterRecorderClock); // start clock
1476 // Checking command line parameters
1477 if(cl.exists("sessionBasedModelsClientSocketSelection")) {
1478 std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
1480 if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
1481 throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
1486 if(cl.exists("trace"))
1487 anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
1490 // Help on startup traces:
1491 anna::Logger::information(help(), ANNA_FILE_LOCATION);
1492 // Test messages dtd:
1493 std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n";
1494 msg += anna::diameter::codec::MessageDTD;
1495 anna::Logger::information(msg, ANNA_FILE_LOCATION);
1499 if(cl.exists("httpServer")) {
1500 anna::comm::Network& network = anna::comm::Network::instantiate();
1501 std::string address;
1503 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
1504 //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
1505 const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
1506 a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
1510 anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
1511 anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
1512 anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
1513 // Analyze comma-separated list:
1514 anna::Tokenizer lst;
1515 std::string dictionaryParameter = cl.getValue("dictionary");
1516 lst.apply(dictionaryParameter, ",");
1518 if(lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
1519 anna::Tokenizer::const_iterator tok_min(lst.begin());
1520 anna::Tokenizer::const_iterator tok_max(lst.end());
1521 anna::Tokenizer::const_iterator tok_iter;
1522 std::string pathFile;
1525 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1526 pathFile = anna::Tokenizer::data(tok_iter);
1531 codecEngine->setDictionary(d);
1532 LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
1534 if(lst.size() > 1) {
1535 std::string all_in_one = "./dictionary-all-in-one.xml";
1536 std::ofstream out(all_in_one.c_str(), std::ifstream::out);
1537 std::string buffer = d->asXMLString();
1538 out.write(buffer.c_str(), buffer.size());
1540 std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
1545 // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
1546 // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
1547 if(cl.exists("integrationAndDebugging")) {
1548 codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
1549 codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
1552 codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
1555 if(cl.exists("diameterServer"))
1556 startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
1558 // Optional command line parameters ////////////////////////////////////////////////////////
1559 checkTimeMeasure("allowedInactivityTime");
1560 checkTimeMeasure("tcpConnectDelay");
1561 checkTimeMeasure("answersTimeout");
1562 checkTimeMeasure("ceaTimeout");
1563 checkTimeMeasure("watchdogPeriod");
1564 checkTimeMeasure("reconnectionPeriod");
1565 int tcpConnectDelay = 200; // ms
1566 anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
1567 anna::Millisecond ceaTimeout;
1568 anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
1569 int reconnectionPeriod = 10000; // ms
1571 if(cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
1573 if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout");
1575 if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout");
1576 else ceaTimeout = answersTimeout;
1578 if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
1580 if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
1582 a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
1583 a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
1584 std::string originHost = "";
1585 std::string originRealm = "";
1587 if(cl.exists("cer")) a_cerPathfile = cl.getValue("cer");
1589 if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr");
1591 if(cl.exists("originHost")) originHost = cl.getValue("originHost");
1593 if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm");
1595 a_myDiameterEngine->setHost(originHost);
1596 a_myDiameterEngine->setRealm(originRealm);
1599 if(cl.exists("entity")) {
1600 int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
1602 if(entityServerSessions > 0) {
1603 baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
1604 anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
1605 a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
1606 a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity");
1607 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
1608 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
1614 if(cl.exists("log")) a_logFile = cl.getValue("log");
1616 if(cl.exists("splitLog")) a_splitLog = true;
1618 if(cl.exists("detailedLog")) a_detailedLog = true;
1620 if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
1622 // Log statistics concepts
1623 if(cl.exists("logStatisticSamples")) {
1624 std::string list = cl.getValue("logStatisticSamples");
1625 anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
1628 if(statEngine.enableSampleLog(/* -1: all concepts */))
1629 LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
1631 anna::Tokenizer lst;
1632 lst.apply(cl.getValue("logStatisticSamples"), ",");
1634 if(lst.size() >= 1) {
1635 anna::Tokenizer::const_iterator tok_min(lst.begin());
1636 anna::Tokenizer::const_iterator tok_max(lst.end());
1637 anna::Tokenizer::const_iterator tok_iter;
1640 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1641 conceptId = atoi(anna::Tokenizer::data(tok_iter));
1643 if(statEngine.enableSampleLog(conceptId))
1644 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
1650 a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
1652 if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
1654 a_communicator->accept();
1657 void MyCommunicator::eventBreakConnection(Server* server)
1659 LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION));
1661 anna::comm::Communicator::eventBreakConnection(server);
1664 void MyCommunicator::terminate()
1666 if(hasRequestedStop() == true)
1672 void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request)
1673 throw(anna::RuntimeException) {
1674 const anna::DataBlock& body = request.getBody();
1676 if(body.getSize() == 0)
1677 throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION);
1680 string msg("Received body: ");
1681 msg += anna::functions::asString(body);
1682 anna::Logger::information(msg, ANNA_FILE_LOCATION);
1684 std::string body_content;
1685 body_content.assign(body.getData(), body.getSize());
1687 std::string response_content;
1690 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1691 my_app.eventOperation(body_content, response_content);
1692 } catch(RuntimeException &ex) {
1696 anna::http::Response* response = allocateResponse();
1697 response->setStatusCode(200); // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1698 anna::DataBlock db_content(true);
1699 db_content = response_content;
1700 response->setBody(db_content);
1701 // response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT");
1702 // anna::http::Header* keepAlive = response->find("Keep-Alive");
1704 // if (keepAlive == NULL)
1705 // keepAlive = response->createHeader("Keep-Alive");
1707 // keepAlive->setValue("Verificacion del cambio 1.0.7");
1710 clientSocket.send(*response);
1711 } catch(Exception& ex) {
1716 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1717 LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1718 CommandLine& cl(anna::CommandLine::instantiate());
1719 LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1720 response_content = "Operation processed with exception. See traces\n"; // supposed
1721 std::string result = "";
1722 anna::DataBlock db_aux(true);
1724 ///////////////////////////////////////////////////////////////////
1725 // Simple operations without arguments:
1728 if(operation == "help") {
1729 std::string s_help = help();
1730 std::cout << s_help << std::endl;
1731 LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1732 response_content = "Help dumped on stdout and information-level traces (launcher.traces file)\n";
1736 // Reset performance data:
1737 if(operation == "collect") {
1740 response_content = "All process counters & statistic information have been reset\n";
1744 ///////////////////////////////////////////////////////////////////
1745 // Tokenize operation
1747 params.apply(operation, "|");
1748 int numParams = params.size() - 1;
1750 // No operation has more than 2 arguments ...
1752 LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1753 throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1756 // Get the operation type:
1757 Tokenizer::const_iterator tok_iter = params.begin();
1758 std::string opType = Tokenizer::data(tok_iter);
1759 // Check the number of parameters:
1760 bool wrongBody = false;
1762 if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1764 if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1766 if((opType == "burst") && (numParams < 1)) wrongBody = true;
1768 if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1772 std::string msg = "Wrong body content format on HTTP Request for '";
1774 msg += "' operation (missing parameter/s)";
1775 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1779 std::string param1, param2;
1781 if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1783 if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1786 if(opType == "code") {
1787 G_codecMsg.loadXML(param1);
1788 std::string hexString = anna::functions::asHexString(G_codecMsg.code());
1790 ofstream outfile(param2.c_str(), ifstream::out);
1791 outfile.write(hexString.c_str(), hexString.size());
1793 } else if(opType == "decode") {
1794 // Get DataBlock from file with hex content:
1795 if(!getDataBlockFromHexFile(param1, db_aux))
1796 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1799 try { G_codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1801 std::string xmlString = G_codecMsg.asXMLString();
1803 ofstream outfile(param2.c_str(), ifstream::out);
1804 outfile.write(xmlString.c_str(), xmlString.size());
1806 } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1807 anna::diameter::comm::Entity *entity = getEntity();
1809 if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1813 std::string key = param1;
1817 if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1819 if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1821 if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1823 if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1825 std::string address;
1827 anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1829 if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1831 if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1833 if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1835 if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1838 if(opType == "hide") entity->hide();
1840 if(opType == "show") entity->show();
1842 if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1844 if(opType == "shown") result = entity->shown() ? "true" : "false";
1846 } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1847 anna::diameter::comm::Entity *entity = getEntity();
1849 if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1851 if((opType == "sendxml") || (opType == "sendxml2e")) {
1852 G_codecMsg.loadXML(param1);
1853 G_commMsgSent2e.clearBody();
1854 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)
1856 G_commMsgSent2e.setBody(G_codecMsg.code());
1858 // Get DataBlock from file with hex content:
1859 if(!getDataBlockFromHexFile(param1, db_aux))
1860 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1862 G_commMsgSent2e.setBody(db_aux);
1865 bool success = entity->send(G_commMsgSent2e, cl.exists("balance"));
1869 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1870 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1871 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1872 writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
1874 } else if((opType == "burst")) {
1875 anna::diameter::comm::Entity *entity = getEntity();
1877 if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1879 // burst|clear clears all loaded burst messages.
1880 // burst|load|<source_file> loads the next diameter message into launcher burst.
1881 // burst|start|<initial load> starts the message sending with a certain initial load.
1882 // burst|push|<load amount> sends specific non-aynchronous load.
1883 // burst|stop stops the burst cycle.
1884 // burst|repeat|[[yes]|no] restarts the burst launch when finish.
1885 // burst|send|<amount> send messages from burst list. The main difference with
1886 // start/push operations is that burst won't be awaken.
1887 // Externally we could control sending time (no request
1888 // will be sent for answers).
1889 // burst|goto|<order> Updates current burst pointer position.
1890 // burst|look|<order> Show programmed burst message for order provided.
1892 if(param1 == "clear") {
1893 result = "Removed ";
1894 result += anna::functions::asString(clearBurst());
1895 result += " elements.";
1896 } else if(param1 == "load") {
1897 if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1899 G_codecMsg.loadXML(param2);
1901 if(G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1902 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)
1904 int position = loadBurstMessage(G_codecMsg.code());
1905 result = "Loaded '";
1907 result += "' file into burst list position ";
1908 result += anna::functions::asString(position);
1909 } else if(param1 == "start") {
1910 if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1912 int initialLoad = atoi(param2.c_str());
1913 int processed = startBurst(initialLoad);
1916 result = "Initial load completed for ";
1917 result += anna::functions::entriesAsString(processed, "message");
1920 } else if(param1 == "push") {
1921 if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1923 int pushed = pushBurst(atoi(param2.c_str()));
1927 result += anna::functions::entriesAsString(pushed, "message");
1930 } else if(param1 == "pop") {
1931 if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1933 int releaseLoad = atoi(param2.c_str());
1934 int popped = popBurst(releaseLoad);
1937 result = "Burst popped for ";
1938 result += anna::functions::entriesAsString(popped, "message");
1941 } else if(param1 == "stop") {
1942 int left = stopBurst();
1945 result += anna::functions::entriesAsString(left, "message");
1946 result += " left to the end of the cycle.";
1948 } else if(param1 == "repeat") {
1949 if(param2 == "") param2 = "yes";
1951 bool repeat = (param2 == "yes");
1952 repeatBurst(repeat);
1953 result += (repeat ? "Mode on." : "Mode off.");
1954 } else if(param1 == "send") {
1955 if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1957 int sent = sendBurst(atoi(param2.c_str()));
1961 result += anna::functions::entriesAsString(sent, "message");
1964 } else if(param1 == "goto") {
1965 if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1967 result = gotoBurst(atoi(param2.c_str()));
1969 } else if(param1 == "look") {
1970 if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1973 result += lookBurst(atoi(param2.c_str()));
1976 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1978 } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1979 anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
1981 if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1983 if(opType == "sendxml2c") {
1984 G_codecMsg.loadXML(param1);
1985 G_commMsgSent2c.clearBody();
1986 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)
1988 G_commMsgSent2c.setBody(G_codecMsg.code());
1990 // Get DataBlock from file with hex content:
1991 if(!getDataBlockFromHexFile(param1, db_aux))
1992 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1994 G_commMsgSent2c.setBody(db_aux);
1997 bool success = localServer->send(G_commMsgSent2c);
2001 anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2002 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2003 writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
2005 } else if(opType == "loadxml") {
2006 G_codecMsg.loadXML(param1);
2007 std::string xmlString = G_codecMsg.asXMLString();
2008 std::cout << xmlString << std::endl;
2009 } else if(opType == "diameterServerSessions") {
2010 int diameterServerSessions = atoi(param1.c_str());
2012 if(!getDiameterLocalServer())
2013 startDiameterServer(diameterServerSessions);
2015 getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
2016 } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2017 anna::diameter::comm::LocalServer *localServer = getDiameterLocalServer();
2020 throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
2023 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2024 anna::diameter::codec::Message *message = engine->createMessage(param1);
2027 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2030 if(message->isRequest())
2031 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2033 int code = message->getId().first;
2034 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the deque...", ANNA_FILE_LOCATION));
2035 G_reactingAnswers2C.addMessage(code, message);
2036 } else { // answers query on stdout
2037 std::cout << std::endl << std::endl;
2038 std::cout << " ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n";
2039 std::cout << G_reactingAnswers2C.asString() << std::endl;
2040 response_content = "Programmed answers dumped on stdout\n";
2043 } else if(opType == "answerxml2e") {
2044 anna::diameter::comm::Entity *entity = getEntity();
2047 throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
2050 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
2051 anna::diameter::codec::Message *message = engine->createMessage(param1);
2054 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
2057 if(message->isRequest())
2058 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
2060 int code = message->getId().first;
2061 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the deque...", ANNA_FILE_LOCATION));
2062 G_reactingAnswers2E.addMessage(code, message);
2063 } else { // answers query on stdout
2064 std::cout << std::endl << std::endl;
2065 std::cout << " ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n";
2066 std::cout << G_reactingAnswers2E.asString() << std::endl;
2067 response_content = "Programmed answers dumped on stdout\n";
2071 LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
2072 throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
2076 response_content = "Operation processed; ";
2078 if((opType == "decode") || (opType == "code")) {
2079 response_content += "File '";
2080 response_content += param2;
2081 response_content += "' created.";
2082 response_content += "\n";
2083 } else if((opType == "hide") || (opType == "show")) {
2084 response_content += "Resource '";
2085 response_content += ((param1 != "") ? param1 : "Entity");
2088 response_content += "|";
2089 response_content += param2;
2092 response_content += "' ";
2094 if(opType == "hide") response_content += "has been hidden.";
2096 if(opType == "show") response_content += "has been shown.";
2098 response_content += "\n";
2099 } else if((opType == "hidden") || (opType == "shown")) {
2100 response_content += "Result: ";
2101 response_content += result;
2102 response_content += "\n";
2103 } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
2104 response_content += "Message '";
2105 response_content += param1;
2106 response_content += "' sent to entity.";
2107 response_content += "\n";
2108 } else if(opType == "burst") {
2109 response_content += "Burst '";
2110 response_content += param1;
2111 response_content += "' executed. ";
2112 response_content += result;
2113 response_content += "\n";
2114 } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
2115 response_content += "Message '";
2116 response_content += param1;
2117 response_content += "' sent to client.";
2118 response_content += "\n";
2119 } else if(opType == "loadxml") {
2120 response_content += "Message '";
2121 response_content += param1;
2122 response_content += "' loaded.";
2123 response_content += "\n";
2124 } else if((opType == "answerxml") || (opType == "answerxml2c")) {
2125 response_content += "Answer to client '";
2126 response_content += param1;
2127 response_content += "' programmed.";
2128 response_content += "\n";
2129 } else if(opType == "answerxml2e") {
2130 response_content += "Answer to entity '";
2131 response_content += param1;
2132 response_content += "' programmed.";
2133 response_content += "\n";
2134 } else if(opType == "diameterServerSessions") {
2135 response_content += "Maximum server socket connections updated to '";
2136 response_content += param1;
2137 response_content += "'.";
2138 response_content += "\n";
2143 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
2144 CommandLine& cl(anna::CommandLine::instantiate());
2145 std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
2147 if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
2150 // Service-Context-Id:
2151 anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
2152 std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
2154 switch(chargingContext) {
2155 case anna::diameter::helpers::dcca::ChargingContext::Data:
2156 case anna::diameter::helpers::dcca::ChargingContext::Voice:
2157 case anna::diameter::helpers::dcca::ChargingContext::Content: {
2158 // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
2159 std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
2160 std::string diameterIdentity, optional;
2161 anna::U32 high, low;
2162 anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
2164 if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
2166 if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
2168 if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
2170 //case anna::diameter::helpers::dcca::ChargingContext::SMS:
2171 //case anna::diameter::helpers::dcca::ChargingContext::MMS:
2173 // return -1; // IEC model and Unknown traffic types
2175 } catch(anna::RuntimeException &ex) {
2177 std::string msg = ex.getText();
2178 msg += " | Round-robin between sessions will be used to send";
2179 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2187 void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2188 throw(anna::RuntimeException) {
2189 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
2190 // Performance stats:
2191 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2192 CommandLine& cl(anna::CommandLine::instantiate());
2194 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2197 std::string msg = "Request received: ";
2198 msg += anna::diameter::functions::commandIdAsPairString(cid);
2199 msg += " | DiameterServer: ";
2200 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2201 msg += " | EventTime: ";
2202 msg += anna::time::functions::currentTimeAsString();
2203 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2207 if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
2209 // Lookup reacting answers list:
2210 int code = cid.first;
2211 anna::diameter::codec::Message *answer_message = G_reactingAnswers2E.getMessage(code);
2212 if (answer_message) {
2214 my_app.getCommunicator()->prepareAnswer(answer_message, message);
2217 G_commMsgSent2e.setBody(answer_message->code());
2218 /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
2220 if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
2221 } catch(anna::RuntimeException &ex) {
2224 if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
2227 // Pop front the reacting answer:
2228 G_reactingAnswers2E.nextMessage(code);
2234 std::string msg = "No answers programmed (maybe sold out) for request coming from entity: ";
2235 msg += anna::diameter::functions::commandIdAsPairString(cid);
2236 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2239 // not found: forward to client (if exists)
2240 // Forward to client:
2241 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2243 if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
2245 anna::diameter::comm::Message *msg = G_commMessages.create();
2246 msg->setBody(message);
2247 msg->setRequestClientSessionKey(clientSession->getKey());
2248 bool success = localServer->send(msg);
2251 if(my_app.logEnabled()) {
2252 anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
2253 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2254 my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
2256 } catch(anna::RuntimeException &ex) {
2263 void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response)
2264 throw(anna::RuntimeException) {
2265 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
2266 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2267 CommandLine& cl(anna::CommandLine::instantiate());
2268 anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2269 anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2270 anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2271 const anna::DataBlock* message = response.getMessage();
2272 const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(response.getSession());
2273 bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2274 bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2275 bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2276 bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2277 bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2279 anna::diameter::CommandId request_cid = request->getCommandId();
2282 std::string msg = "Response received for original diameter request: ";
2283 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2284 msg += " | Response: ";
2285 msg += response.asString();
2286 msg += " | DiameterServer: ";
2287 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2288 msg += " | EventTime: ";
2289 msg += anna::time::functions::currentTimeAsString();
2290 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2294 //if (isApplicationMessage)
2295 LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION));
2298 if(contextExpired) {
2299 //if (isApplicationMessage)
2300 LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
2302 if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2303 if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString());
2309 std::string msg = "Received response for diameter message: ";
2310 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2311 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2314 bool alreadyDecodedOnG_codecMsg = false;
2316 if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2317 if(my_app.logEnabled()) {
2318 my_app.writeLogFile(*message, "recvfe", clientSession->asString());
2319 alreadyDecodedOnG_codecMsg = true;
2323 // Forward to client:
2324 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2326 if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
2328 G_commMsgFwd2c.setBody(*message);
2329 bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey());
2330 G_commMessages.release(request);
2332 anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
2333 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2335 if(my_app.logEnabled()) {
2336 if(alreadyDecodedOnG_codecMsg)
2337 my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail);
2339 my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
2341 } catch(anna::RuntimeException &ex) {
2347 // Triggering burst:
2348 if(isOK || contextExpired) my_app.sendBurstMessage();
2352 void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2353 throw(anna::RuntimeException) {
2354 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
2355 // Performance stats:
2356 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2358 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2361 std::string msg = "Out-of-context response received from entity: ";
2362 msg += anna::diameter::functions::commandIdAsPairString(cid);
2363 msg += " | DiameterServer: ";
2364 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2365 msg += " | EventTime: ";
2366 msg += anna::time::functions::currentTimeAsString();
2367 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2371 if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
2377 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2378 throw(anna::RuntimeException) {
2379 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
2380 // Performance stats:
2381 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2382 CommandLine& cl(anna::CommandLine::instantiate());
2384 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2387 std::string msg = "Request received: ";
2388 msg += anna::diameter::functions::commandIdAsPairString(cid);
2389 msg += " | DiameterServer: ";
2390 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2391 msg += " | EventTime: ";
2392 msg += anna::time::functions::currentTimeAsString();
2393 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2397 if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2399 // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
2400 int code = cid.first;
2401 anna::diameter::codec::Message *programmed_answer = G_reactingAnswers2C.getMessage(code);
2402 bool programmed = (programmed_answer != NULL);
2404 anna::diameter::comm::Entity *entity = my_app.getEntity();
2405 if(!programmed && entity) { // forward condition (no programmed answer + entity available)
2406 anna::diameter::comm::Message *msg = G_commMessages.create();
2407 msg->setBody(message);
2408 msg->setRequestServerSessionKey(serverSession->getKey());
2409 bool success = entity->send(msg, cl.exists("balance"));
2412 if(my_app.logEnabled()) {
2413 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
2414 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
2415 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2416 my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
2423 bool analysisOK = true; // by default
2424 anna::diameter::codec::Message *answer_message = NULL;
2426 if(!cl.exists("ignoreErrors")) { // Error analysis
2427 answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg;
2428 answer_message->clear();
2431 try { G_codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); }
2433 answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
2434 analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
2437 // Programmed answer only when all is ok
2440 answer_message = programmed_answer;
2442 my_app.getCommunicator()->prepareAnswer(answer_message, message);
2443 } else return; // nothing done
2446 anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION));
2447 anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
2450 codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
2453 G_commMsgSent2c.setBody(answer_message->code());
2454 /* response = NULL =*/serverSession->send(&G_commMsgSent2c);
2456 if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
2457 } catch(anna::RuntimeException &ex) {
2460 if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
2463 // Restore validation mode
2464 codecEngine->setValidationMode(backupVM);
2466 // Pop front the reacting answer:
2467 if(analysisOK && programmed) G_reactingAnswers2C.nextMessage(code);
2470 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
2471 throw(anna::RuntimeException) {
2472 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
2473 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2474 CommandLine& cl(anna::CommandLine::instantiate());
2475 anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2476 anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2477 anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2478 const anna::DataBlock* message = response.getMessage();
2479 const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
2480 bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2481 bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2482 bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2483 bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2484 bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2486 anna::diameter::CommandId request_cid = request->getCommandId();
2489 std::string msg = "Response received for original diameter request: ";
2490 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2491 msg += " | Response: ";
2492 msg += response.asString();
2493 msg += " | LocalServer: ";
2494 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2495 msg += " | EventTime: ";
2496 msg += anna::time::functions::currentTimeAsString();
2497 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2501 //if (isApplicationMessage)
2502 LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
2505 if(contextExpired) {
2506 //if (isApplicationMessage)
2507 LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
2509 if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2510 if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString());
2516 std::string msg = "Received response for diameter message: ";
2517 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2518 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2522 if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString());
2524 // This is not very usual, but answers could arrive from clients:
2525 anna::diameter::comm::Entity *entity = my_app.getEntity();
2528 anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
2531 if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2534 G_commMsgFwd2e.setBody(*message);
2537 if(usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e);
2540 //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey());
2541 //bool success = entity->send(G_commMsgFwd2e);
2542 G_commMessages.release(request);
2544 if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded
2545 } catch(anna::RuntimeException &ex) {
2548 if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded
2554 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2555 throw(anna::RuntimeException) {
2556 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
2557 // Performance stats:
2558 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2560 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2563 std::string msg = "Out-of-context response received from client: ";
2564 msg += anna::diameter::functions::commandIdAsPairString(cid);
2565 msg += " | DiameterServer: ";
2566 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2567 msg += " | EventTime: ";
2568 msg += anna::time::functions::currentTimeAsString();
2569 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2572 if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
2576 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2578 anna::xml::Node* result = parent->createChild("launcher");
2579 anna::comm::Application::asXML(result);
2581 result->createAttribute("StartTime", a_start_time.asString());
2582 result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2584 (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
2586 anna::diameter::comm::OamModule::instantiate().asXML(result);
2587 anna::diameter::codec::OamModule::instantiate().asXML(result);
2589 anna::statistics::Engine::instantiate().asXML(result);